repo
stringlengths 7
55
| path
stringlengths 4
223
| func_name
stringlengths 1
134
| original_string
stringlengths 75
104k
| language
stringclasses 1
value | code
stringlengths 75
104k
| code_tokens
listlengths 19
28.4k
| docstring
stringlengths 1
46.9k
| docstring_tokens
listlengths 1
1.97k
| sha
stringlengths 40
40
| url
stringlengths 87
315
| partition
stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
opennode/waldur-core
|
waldur_core/logging/views.py
|
AlertViewSet.create
|
def create(self, request, *args, **kwargs):
"""
Run **POST** against */api/alerts/* to create or update alert. If alert with posted scope and
alert_type already exists - it will be updated. Only users with staff privileges can create alerts.
Request example:
.. code-block:: javascript
POST /api/alerts/
Accept: application/json
Content-Type: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"scope": "http://testserver/api/projects/b9e8a102b5ff4469b9ac03253fae4b95/",
"message": "message#1",
"alert_type": "first_alert",
"severity": "Debug"
}
"""
return super(AlertViewSet, self).create(request, *args, **kwargs)
|
python
|
def create(self, request, *args, **kwargs):
"""
Run **POST** against */api/alerts/* to create or update alert. If alert with posted scope and
alert_type already exists - it will be updated. Only users with staff privileges can create alerts.
Request example:
.. code-block:: javascript
POST /api/alerts/
Accept: application/json
Content-Type: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"scope": "http://testserver/api/projects/b9e8a102b5ff4469b9ac03253fae4b95/",
"message": "message#1",
"alert_type": "first_alert",
"severity": "Debug"
}
"""
return super(AlertViewSet, self).create(request, *args, **kwargs)
|
[
"def",
"create",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"AlertViewSet",
",",
"self",
")",
".",
"create",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
Run **POST** against */api/alerts/* to create or update alert. If alert with posted scope and
alert_type already exists - it will be updated. Only users with staff privileges can create alerts.
Request example:
.. code-block:: javascript
POST /api/alerts/
Accept: application/json
Content-Type: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"scope": "http://testserver/api/projects/b9e8a102b5ff4469b9ac03253fae4b95/",
"message": "message#1",
"alert_type": "first_alert",
"severity": "Debug"
}
|
[
"Run",
"**",
"POST",
"**",
"against",
"*",
"/",
"api",
"/",
"alerts",
"/",
"*",
"to",
"create",
"or",
"update",
"alert",
".",
"If",
"alert",
"with",
"posted",
"scope",
"and",
"alert_type",
"already",
"exists",
"-",
"it",
"will",
"be",
"updated",
".",
"Only",
"users",
"with",
"staff",
"privileges",
"can",
"create",
"alerts",
"."
] |
d6c17a9592bb6c49c33567542eef8d099605a46a
|
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/logging/views.py#L232-L254
|
train
|
opennode/waldur-core
|
waldur_core/logging/views.py
|
AlertViewSet.close
|
def close(self, request, *args, **kwargs):
"""
To close alert - run **POST** against */api/alerts/<alert_uuid>/close/*. No data is required.
Only users with staff privileges can close alerts.
"""
if not request.user.is_staff:
raise PermissionDenied()
alert = self.get_object()
alert.close()
return response.Response(status=status.HTTP_204_NO_CONTENT)
|
python
|
def close(self, request, *args, **kwargs):
"""
To close alert - run **POST** against */api/alerts/<alert_uuid>/close/*. No data is required.
Only users with staff privileges can close alerts.
"""
if not request.user.is_staff:
raise PermissionDenied()
alert = self.get_object()
alert.close()
return response.Response(status=status.HTTP_204_NO_CONTENT)
|
[
"def",
"close",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"request",
".",
"user",
".",
"is_staff",
":",
"raise",
"PermissionDenied",
"(",
")",
"alert",
"=",
"self",
".",
"get_object",
"(",
")",
"alert",
".",
"close",
"(",
")",
"return",
"response",
".",
"Response",
"(",
"status",
"=",
"status",
".",
"HTTP_204_NO_CONTENT",
")"
] |
To close alert - run **POST** against */api/alerts/<alert_uuid>/close/*. No data is required.
Only users with staff privileges can close alerts.
|
[
"To",
"close",
"alert",
"-",
"run",
"**",
"POST",
"**",
"against",
"*",
"/",
"api",
"/",
"alerts",
"/",
"<alert_uuid",
">",
"/",
"close",
"/",
"*",
".",
"No",
"data",
"is",
"required",
".",
"Only",
"users",
"with",
"staff",
"privileges",
"can",
"close",
"alerts",
"."
] |
d6c17a9592bb6c49c33567542eef8d099605a46a
|
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/logging/views.py#L257-L267
|
train
|
opennode/waldur-core
|
waldur_core/logging/views.py
|
AlertViewSet.acknowledge
|
def acknowledge(self, request, *args, **kwargs):
"""
To acknowledge alert - run **POST** against */api/alerts/<alert_uuid>/acknowledge/*. No payload is required.
All users that can see alerts can also acknowledge it. If alert is already acknowledged endpoint
will return error with code 409(conflict).
"""
alert = self.get_object()
if not alert.acknowledged:
alert.acknowledge()
return response.Response(status=status.HTTP_200_OK)
else:
return response.Response({'detail': _('Alert is already acknowledged.')}, status=status.HTTP_409_CONFLICT)
|
python
|
def acknowledge(self, request, *args, **kwargs):
"""
To acknowledge alert - run **POST** against */api/alerts/<alert_uuid>/acknowledge/*. No payload is required.
All users that can see alerts can also acknowledge it. If alert is already acknowledged endpoint
will return error with code 409(conflict).
"""
alert = self.get_object()
if not alert.acknowledged:
alert.acknowledge()
return response.Response(status=status.HTTP_200_OK)
else:
return response.Response({'detail': _('Alert is already acknowledged.')}, status=status.HTTP_409_CONFLICT)
|
[
"def",
"acknowledge",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"alert",
"=",
"self",
".",
"get_object",
"(",
")",
"if",
"not",
"alert",
".",
"acknowledged",
":",
"alert",
".",
"acknowledge",
"(",
")",
"return",
"response",
".",
"Response",
"(",
"status",
"=",
"status",
".",
"HTTP_200_OK",
")",
"else",
":",
"return",
"response",
".",
"Response",
"(",
"{",
"'detail'",
":",
"_",
"(",
"'Alert is already acknowledged.'",
")",
"}",
",",
"status",
"=",
"status",
".",
"HTTP_409_CONFLICT",
")"
] |
To acknowledge alert - run **POST** against */api/alerts/<alert_uuid>/acknowledge/*. No payload is required.
All users that can see alerts can also acknowledge it. If alert is already acknowledged endpoint
will return error with code 409(conflict).
|
[
"To",
"acknowledge",
"alert",
"-",
"run",
"**",
"POST",
"**",
"against",
"*",
"/",
"api",
"/",
"alerts",
"/",
"<alert_uuid",
">",
"/",
"acknowledge",
"/",
"*",
".",
"No",
"payload",
"is",
"required",
".",
"All",
"users",
"that",
"can",
"see",
"alerts",
"can",
"also",
"acknowledge",
"it",
".",
"If",
"alert",
"is",
"already",
"acknowledged",
"endpoint",
"will",
"return",
"error",
"with",
"code",
"409",
"(",
"conflict",
")",
"."
] |
d6c17a9592bb6c49c33567542eef8d099605a46a
|
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/logging/views.py#L270-L281
|
train
|
opennode/waldur-core
|
waldur_core/logging/views.py
|
AlertViewSet.stats
|
def stats(self, request, *args, **kwargs):
"""
To get count of alerts per severities - run **GET** request against */api/alerts/stats/*.
This endpoint supports all filters that are available for alerts list (*/api/alerts/*).
Response example:
.. code-block:: javascript
{
"debug": 2,
"error": 1,
"info": 1,
"warning": 1
}
"""
queryset = self.filter_queryset(self.get_queryset())
alerts_severities_count = queryset.values('severity').annotate(count=Count('severity'))
severity_names = dict(models.Alert.SeverityChoices.CHOICES)
# For consistency with all other endpoint we need to return severity names in lower case.
alerts_severities_count = {
severity_names[asc['severity']].lower(): asc['count'] for asc in alerts_severities_count}
for severity_name in severity_names.values():
if severity_name.lower() not in alerts_severities_count:
alerts_severities_count[severity_name.lower()] = 0
return response.Response(alerts_severities_count, status=status.HTTP_200_OK)
|
python
|
def stats(self, request, *args, **kwargs):
"""
To get count of alerts per severities - run **GET** request against */api/alerts/stats/*.
This endpoint supports all filters that are available for alerts list (*/api/alerts/*).
Response example:
.. code-block:: javascript
{
"debug": 2,
"error": 1,
"info": 1,
"warning": 1
}
"""
queryset = self.filter_queryset(self.get_queryset())
alerts_severities_count = queryset.values('severity').annotate(count=Count('severity'))
severity_names = dict(models.Alert.SeverityChoices.CHOICES)
# For consistency with all other endpoint we need to return severity names in lower case.
alerts_severities_count = {
severity_names[asc['severity']].lower(): asc['count'] for asc in alerts_severities_count}
for severity_name in severity_names.values():
if severity_name.lower() not in alerts_severities_count:
alerts_severities_count[severity_name.lower()] = 0
return response.Response(alerts_severities_count, status=status.HTTP_200_OK)
|
[
"def",
"stats",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"queryset",
"=",
"self",
".",
"filter_queryset",
"(",
"self",
".",
"get_queryset",
"(",
")",
")",
"alerts_severities_count",
"=",
"queryset",
".",
"values",
"(",
"'severity'",
")",
".",
"annotate",
"(",
"count",
"=",
"Count",
"(",
"'severity'",
")",
")",
"severity_names",
"=",
"dict",
"(",
"models",
".",
"Alert",
".",
"SeverityChoices",
".",
"CHOICES",
")",
"# For consistency with all other endpoint we need to return severity names in lower case.",
"alerts_severities_count",
"=",
"{",
"severity_names",
"[",
"asc",
"[",
"'severity'",
"]",
"]",
".",
"lower",
"(",
")",
":",
"asc",
"[",
"'count'",
"]",
"for",
"asc",
"in",
"alerts_severities_count",
"}",
"for",
"severity_name",
"in",
"severity_names",
".",
"values",
"(",
")",
":",
"if",
"severity_name",
".",
"lower",
"(",
")",
"not",
"in",
"alerts_severities_count",
":",
"alerts_severities_count",
"[",
"severity_name",
".",
"lower",
"(",
")",
"]",
"=",
"0",
"return",
"response",
".",
"Response",
"(",
"alerts_severities_count",
",",
"status",
"=",
"status",
".",
"HTTP_200_OK",
")"
] |
To get count of alerts per severities - run **GET** request against */api/alerts/stats/*.
This endpoint supports all filters that are available for alerts list (*/api/alerts/*).
Response example:
.. code-block:: javascript
{
"debug": 2,
"error": 1,
"info": 1,
"warning": 1
}
|
[
"To",
"get",
"count",
"of",
"alerts",
"per",
"severities",
"-",
"run",
"**",
"GET",
"**",
"request",
"against",
"*",
"/",
"api",
"/",
"alerts",
"/",
"stats",
"/",
"*",
".",
"This",
"endpoint",
"supports",
"all",
"filters",
"that",
"are",
"available",
"for",
"alerts",
"list",
"(",
"*",
"/",
"api",
"/",
"alerts",
"/",
"*",
")",
"."
] |
d6c17a9592bb6c49c33567542eef8d099605a46a
|
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/logging/views.py#L298-L325
|
train
|
opennode/waldur-core
|
waldur_core/logging/views.py
|
WebHookViewSet.create
|
def create(self, request, *args, **kwargs):
"""
To create new web hook issue **POST** against */api/hooks-web/* as an authenticated user.
You should specify list of event_types or event_groups.
Example of a request:
.. code-block:: http
POST /api/hooks-web/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"event_types": ["resource_start_succeeded"],
"event_groups": ["users"],
"destination_url": "http://example.com/"
}
When hook is activated, **POST** request is issued against destination URL with the following data:
.. code-block:: javascript
{
"timestamp": "2015-07-14T12:12:56.000000",
"message": "Customer ABC LLC has been updated.",
"type": "customer_update_succeeded",
"context": {
"user_native_name": "Walter Lebrowski",
"customer_contact_details": "",
"user_username": "Walter",
"user_uuid": "1c3323fc4ae44120b57ec40dea1be6e6",
"customer_uuid": "4633bbbb0b3a4b91bffc0e18f853de85",
"ip_address": "8.8.8.8",
"user_full_name": "Walter Lebrowski",
"customer_abbreviation": "ABC LLC",
"customer_name": "ABC LLC"
},
"levelname": "INFO"
}
Note that context depends on event type.
"""
return super(WebHookViewSet, self).create(request, *args, **kwargs)
|
python
|
def create(self, request, *args, **kwargs):
"""
To create new web hook issue **POST** against */api/hooks-web/* as an authenticated user.
You should specify list of event_types or event_groups.
Example of a request:
.. code-block:: http
POST /api/hooks-web/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"event_types": ["resource_start_succeeded"],
"event_groups": ["users"],
"destination_url": "http://example.com/"
}
When hook is activated, **POST** request is issued against destination URL with the following data:
.. code-block:: javascript
{
"timestamp": "2015-07-14T12:12:56.000000",
"message": "Customer ABC LLC has been updated.",
"type": "customer_update_succeeded",
"context": {
"user_native_name": "Walter Lebrowski",
"customer_contact_details": "",
"user_username": "Walter",
"user_uuid": "1c3323fc4ae44120b57ec40dea1be6e6",
"customer_uuid": "4633bbbb0b3a4b91bffc0e18f853de85",
"ip_address": "8.8.8.8",
"user_full_name": "Walter Lebrowski",
"customer_abbreviation": "ABC LLC",
"customer_name": "ABC LLC"
},
"levelname": "INFO"
}
Note that context depends on event type.
"""
return super(WebHookViewSet, self).create(request, *args, **kwargs)
|
[
"def",
"create",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"WebHookViewSet",
",",
"self",
")",
".",
"create",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
To create new web hook issue **POST** against */api/hooks-web/* as an authenticated user.
You should specify list of event_types or event_groups.
Example of a request:
.. code-block:: http
POST /api/hooks-web/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"event_types": ["resource_start_succeeded"],
"event_groups": ["users"],
"destination_url": "http://example.com/"
}
When hook is activated, **POST** request is issued against destination URL with the following data:
.. code-block:: javascript
{
"timestamp": "2015-07-14T12:12:56.000000",
"message": "Customer ABC LLC has been updated.",
"type": "customer_update_succeeded",
"context": {
"user_native_name": "Walter Lebrowski",
"customer_contact_details": "",
"user_username": "Walter",
"user_uuid": "1c3323fc4ae44120b57ec40dea1be6e6",
"customer_uuid": "4633bbbb0b3a4b91bffc0e18f853de85",
"ip_address": "8.8.8.8",
"user_full_name": "Walter Lebrowski",
"customer_abbreviation": "ABC LLC",
"customer_name": "ABC LLC"
},
"levelname": "INFO"
}
Note that context depends on event type.
|
[
"To",
"create",
"new",
"web",
"hook",
"issue",
"**",
"POST",
"**",
"against",
"*",
"/",
"api",
"/",
"hooks",
"-",
"web",
"/",
"*",
"as",
"an",
"authenticated",
"user",
".",
"You",
"should",
"specify",
"list",
"of",
"event_types",
"or",
"event_groups",
"."
] |
d6c17a9592bb6c49c33567542eef8d099605a46a
|
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/logging/views.py#L356-L401
|
train
|
opennode/waldur-core
|
waldur_core/logging/views.py
|
EmailHookViewSet.create
|
def create(self, request, *args, **kwargs):
"""
To create new email hook issue **POST** against */api/hooks-email/* as an authenticated user.
You should specify list of event_types or event_groups.
Example of a request:
.. code-block:: http
POST /api/hooks-email/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"event_types": ["openstack_instance_start_succeeded"],
"event_groups": ["users"],
"email": "test@example.com"
}
You may temporarily disable hook without deleting it by issuing following **PATCH** request against hook URL:
.. code-block:: javascript
{
"is_active": "false"
}
"""
return super(EmailHookViewSet, self).create(request, *args, **kwargs)
|
python
|
def create(self, request, *args, **kwargs):
"""
To create new email hook issue **POST** against */api/hooks-email/* as an authenticated user.
You should specify list of event_types or event_groups.
Example of a request:
.. code-block:: http
POST /api/hooks-email/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"event_types": ["openstack_instance_start_succeeded"],
"event_groups": ["users"],
"email": "test@example.com"
}
You may temporarily disable hook without deleting it by issuing following **PATCH** request against hook URL:
.. code-block:: javascript
{
"is_active": "false"
}
"""
return super(EmailHookViewSet, self).create(request, *args, **kwargs)
|
[
"def",
"create",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"EmailHookViewSet",
",",
"self",
")",
".",
"create",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
To create new email hook issue **POST** against */api/hooks-email/* as an authenticated user.
You should specify list of event_types or event_groups.
Example of a request:
.. code-block:: http
POST /api/hooks-email/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"event_types": ["openstack_instance_start_succeeded"],
"event_groups": ["users"],
"email": "test@example.com"
}
You may temporarily disable hook without deleting it by issuing following **PATCH** request against hook URL:
.. code-block:: javascript
{
"is_active": "false"
}
|
[
"To",
"create",
"new",
"email",
"hook",
"issue",
"**",
"POST",
"**",
"against",
"*",
"/",
"api",
"/",
"hooks",
"-",
"email",
"/",
"*",
"as",
"an",
"authenticated",
"user",
".",
"You",
"should",
"specify",
"list",
"of",
"event_types",
"or",
"event_groups",
"."
] |
d6c17a9592bb6c49c33567542eef8d099605a46a
|
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/logging/views.py#L409-L438
|
train
|
opennode/waldur-core
|
waldur_core/logging/views.py
|
PushHookViewSet.create
|
def create(self, request, *args, **kwargs):
"""
To create new push hook issue **POST** against */api/hooks-push/* as an authenticated user.
You should specify list of event_types or event_groups.
Example of a request:
.. code-block:: http
POST /api/hooks-push/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"event_types": ["resource_start_succeeded"],
"event_groups": ["users"],
"type": "Android"
}
You may temporarily disable hook without deleting it by issuing following **PATCH** request against hook URL:
.. code-block:: javascript
{
"is_active": "false"
}
"""
return super(PushHookViewSet, self).create(request, *args, **kwargs)
|
python
|
def create(self, request, *args, **kwargs):
"""
To create new push hook issue **POST** against */api/hooks-push/* as an authenticated user.
You should specify list of event_types or event_groups.
Example of a request:
.. code-block:: http
POST /api/hooks-push/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"event_types": ["resource_start_succeeded"],
"event_groups": ["users"],
"type": "Android"
}
You may temporarily disable hook without deleting it by issuing following **PATCH** request against hook URL:
.. code-block:: javascript
{
"is_active": "false"
}
"""
return super(PushHookViewSet, self).create(request, *args, **kwargs)
|
[
"def",
"create",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"PushHookViewSet",
",",
"self",
")",
".",
"create",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
To create new push hook issue **POST** against */api/hooks-push/* as an authenticated user.
You should specify list of event_types or event_groups.
Example of a request:
.. code-block:: http
POST /api/hooks-push/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Authorization: Token c84d653b9ec92c6cbac41c706593e66f567a7fa4
Host: example.com
{
"event_types": ["resource_start_succeeded"],
"event_groups": ["users"],
"type": "Android"
}
You may temporarily disable hook without deleting it by issuing following **PATCH** request against hook URL:
.. code-block:: javascript
{
"is_active": "false"
}
|
[
"To",
"create",
"new",
"push",
"hook",
"issue",
"**",
"POST",
"**",
"against",
"*",
"/",
"api",
"/",
"hooks",
"-",
"push",
"/",
"*",
"as",
"an",
"authenticated",
"user",
".",
"You",
"should",
"specify",
"list",
"of",
"event_types",
"or",
"event_groups",
"."
] |
d6c17a9592bb6c49c33567542eef8d099605a46a
|
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/logging/views.py#L446-L475
|
train
|
alexras/pylsdj
|
pylsdj/instruments.py
|
Instruments.import_from_file
|
def import_from_file(self, index, filename):
"""Import this instrument's settings from the given file. Will
automatically add the instrument's synth and table to the song's
synths and tables if needed.
Note that this may invalidate existing instrument accessor objects.
:param index: the index into which to import
:param filename: the file from which to load
:raises ImportException: if importing failed, usually because the song
doesn't have enough synth or table slots left for the instrument's
synth or table
"""
with open(filename, 'r') as fp:
self._import_from_struct(index, json.load(fp))
|
python
|
def import_from_file(self, index, filename):
"""Import this instrument's settings from the given file. Will
automatically add the instrument's synth and table to the song's
synths and tables if needed.
Note that this may invalidate existing instrument accessor objects.
:param index: the index into which to import
:param filename: the file from which to load
:raises ImportException: if importing failed, usually because the song
doesn't have enough synth or table slots left for the instrument's
synth or table
"""
with open(filename, 'r') as fp:
self._import_from_struct(index, json.load(fp))
|
[
"def",
"import_from_file",
"(",
"self",
",",
"index",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"fp",
":",
"self",
".",
"_import_from_struct",
"(",
"index",
",",
"json",
".",
"load",
"(",
"fp",
")",
")"
] |
Import this instrument's settings from the given file. Will
automatically add the instrument's synth and table to the song's
synths and tables if needed.
Note that this may invalidate existing instrument accessor objects.
:param index: the index into which to import
:param filename: the file from which to load
:raises ImportException: if importing failed, usually because the song
doesn't have enough synth or table slots left for the instrument's
synth or table
|
[
"Import",
"this",
"instrument",
"s",
"settings",
"from",
"the",
"given",
"file",
".",
"Will",
"automatically",
"add",
"the",
"instrument",
"s",
"synth",
"and",
"table",
"to",
"the",
"song",
"s",
"synths",
"and",
"tables",
"if",
"needed",
"."
] |
1c45a7919dd324e941f76b315558b9647892e4d5
|
https://github.com/alexras/pylsdj/blob/1c45a7919dd324e941f76b315558b9647892e4d5/pylsdj/instruments.py#L63-L80
|
train
|
alexras/pylsdj
|
pylsdj/project.py
|
load_lsdsng
|
def load_lsdsng(filename):
"""Load a Project from a ``.lsdsng`` file.
:param filename: the name of the file from which to load
:rtype: :py:class:`pylsdj.Project`
"""
# Load preamble data so that we know the name and version of the song
with open(filename, 'rb') as fp:
preamble_data = bread.parse(fp, spec.lsdsng_preamble)
with open(filename, 'rb') as fp:
# Skip the preamble this time around
fp.seek(int(len(preamble_data) / 8))
# Load compressed data into a block map and use BlockReader to
# decompress it
factory = BlockFactory()
while True:
block_data = bytearray(fp.read(blockutils.BLOCK_SIZE))
if len(block_data) == 0:
break
block = factory.new_block()
block.data = block_data
remapped_blocks = filepack.renumber_block_keys(factory.blocks)
reader = BlockReader()
compressed_data = reader.read(remapped_blocks)
# Now, decompress the raw data and use it and the preamble to construct
# a Project
raw_data = filepack.decompress(compressed_data)
name = preamble_data.name
version = preamble_data.version
size_blks = int(math.ceil(
float(len(compressed_data)) / blockutils.BLOCK_SIZE))
return Project(name, version, size_blks, raw_data)
|
python
|
def load_lsdsng(filename):
"""Load a Project from a ``.lsdsng`` file.
:param filename: the name of the file from which to load
:rtype: :py:class:`pylsdj.Project`
"""
# Load preamble data so that we know the name and version of the song
with open(filename, 'rb') as fp:
preamble_data = bread.parse(fp, spec.lsdsng_preamble)
with open(filename, 'rb') as fp:
# Skip the preamble this time around
fp.seek(int(len(preamble_data) / 8))
# Load compressed data into a block map and use BlockReader to
# decompress it
factory = BlockFactory()
while True:
block_data = bytearray(fp.read(blockutils.BLOCK_SIZE))
if len(block_data) == 0:
break
block = factory.new_block()
block.data = block_data
remapped_blocks = filepack.renumber_block_keys(factory.blocks)
reader = BlockReader()
compressed_data = reader.read(remapped_blocks)
# Now, decompress the raw data and use it and the preamble to construct
# a Project
raw_data = filepack.decompress(compressed_data)
name = preamble_data.name
version = preamble_data.version
size_blks = int(math.ceil(
float(len(compressed_data)) / blockutils.BLOCK_SIZE))
return Project(name, version, size_blks, raw_data)
|
[
"def",
"load_lsdsng",
"(",
"filename",
")",
":",
"# Load preamble data so that we know the name and version of the song",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"fp",
":",
"preamble_data",
"=",
"bread",
".",
"parse",
"(",
"fp",
",",
"spec",
".",
"lsdsng_preamble",
")",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"fp",
":",
"# Skip the preamble this time around",
"fp",
".",
"seek",
"(",
"int",
"(",
"len",
"(",
"preamble_data",
")",
"/",
"8",
")",
")",
"# Load compressed data into a block map and use BlockReader to",
"# decompress it",
"factory",
"=",
"BlockFactory",
"(",
")",
"while",
"True",
":",
"block_data",
"=",
"bytearray",
"(",
"fp",
".",
"read",
"(",
"blockutils",
".",
"BLOCK_SIZE",
")",
")",
"if",
"len",
"(",
"block_data",
")",
"==",
"0",
":",
"break",
"block",
"=",
"factory",
".",
"new_block",
"(",
")",
"block",
".",
"data",
"=",
"block_data",
"remapped_blocks",
"=",
"filepack",
".",
"renumber_block_keys",
"(",
"factory",
".",
"blocks",
")",
"reader",
"=",
"BlockReader",
"(",
")",
"compressed_data",
"=",
"reader",
".",
"read",
"(",
"remapped_blocks",
")",
"# Now, decompress the raw data and use it and the preamble to construct",
"# a Project",
"raw_data",
"=",
"filepack",
".",
"decompress",
"(",
"compressed_data",
")",
"name",
"=",
"preamble_data",
".",
"name",
"version",
"=",
"preamble_data",
".",
"version",
"size_blks",
"=",
"int",
"(",
"math",
".",
"ceil",
"(",
"float",
"(",
"len",
"(",
"compressed_data",
")",
")",
"/",
"blockutils",
".",
"BLOCK_SIZE",
")",
")",
"return",
"Project",
"(",
"name",
",",
"version",
",",
"size_blks",
",",
"raw_data",
")"
] |
Load a Project from a ``.lsdsng`` file.
:param filename: the name of the file from which to load
:rtype: :py:class:`pylsdj.Project`
|
[
"Load",
"a",
"Project",
"from",
"a",
".",
"lsdsng",
"file",
"."
] |
1c45a7919dd324e941f76b315558b9647892e4d5
|
https://github.com/alexras/pylsdj/blob/1c45a7919dd324e941f76b315558b9647892e4d5/pylsdj/project.py#L10-L52
|
train
|
alexras/pylsdj
|
pylsdj/project.py
|
load_srm
|
def load_srm(filename):
"""Load a Project from an ``.srm`` file.
:param filename: the name of the file from which to load
:rtype: :py:class:`pylsdj.Project`
"""
# .srm files are just decompressed projects without headers
# In order to determine the file's size in compressed blocks, we have to
# compress it first
with open(filename, 'rb') as fp:
raw_data = fp.read()
compressed_data = filepack.compress(raw_data)
factory = BlockFactory()
writer = BlockWriter()
writer.write(compressed_data, factory)
size_in_blocks = len(factory.blocks)
# We'll give the file a dummy name ("SRMLOAD") and version, since we know
# neither
name = "SRMLOAD"
version = 0
return Project(name, version, size_in_blocks, raw_data)
|
python
|
def load_srm(filename):
"""Load a Project from an ``.srm`` file.
:param filename: the name of the file from which to load
:rtype: :py:class:`pylsdj.Project`
"""
# .srm files are just decompressed projects without headers
# In order to determine the file's size in compressed blocks, we have to
# compress it first
with open(filename, 'rb') as fp:
raw_data = fp.read()
compressed_data = filepack.compress(raw_data)
factory = BlockFactory()
writer = BlockWriter()
writer.write(compressed_data, factory)
size_in_blocks = len(factory.blocks)
# We'll give the file a dummy name ("SRMLOAD") and version, since we know
# neither
name = "SRMLOAD"
version = 0
return Project(name, version, size_in_blocks, raw_data)
|
[
"def",
"load_srm",
"(",
"filename",
")",
":",
"# .srm files are just decompressed projects without headers",
"# In order to determine the file's size in compressed blocks, we have to",
"# compress it first",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"fp",
":",
"raw_data",
"=",
"fp",
".",
"read",
"(",
")",
"compressed_data",
"=",
"filepack",
".",
"compress",
"(",
"raw_data",
")",
"factory",
"=",
"BlockFactory",
"(",
")",
"writer",
"=",
"BlockWriter",
"(",
")",
"writer",
".",
"write",
"(",
"compressed_data",
",",
"factory",
")",
"size_in_blocks",
"=",
"len",
"(",
"factory",
".",
"blocks",
")",
"# We'll give the file a dummy name (\"SRMLOAD\") and version, since we know",
"# neither",
"name",
"=",
"\"SRMLOAD\"",
"version",
"=",
"0",
"return",
"Project",
"(",
"name",
",",
"version",
",",
"size_in_blocks",
",",
"raw_data",
")"
] |
Load a Project from an ``.srm`` file.
:param filename: the name of the file from which to load
:rtype: :py:class:`pylsdj.Project`
|
[
"Load",
"a",
"Project",
"from",
"an",
".",
"srm",
"file",
"."
] |
1c45a7919dd324e941f76b315558b9647892e4d5
|
https://github.com/alexras/pylsdj/blob/1c45a7919dd324e941f76b315558b9647892e4d5/pylsdj/project.py#L55-L82
|
train
|
alexras/pylsdj
|
pylsdj/project.py
|
Project.song
|
def song(self):
"""the song associated with the project"""
if self._song is None:
self._song = Song(self._song_data)
return self._song
|
python
|
def song(self):
"""the song associated with the project"""
if self._song is None:
self._song = Song(self._song_data)
return self._song
|
[
"def",
"song",
"(",
"self",
")",
":",
"if",
"self",
".",
"_song",
"is",
"None",
":",
"self",
".",
"_song",
"=",
"Song",
"(",
"self",
".",
"_song_data",
")",
"return",
"self",
".",
"_song"
] |
the song associated with the project
|
[
"the",
"song",
"associated",
"with",
"the",
"project"
] |
1c45a7919dd324e941f76b315558b9647892e4d5
|
https://github.com/alexras/pylsdj/blob/1c45a7919dd324e941f76b315558b9647892e4d5/pylsdj/project.py#L119-L124
|
train
|
alexras/pylsdj
|
pylsdj/project.py
|
Project.save
|
def save(self, filename):
"""Save a project in .lsdsng format to the target file.
:param filename: the name of the file to which to save
:deprecated: use ``save_lsdsng(filename)`` instead
"""
with open(filename, 'wb') as fp:
writer = BlockWriter()
factory = BlockFactory()
preamble_dummy_bytes = bytearray([0] * 9)
preamble = bread.parse(
preamble_dummy_bytes, spec.lsdsng_preamble)
preamble.name = self.name
preamble.version = self.version
preamble_data = bread.write(preamble)
raw_data = self.get_raw_data()
compressed_data = filepack.compress(raw_data)
writer.write(compressed_data, factory)
fp.write(preamble_data)
for key in sorted(factory.blocks.keys()):
fp.write(bytearray(factory.blocks[key].data))
|
python
|
def save(self, filename):
"""Save a project in .lsdsng format to the target file.
:param filename: the name of the file to which to save
:deprecated: use ``save_lsdsng(filename)`` instead
"""
with open(filename, 'wb') as fp:
writer = BlockWriter()
factory = BlockFactory()
preamble_dummy_bytes = bytearray([0] * 9)
preamble = bread.parse(
preamble_dummy_bytes, spec.lsdsng_preamble)
preamble.name = self.name
preamble.version = self.version
preamble_data = bread.write(preamble)
raw_data = self.get_raw_data()
compressed_data = filepack.compress(raw_data)
writer.write(compressed_data, factory)
fp.write(preamble_data)
for key in sorted(factory.blocks.keys()):
fp.write(bytearray(factory.blocks[key].data))
|
[
"def",
"save",
"(",
"self",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'wb'",
")",
"as",
"fp",
":",
"writer",
"=",
"BlockWriter",
"(",
")",
"factory",
"=",
"BlockFactory",
"(",
")",
"preamble_dummy_bytes",
"=",
"bytearray",
"(",
"[",
"0",
"]",
"*",
"9",
")",
"preamble",
"=",
"bread",
".",
"parse",
"(",
"preamble_dummy_bytes",
",",
"spec",
".",
"lsdsng_preamble",
")",
"preamble",
".",
"name",
"=",
"self",
".",
"name",
"preamble",
".",
"version",
"=",
"self",
".",
"version",
"preamble_data",
"=",
"bread",
".",
"write",
"(",
"preamble",
")",
"raw_data",
"=",
"self",
".",
"get_raw_data",
"(",
")",
"compressed_data",
"=",
"filepack",
".",
"compress",
"(",
"raw_data",
")",
"writer",
".",
"write",
"(",
"compressed_data",
",",
"factory",
")",
"fp",
".",
"write",
"(",
"preamble_data",
")",
"for",
"key",
"in",
"sorted",
"(",
"factory",
".",
"blocks",
".",
"keys",
"(",
")",
")",
":",
"fp",
".",
"write",
"(",
"bytearray",
"(",
"factory",
".",
"blocks",
"[",
"key",
"]",
".",
"data",
")",
")"
] |
Save a project in .lsdsng format to the target file.
:param filename: the name of the file to which to save
:deprecated: use ``save_lsdsng(filename)`` instead
|
[
"Save",
"a",
"project",
"in",
".",
"lsdsng",
"format",
"to",
"the",
"target",
"file",
"."
] |
1c45a7919dd324e941f76b315558b9647892e4d5
|
https://github.com/alexras/pylsdj/blob/1c45a7919dd324e941f76b315558b9647892e4d5/pylsdj/project.py#L133-L159
|
train
|
alexras/pylsdj
|
pylsdj/project.py
|
Project.save_srm
|
def save_srm(self, filename):
"""Save a project in .srm format to the target file.
:param filename: the name of the file to which to save
"""
with open(filename, 'wb') as fp:
raw_data = bread.write(self._song_data, spec.song)
fp.write(raw_data)
|
python
|
def save_srm(self, filename):
"""Save a project in .srm format to the target file.
:param filename: the name of the file to which to save
"""
with open(filename, 'wb') as fp:
raw_data = bread.write(self._song_data, spec.song)
fp.write(raw_data)
|
[
"def",
"save_srm",
"(",
"self",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'wb'",
")",
"as",
"fp",
":",
"raw_data",
"=",
"bread",
".",
"write",
"(",
"self",
".",
"_song_data",
",",
"spec",
".",
"song",
")",
"fp",
".",
"write",
"(",
"raw_data",
")"
] |
Save a project in .srm format to the target file.
:param filename: the name of the file to which to save
|
[
"Save",
"a",
"project",
"in",
".",
"srm",
"format",
"to",
"the",
"target",
"file",
"."
] |
1c45a7919dd324e941f76b315558b9647892e4d5
|
https://github.com/alexras/pylsdj/blob/1c45a7919dd324e941f76b315558b9647892e4d5/pylsdj/project.py#L168-L175
|
train
|
alexras/pylsdj
|
pylsdj/synth.py
|
Synth.phase_type
|
def phase_type(self, value):
'''compresses the waveform horizontally; one of
``"normal"``, ``"resync"``, ``"resync2"``'''
self._params.phase_type = value
self._overwrite_lock.disable()
|
python
|
def phase_type(self, value):
'''compresses the waveform horizontally; one of
``"normal"``, ``"resync"``, ``"resync2"``'''
self._params.phase_type = value
self._overwrite_lock.disable()
|
[
"def",
"phase_type",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_params",
".",
"phase_type",
"=",
"value",
"self",
".",
"_overwrite_lock",
".",
"disable",
"(",
")"
] |
compresses the waveform horizontally; one of
``"normal"``, ``"resync"``, ``"resync2"``
|
[
"compresses",
"the",
"waveform",
"horizontally",
";",
"one",
"of",
"normal",
"resync",
"resync2"
] |
1c45a7919dd324e941f76b315558b9647892e4d5
|
https://github.com/alexras/pylsdj/blob/1c45a7919dd324e941f76b315558b9647892e4d5/pylsdj/synth.py#L186-L190
|
train
|
alexras/pylsdj
|
pylsdj/savfile.py
|
SAVFile.project_list
|
def project_list(self):
"""The list of :py:class:`pylsdj.Project` s that the
.sav file contains"""
return [(i, self.projects[i]) for i in sorted(self.projects.keys())]
|
python
|
def project_list(self):
"""The list of :py:class:`pylsdj.Project` s that the
.sav file contains"""
return [(i, self.projects[i]) for i in sorted(self.projects.keys())]
|
[
"def",
"project_list",
"(",
"self",
")",
":",
"return",
"[",
"(",
"i",
",",
"self",
".",
"projects",
"[",
"i",
"]",
")",
"for",
"i",
"in",
"sorted",
"(",
"self",
".",
"projects",
".",
"keys",
"(",
")",
")",
"]"
] |
The list of :py:class:`pylsdj.Project` s that the
.sav file contains
|
[
"The",
"list",
"of",
":",
"py",
":",
"class",
":",
"pylsdj",
".",
"Project",
"s",
"that",
"the",
".",
"sav",
"file",
"contains"
] |
1c45a7919dd324e941f76b315558b9647892e4d5
|
https://github.com/alexras/pylsdj/blob/1c45a7919dd324e941f76b315558b9647892e4d5/pylsdj/savfile.py#L207-L210
|
train
|
alexras/pylsdj
|
pylsdj/savfile.py
|
SAVFile.save
|
def save(self, filename, callback=_noop_callback):
"""Save this file.
:param filename: the file to which to save the .sav file
:type filename: str
:param callback: a progress callback function
:type callback: function
"""
with open(filename, 'wb') as fp:
self._save(fp, callback)
|
python
|
def save(self, filename, callback=_noop_callback):
"""Save this file.
:param filename: the file to which to save the .sav file
:type filename: str
:param callback: a progress callback function
:type callback: function
"""
with open(filename, 'wb') as fp:
self._save(fp, callback)
|
[
"def",
"save",
"(",
"self",
",",
"filename",
",",
"callback",
"=",
"_noop_callback",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'wb'",
")",
"as",
"fp",
":",
"self",
".",
"_save",
"(",
"fp",
",",
"callback",
")"
] |
Save this file.
:param filename: the file to which to save the .sav file
:type filename: str
:param callback: a progress callback function
:type callback: function
|
[
"Save",
"this",
"file",
"."
] |
1c45a7919dd324e941f76b315558b9647892e4d5
|
https://github.com/alexras/pylsdj/blob/1c45a7919dd324e941f76b315558b9647892e4d5/pylsdj/savfile.py#L312-L321
|
train
|
alexras/pylsdj
|
pylsdj/filepack.py
|
split
|
def split(compressed_data, segment_size, block_factory):
"""Splits compressed data into blocks.
:param compressed_data: the compressed data to split
:param segment_size: the size of a block in bytes
:param block_factory: a BlockFactory used to construct the blocks
:rtype: a list of block IDs of blocks that the block factory created while
splitting
"""
# Split compressed data into blocks
segments = []
current_segment_start = 0
index = 0
data_size = len(compressed_data)
while index < data_size:
current_byte = compressed_data[index]
if index < data_size - 1:
next_byte = compressed_data[index + 1]
else:
next_byte = None
jump_size = 1
if current_byte == RLE_BYTE:
assert next_byte is not None, "Expected a command to follow " \
"RLE byte"
if next_byte == RLE_BYTE:
jump_size = 2
else:
jump_size = 3
elif current_byte == SPECIAL_BYTE:
assert next_byte is not None, "Expected a command to follow " \
"special byte"
if next_byte == SPECIAL_BYTE:
jump_size = 2
elif next_byte == DEFAULT_INSTR_BYTE or \
next_byte == DEFAULT_WAVE_BYTE:
jump_size = 3
else:
assert False, "Encountered unexpected EOF or block " \
"switch while segmenting"
# Need two bytes for the jump or EOF
if index - current_segment_start + jump_size > segment_size - 2:
segments.append(compressed_data[
current_segment_start:index])
current_segment_start = index
else:
index += jump_size
# Append the last segment, if any
if current_segment_start != index:
segments.append(compressed_data[
current_segment_start:current_segment_start + index])
# Make sure that no data was lost while segmenting
total_segment_length = sum(map(len, segments))
assert total_segment_length == len(compressed_data), "Lost %d bytes of " \
"data while segmenting" % (len(compressed_data) - total_segment_length)
block_ids = []
for segment in segments:
block = block_factory.new_block()
block_ids.append(block.id)
for (i, segment) in enumerate(segments):
block = block_factory.blocks[block_ids[i]]
assert len(block.data) == 0, "Encountered a block with "
"pre-existing data while writing"
if i == len(segments) - 1:
# Write EOF to the end of the segment
add_eof(segment)
else:
# Write a pointer to the next segment
add_block_switch(segment, block_ids[i + 1])
# Pad segment with zeroes until it's large enough
pad(segment, segment_size)
block.data = segment
return block_ids
|
python
|
def split(compressed_data, segment_size, block_factory):
"""Splits compressed data into blocks.
:param compressed_data: the compressed data to split
:param segment_size: the size of a block in bytes
:param block_factory: a BlockFactory used to construct the blocks
:rtype: a list of block IDs of blocks that the block factory created while
splitting
"""
# Split compressed data into blocks
segments = []
current_segment_start = 0
index = 0
data_size = len(compressed_data)
while index < data_size:
current_byte = compressed_data[index]
if index < data_size - 1:
next_byte = compressed_data[index + 1]
else:
next_byte = None
jump_size = 1
if current_byte == RLE_BYTE:
assert next_byte is not None, "Expected a command to follow " \
"RLE byte"
if next_byte == RLE_BYTE:
jump_size = 2
else:
jump_size = 3
elif current_byte == SPECIAL_BYTE:
assert next_byte is not None, "Expected a command to follow " \
"special byte"
if next_byte == SPECIAL_BYTE:
jump_size = 2
elif next_byte == DEFAULT_INSTR_BYTE or \
next_byte == DEFAULT_WAVE_BYTE:
jump_size = 3
else:
assert False, "Encountered unexpected EOF or block " \
"switch while segmenting"
# Need two bytes for the jump or EOF
if index - current_segment_start + jump_size > segment_size - 2:
segments.append(compressed_data[
current_segment_start:index])
current_segment_start = index
else:
index += jump_size
# Append the last segment, if any
if current_segment_start != index:
segments.append(compressed_data[
current_segment_start:current_segment_start + index])
# Make sure that no data was lost while segmenting
total_segment_length = sum(map(len, segments))
assert total_segment_length == len(compressed_data), "Lost %d bytes of " \
"data while segmenting" % (len(compressed_data) - total_segment_length)
block_ids = []
for segment in segments:
block = block_factory.new_block()
block_ids.append(block.id)
for (i, segment) in enumerate(segments):
block = block_factory.blocks[block_ids[i]]
assert len(block.data) == 0, "Encountered a block with "
"pre-existing data while writing"
if i == len(segments) - 1:
# Write EOF to the end of the segment
add_eof(segment)
else:
# Write a pointer to the next segment
add_block_switch(segment, block_ids[i + 1])
# Pad segment with zeroes until it's large enough
pad(segment, segment_size)
block.data = segment
return block_ids
|
[
"def",
"split",
"(",
"compressed_data",
",",
"segment_size",
",",
"block_factory",
")",
":",
"# Split compressed data into blocks",
"segments",
"=",
"[",
"]",
"current_segment_start",
"=",
"0",
"index",
"=",
"0",
"data_size",
"=",
"len",
"(",
"compressed_data",
")",
"while",
"index",
"<",
"data_size",
":",
"current_byte",
"=",
"compressed_data",
"[",
"index",
"]",
"if",
"index",
"<",
"data_size",
"-",
"1",
":",
"next_byte",
"=",
"compressed_data",
"[",
"index",
"+",
"1",
"]",
"else",
":",
"next_byte",
"=",
"None",
"jump_size",
"=",
"1",
"if",
"current_byte",
"==",
"RLE_BYTE",
":",
"assert",
"next_byte",
"is",
"not",
"None",
",",
"\"Expected a command to follow \"",
"\"RLE byte\"",
"if",
"next_byte",
"==",
"RLE_BYTE",
":",
"jump_size",
"=",
"2",
"else",
":",
"jump_size",
"=",
"3",
"elif",
"current_byte",
"==",
"SPECIAL_BYTE",
":",
"assert",
"next_byte",
"is",
"not",
"None",
",",
"\"Expected a command to follow \"",
"\"special byte\"",
"if",
"next_byte",
"==",
"SPECIAL_BYTE",
":",
"jump_size",
"=",
"2",
"elif",
"next_byte",
"==",
"DEFAULT_INSTR_BYTE",
"or",
"next_byte",
"==",
"DEFAULT_WAVE_BYTE",
":",
"jump_size",
"=",
"3",
"else",
":",
"assert",
"False",
",",
"\"Encountered unexpected EOF or block \"",
"\"switch while segmenting\"",
"# Need two bytes for the jump or EOF",
"if",
"index",
"-",
"current_segment_start",
"+",
"jump_size",
">",
"segment_size",
"-",
"2",
":",
"segments",
".",
"append",
"(",
"compressed_data",
"[",
"current_segment_start",
":",
"index",
"]",
")",
"current_segment_start",
"=",
"index",
"else",
":",
"index",
"+=",
"jump_size",
"# Append the last segment, if any",
"if",
"current_segment_start",
"!=",
"index",
":",
"segments",
".",
"append",
"(",
"compressed_data",
"[",
"current_segment_start",
":",
"current_segment_start",
"+",
"index",
"]",
")",
"# Make sure that no data was lost while segmenting",
"total_segment_length",
"=",
"sum",
"(",
"map",
"(",
"len",
",",
"segments",
")",
")",
"assert",
"total_segment_length",
"==",
"len",
"(",
"compressed_data",
")",
",",
"\"Lost %d bytes of \"",
"\"data while segmenting\"",
"%",
"(",
"len",
"(",
"compressed_data",
")",
"-",
"total_segment_length",
")",
"block_ids",
"=",
"[",
"]",
"for",
"segment",
"in",
"segments",
":",
"block",
"=",
"block_factory",
".",
"new_block",
"(",
")",
"block_ids",
".",
"append",
"(",
"block",
".",
"id",
")",
"for",
"(",
"i",
",",
"segment",
")",
"in",
"enumerate",
"(",
"segments",
")",
":",
"block",
"=",
"block_factory",
".",
"blocks",
"[",
"block_ids",
"[",
"i",
"]",
"]",
"assert",
"len",
"(",
"block",
".",
"data",
")",
"==",
"0",
",",
"\"Encountered a block with \"",
"\"pre-existing data while writing\"",
"if",
"i",
"==",
"len",
"(",
"segments",
")",
"-",
"1",
":",
"# Write EOF to the end of the segment",
"add_eof",
"(",
"segment",
")",
"else",
":",
"# Write a pointer to the next segment",
"add_block_switch",
"(",
"segment",
",",
"block_ids",
"[",
"i",
"+",
"1",
"]",
")",
"# Pad segment with zeroes until it's large enough",
"pad",
"(",
"segment",
",",
"segment_size",
")",
"block",
".",
"data",
"=",
"segment",
"return",
"block_ids"
] |
Splits compressed data into blocks.
:param compressed_data: the compressed data to split
:param segment_size: the size of a block in bytes
:param block_factory: a BlockFactory used to construct the blocks
:rtype: a list of block IDs of blocks that the block factory created while
splitting
|
[
"Splits",
"compressed",
"data",
"into",
"blocks",
"."
] |
1c45a7919dd324e941f76b315558b9647892e4d5
|
https://github.com/alexras/pylsdj/blob/1c45a7919dd324e941f76b315558b9647892e4d5/pylsdj/filepack.py#L46-L138
|
train
|
alexras/pylsdj
|
pylsdj/filepack.py
|
renumber_block_keys
|
def renumber_block_keys(blocks):
"""Renumber a block map's indices so that tehy match the blocks' block
switch statements.
:param blocks a block map to renumber
:rtype: a renumbered copy of the block map
"""
# There is an implicit block switch to the 0th block at the start of the
# file
byte_switch_keys = [0]
block_keys = list(blocks.keys())
# Scan the blocks, recording every block switch statement
for block in list(blocks.values()):
i = 0
while i < len(block.data) - 1:
current_byte = block.data[i]
next_byte = block.data[i + 1]
if current_byte == RLE_BYTE:
if next_byte == RLE_BYTE:
i += 2
else:
i += 3
elif current_byte == SPECIAL_BYTE:
if next_byte in SPECIAL_DEFAULTS:
i += 3
elif next_byte == SPECIAL_BYTE:
i += 2
else:
if next_byte != EOF_BYTE:
byte_switch_keys.append(next_byte)
break
else:
i += 1
byte_switch_keys.sort()
block_keys.sort()
assert len(byte_switch_keys) == len(block_keys), (
"Number of blocks that are target of block switches (%d) "
% (len(byte_switch_keys)) +
"does not equal number of blocks in the song (%d)"
% (len(block_keys)) +
"; possible corruption")
if byte_switch_keys == block_keys:
# No remapping necessary
return blocks
new_block_map = {}
for block_key, byte_switch_key in zip(
block_keys, byte_switch_keys):
new_block_map[byte_switch_key] = blocks[block_key]
return new_block_map
|
python
|
def renumber_block_keys(blocks):
"""Renumber a block map's indices so that tehy match the blocks' block
switch statements.
:param blocks a block map to renumber
:rtype: a renumbered copy of the block map
"""
# There is an implicit block switch to the 0th block at the start of the
# file
byte_switch_keys = [0]
block_keys = list(blocks.keys())
# Scan the blocks, recording every block switch statement
for block in list(blocks.values()):
i = 0
while i < len(block.data) - 1:
current_byte = block.data[i]
next_byte = block.data[i + 1]
if current_byte == RLE_BYTE:
if next_byte == RLE_BYTE:
i += 2
else:
i += 3
elif current_byte == SPECIAL_BYTE:
if next_byte in SPECIAL_DEFAULTS:
i += 3
elif next_byte == SPECIAL_BYTE:
i += 2
else:
if next_byte != EOF_BYTE:
byte_switch_keys.append(next_byte)
break
else:
i += 1
byte_switch_keys.sort()
block_keys.sort()
assert len(byte_switch_keys) == len(block_keys), (
"Number of blocks that are target of block switches (%d) "
% (len(byte_switch_keys)) +
"does not equal number of blocks in the song (%d)"
% (len(block_keys)) +
"; possible corruption")
if byte_switch_keys == block_keys:
# No remapping necessary
return blocks
new_block_map = {}
for block_key, byte_switch_key in zip(
block_keys, byte_switch_keys):
new_block_map[byte_switch_key] = blocks[block_key]
return new_block_map
|
[
"def",
"renumber_block_keys",
"(",
"blocks",
")",
":",
"# There is an implicit block switch to the 0th block at the start of the",
"# file",
"byte_switch_keys",
"=",
"[",
"0",
"]",
"block_keys",
"=",
"list",
"(",
"blocks",
".",
"keys",
"(",
")",
")",
"# Scan the blocks, recording every block switch statement",
"for",
"block",
"in",
"list",
"(",
"blocks",
".",
"values",
"(",
")",
")",
":",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"block",
".",
"data",
")",
"-",
"1",
":",
"current_byte",
"=",
"block",
".",
"data",
"[",
"i",
"]",
"next_byte",
"=",
"block",
".",
"data",
"[",
"i",
"+",
"1",
"]",
"if",
"current_byte",
"==",
"RLE_BYTE",
":",
"if",
"next_byte",
"==",
"RLE_BYTE",
":",
"i",
"+=",
"2",
"else",
":",
"i",
"+=",
"3",
"elif",
"current_byte",
"==",
"SPECIAL_BYTE",
":",
"if",
"next_byte",
"in",
"SPECIAL_DEFAULTS",
":",
"i",
"+=",
"3",
"elif",
"next_byte",
"==",
"SPECIAL_BYTE",
":",
"i",
"+=",
"2",
"else",
":",
"if",
"next_byte",
"!=",
"EOF_BYTE",
":",
"byte_switch_keys",
".",
"append",
"(",
"next_byte",
")",
"break",
"else",
":",
"i",
"+=",
"1",
"byte_switch_keys",
".",
"sort",
"(",
")",
"block_keys",
".",
"sort",
"(",
")",
"assert",
"len",
"(",
"byte_switch_keys",
")",
"==",
"len",
"(",
"block_keys",
")",
",",
"(",
"\"Number of blocks that are target of block switches (%d) \"",
"%",
"(",
"len",
"(",
"byte_switch_keys",
")",
")",
"+",
"\"does not equal number of blocks in the song (%d)\"",
"%",
"(",
"len",
"(",
"block_keys",
")",
")",
"+",
"\"; possible corruption\"",
")",
"if",
"byte_switch_keys",
"==",
"block_keys",
":",
"# No remapping necessary",
"return",
"blocks",
"new_block_map",
"=",
"{",
"}",
"for",
"block_key",
",",
"byte_switch_key",
"in",
"zip",
"(",
"block_keys",
",",
"byte_switch_keys",
")",
":",
"new_block_map",
"[",
"byte_switch_key",
"]",
"=",
"blocks",
"[",
"block_key",
"]",
"return",
"new_block_map"
] |
Renumber a block map's indices so that tehy match the blocks' block
switch statements.
:param blocks a block map to renumber
:rtype: a renumbered copy of the block map
|
[
"Renumber",
"a",
"block",
"map",
"s",
"indices",
"so",
"that",
"tehy",
"match",
"the",
"blocks",
"block",
"switch",
"statements",
"."
] |
1c45a7919dd324e941f76b315558b9647892e4d5
|
https://github.com/alexras/pylsdj/blob/1c45a7919dd324e941f76b315558b9647892e4d5/pylsdj/filepack.py#L141-L201
|
train
|
alexras/pylsdj
|
pylsdj/filepack.py
|
merge
|
def merge(blocks):
"""Merge the given blocks into a contiguous block of compressed data.
:param blocks: the list of blocks
:rtype: a list of compressed bytes
"""
current_block = blocks[sorted(blocks.keys())[0]]
compressed_data = []
eof = False
while not eof:
data_size_to_append = None
next_block = None
i = 0
while i < len(current_block.data) - 1:
current_byte = current_block.data[i]
next_byte = current_block.data[i + 1]
if current_byte == RLE_BYTE:
if next_byte == RLE_BYTE:
i += 2
else:
i += 3
elif current_byte == SPECIAL_BYTE:
if next_byte in SPECIAL_DEFAULTS:
i += 3
elif next_byte == SPECIAL_BYTE:
i += 2
else:
data_size_to_append = i
# hit end of file
if next_byte == EOF_BYTE:
eof = True
else:
next_block = blocks[next_byte]
break
else:
i += 1
assert data_size_to_append is not None, "Ran off the end of a "\
"block without encountering a block switch or EOF"
compressed_data.extend(current_block.data[0:data_size_to_append])
if not eof:
assert next_block is not None, "Switched blocks, but did " \
"not provide the next block to switch to"
current_block = next_block
return compressed_data
|
python
|
def merge(blocks):
"""Merge the given blocks into a contiguous block of compressed data.
:param blocks: the list of blocks
:rtype: a list of compressed bytes
"""
current_block = blocks[sorted(blocks.keys())[0]]
compressed_data = []
eof = False
while not eof:
data_size_to_append = None
next_block = None
i = 0
while i < len(current_block.data) - 1:
current_byte = current_block.data[i]
next_byte = current_block.data[i + 1]
if current_byte == RLE_BYTE:
if next_byte == RLE_BYTE:
i += 2
else:
i += 3
elif current_byte == SPECIAL_BYTE:
if next_byte in SPECIAL_DEFAULTS:
i += 3
elif next_byte == SPECIAL_BYTE:
i += 2
else:
data_size_to_append = i
# hit end of file
if next_byte == EOF_BYTE:
eof = True
else:
next_block = blocks[next_byte]
break
else:
i += 1
assert data_size_to_append is not None, "Ran off the end of a "\
"block without encountering a block switch or EOF"
compressed_data.extend(current_block.data[0:data_size_to_append])
if not eof:
assert next_block is not None, "Switched blocks, but did " \
"not provide the next block to switch to"
current_block = next_block
return compressed_data
|
[
"def",
"merge",
"(",
"blocks",
")",
":",
"current_block",
"=",
"blocks",
"[",
"sorted",
"(",
"blocks",
".",
"keys",
"(",
")",
")",
"[",
"0",
"]",
"]",
"compressed_data",
"=",
"[",
"]",
"eof",
"=",
"False",
"while",
"not",
"eof",
":",
"data_size_to_append",
"=",
"None",
"next_block",
"=",
"None",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"current_block",
".",
"data",
")",
"-",
"1",
":",
"current_byte",
"=",
"current_block",
".",
"data",
"[",
"i",
"]",
"next_byte",
"=",
"current_block",
".",
"data",
"[",
"i",
"+",
"1",
"]",
"if",
"current_byte",
"==",
"RLE_BYTE",
":",
"if",
"next_byte",
"==",
"RLE_BYTE",
":",
"i",
"+=",
"2",
"else",
":",
"i",
"+=",
"3",
"elif",
"current_byte",
"==",
"SPECIAL_BYTE",
":",
"if",
"next_byte",
"in",
"SPECIAL_DEFAULTS",
":",
"i",
"+=",
"3",
"elif",
"next_byte",
"==",
"SPECIAL_BYTE",
":",
"i",
"+=",
"2",
"else",
":",
"data_size_to_append",
"=",
"i",
"# hit end of file",
"if",
"next_byte",
"==",
"EOF_BYTE",
":",
"eof",
"=",
"True",
"else",
":",
"next_block",
"=",
"blocks",
"[",
"next_byte",
"]",
"break",
"else",
":",
"i",
"+=",
"1",
"assert",
"data_size_to_append",
"is",
"not",
"None",
",",
"\"Ran off the end of a \"",
"\"block without encountering a block switch or EOF\"",
"compressed_data",
".",
"extend",
"(",
"current_block",
".",
"data",
"[",
"0",
":",
"data_size_to_append",
"]",
")",
"if",
"not",
"eof",
":",
"assert",
"next_block",
"is",
"not",
"None",
",",
"\"Switched blocks, but did \"",
"\"not provide the next block to switch to\"",
"current_block",
"=",
"next_block",
"return",
"compressed_data"
] |
Merge the given blocks into a contiguous block of compressed data.
:param blocks: the list of blocks
:rtype: a list of compressed bytes
|
[
"Merge",
"the",
"given",
"blocks",
"into",
"a",
"contiguous",
"block",
"of",
"compressed",
"data",
"."
] |
1c45a7919dd324e941f76b315558b9647892e4d5
|
https://github.com/alexras/pylsdj/blob/1c45a7919dd324e941f76b315558b9647892e4d5/pylsdj/filepack.py#L204-L259
|
train
|
alexras/pylsdj
|
pylsdj/filepack.py
|
pad
|
def pad(segment, size):
"""Add zeroes to a segment until it reaches a certain size.
:param segment: the segment to pad
:param size: the size to which to pad the segment
"""
for i in range(size - len(segment)):
segment.append(0)
assert len(segment) == size
|
python
|
def pad(segment, size):
"""Add zeroes to a segment until it reaches a certain size.
:param segment: the segment to pad
:param size: the size to which to pad the segment
"""
for i in range(size - len(segment)):
segment.append(0)
assert len(segment) == size
|
[
"def",
"pad",
"(",
"segment",
",",
"size",
")",
":",
"for",
"i",
"in",
"range",
"(",
"size",
"-",
"len",
"(",
"segment",
")",
")",
":",
"segment",
".",
"append",
"(",
"0",
")",
"assert",
"len",
"(",
"segment",
")",
"==",
"size"
] |
Add zeroes to a segment until it reaches a certain size.
:param segment: the segment to pad
:param size: the size to which to pad the segment
|
[
"Add",
"zeroes",
"to",
"a",
"segment",
"until",
"it",
"reaches",
"a",
"certain",
"size",
"."
] |
1c45a7919dd324e941f76b315558b9647892e4d5
|
https://github.com/alexras/pylsdj/blob/1c45a7919dd324e941f76b315558b9647892e4d5/pylsdj/filepack.py#L276-L285
|
train
|
alexras/pylsdj
|
pylsdj/filepack.py
|
decompress
|
def decompress(compressed_data):
"""Decompress data that has been compressed by the filepack algorithm.
:param compressed_data: an array of compressed data bytes to decompress
:rtype: an array of decompressed bytes"""
raw_data = []
index = 0
while index < len(compressed_data):
current = compressed_data[index]
index += 1
if current == RLE_BYTE:
directive = compressed_data[index]
index += 1
if directive == RLE_BYTE:
raw_data.append(RLE_BYTE)
else:
count = compressed_data[index]
index += 1
raw_data.extend([directive] * count)
elif current == SPECIAL_BYTE:
directive = compressed_data[index]
index += 1
if directive == SPECIAL_BYTE:
raw_data.append(SPECIAL_BYTE)
elif directive == DEFAULT_WAVE_BYTE:
count = compressed_data[index]
index += 1
raw_data.extend(DEFAULT_WAVE * count)
elif directive == DEFAULT_INSTR_BYTE:
count = compressed_data[index]
index += 1
raw_data.extend(DEFAULT_INSTRUMENT_FILEPACK * count)
elif directive == EOF_BYTE:
assert False, ("Unexpected EOF command encountered while "
"decompressing")
else:
assert False, "Countered unexpected sequence 0x%02x 0x%02x" % (
current, directive)
else:
raw_data.append(current)
return raw_data
|
python
|
def decompress(compressed_data):
"""Decompress data that has been compressed by the filepack algorithm.
:param compressed_data: an array of compressed data bytes to decompress
:rtype: an array of decompressed bytes"""
raw_data = []
index = 0
while index < len(compressed_data):
current = compressed_data[index]
index += 1
if current == RLE_BYTE:
directive = compressed_data[index]
index += 1
if directive == RLE_BYTE:
raw_data.append(RLE_BYTE)
else:
count = compressed_data[index]
index += 1
raw_data.extend([directive] * count)
elif current == SPECIAL_BYTE:
directive = compressed_data[index]
index += 1
if directive == SPECIAL_BYTE:
raw_data.append(SPECIAL_BYTE)
elif directive == DEFAULT_WAVE_BYTE:
count = compressed_data[index]
index += 1
raw_data.extend(DEFAULT_WAVE * count)
elif directive == DEFAULT_INSTR_BYTE:
count = compressed_data[index]
index += 1
raw_data.extend(DEFAULT_INSTRUMENT_FILEPACK * count)
elif directive == EOF_BYTE:
assert False, ("Unexpected EOF command encountered while "
"decompressing")
else:
assert False, "Countered unexpected sequence 0x%02x 0x%02x" % (
current, directive)
else:
raw_data.append(current)
return raw_data
|
[
"def",
"decompress",
"(",
"compressed_data",
")",
":",
"raw_data",
"=",
"[",
"]",
"index",
"=",
"0",
"while",
"index",
"<",
"len",
"(",
"compressed_data",
")",
":",
"current",
"=",
"compressed_data",
"[",
"index",
"]",
"index",
"+=",
"1",
"if",
"current",
"==",
"RLE_BYTE",
":",
"directive",
"=",
"compressed_data",
"[",
"index",
"]",
"index",
"+=",
"1",
"if",
"directive",
"==",
"RLE_BYTE",
":",
"raw_data",
".",
"append",
"(",
"RLE_BYTE",
")",
"else",
":",
"count",
"=",
"compressed_data",
"[",
"index",
"]",
"index",
"+=",
"1",
"raw_data",
".",
"extend",
"(",
"[",
"directive",
"]",
"*",
"count",
")",
"elif",
"current",
"==",
"SPECIAL_BYTE",
":",
"directive",
"=",
"compressed_data",
"[",
"index",
"]",
"index",
"+=",
"1",
"if",
"directive",
"==",
"SPECIAL_BYTE",
":",
"raw_data",
".",
"append",
"(",
"SPECIAL_BYTE",
")",
"elif",
"directive",
"==",
"DEFAULT_WAVE_BYTE",
":",
"count",
"=",
"compressed_data",
"[",
"index",
"]",
"index",
"+=",
"1",
"raw_data",
".",
"extend",
"(",
"DEFAULT_WAVE",
"*",
"count",
")",
"elif",
"directive",
"==",
"DEFAULT_INSTR_BYTE",
":",
"count",
"=",
"compressed_data",
"[",
"index",
"]",
"index",
"+=",
"1",
"raw_data",
".",
"extend",
"(",
"DEFAULT_INSTRUMENT_FILEPACK",
"*",
"count",
")",
"elif",
"directive",
"==",
"EOF_BYTE",
":",
"assert",
"False",
",",
"(",
"\"Unexpected EOF command encountered while \"",
"\"decompressing\"",
")",
"else",
":",
"assert",
"False",
",",
"\"Countered unexpected sequence 0x%02x 0x%02x\"",
"%",
"(",
"current",
",",
"directive",
")",
"else",
":",
"raw_data",
".",
"append",
"(",
"current",
")",
"return",
"raw_data"
] |
Decompress data that has been compressed by the filepack algorithm.
:param compressed_data: an array of compressed data bytes to decompress
:rtype: an array of decompressed bytes
|
[
"Decompress",
"data",
"that",
"has",
"been",
"compressed",
"by",
"the",
"filepack",
"algorithm",
"."
] |
1c45a7919dd324e941f76b315558b9647892e4d5
|
https://github.com/alexras/pylsdj/blob/1c45a7919dd324e941f76b315558b9647892e4d5/pylsdj/filepack.py#L288-L338
|
train
|
alexras/pylsdj
|
pylsdj/filepack.py
|
compress
|
def compress(raw_data):
"""Compress raw bytes with the filepack algorithm.
:param raw_data: an array of raw data bytes to compress
:rtype: a list of compressed bytes
"""
raw_data = bytearray(raw_data)
compressed_data = []
data_size = len(raw_data)
index = 0
next_bytes = [-1, -1, -1]
def is_default_instrument(index):
if index + len(DEFAULT_INSTRUMENT_FILEPACK) > len(raw_data):
return False
instr_bytes = raw_data[index:index + len(DEFAULT_INSTRUMENT_FILEPACK)]
if instr_bytes[0] != 0xa8 or instr_bytes[1] != 0:
return False
return instr_bytes == DEFAULT_INSTRUMENT_FILEPACK
def is_default_wave(index):
return (index + len(DEFAULT_WAVE) <= len(raw_data) and
raw_data[index:index + len(DEFAULT_WAVE)] == DEFAULT_WAVE)
while index < data_size:
current_byte = raw_data[index]
for i in range(3):
if index < data_size - (i + 1):
next_bytes[i] = raw_data[index + (i + 1)]
else:
next_bytes[i] = -1
if current_byte == RLE_BYTE:
compressed_data.append(RLE_BYTE)
compressed_data.append(RLE_BYTE)
index += 1
elif current_byte == SPECIAL_BYTE:
compressed_data.append(SPECIAL_BYTE)
compressed_data.append(SPECIAL_BYTE)
index += 1
elif is_default_instrument(index):
counter = 1
index += len(DEFAULT_INSTRUMENT_FILEPACK)
while (is_default_instrument(index) and
counter < 0x100):
counter += 1
index += len(DEFAULT_INSTRUMENT_FILEPACK)
compressed_data.append(SPECIAL_BYTE)
compressed_data.append(DEFAULT_INSTR_BYTE)
compressed_data.append(counter)
elif is_default_wave(index):
counter = 1
index += len(DEFAULT_WAVE)
while is_default_wave(index) and counter < 0xff:
counter += 1
index += len(DEFAULT_WAVE)
compressed_data.append(SPECIAL_BYTE)
compressed_data.append(DEFAULT_WAVE_BYTE)
compressed_data.append(counter)
elif (current_byte == next_bytes[0] and
next_bytes[0] == next_bytes[1] and
next_bytes[1] == next_bytes[2]):
# Do RLE compression
compressed_data.append(RLE_BYTE)
compressed_data.append(current_byte)
counter = 0
while (index < data_size and
raw_data[index] == current_byte and
counter < 0xff):
index += 1
counter += 1
compressed_data.append(counter)
else:
compressed_data.append(current_byte)
index += 1
return compressed_data
|
python
|
def compress(raw_data):
"""Compress raw bytes with the filepack algorithm.
:param raw_data: an array of raw data bytes to compress
:rtype: a list of compressed bytes
"""
raw_data = bytearray(raw_data)
compressed_data = []
data_size = len(raw_data)
index = 0
next_bytes = [-1, -1, -1]
def is_default_instrument(index):
if index + len(DEFAULT_INSTRUMENT_FILEPACK) > len(raw_data):
return False
instr_bytes = raw_data[index:index + len(DEFAULT_INSTRUMENT_FILEPACK)]
if instr_bytes[0] != 0xa8 or instr_bytes[1] != 0:
return False
return instr_bytes == DEFAULT_INSTRUMENT_FILEPACK
def is_default_wave(index):
return (index + len(DEFAULT_WAVE) <= len(raw_data) and
raw_data[index:index + len(DEFAULT_WAVE)] == DEFAULT_WAVE)
while index < data_size:
current_byte = raw_data[index]
for i in range(3):
if index < data_size - (i + 1):
next_bytes[i] = raw_data[index + (i + 1)]
else:
next_bytes[i] = -1
if current_byte == RLE_BYTE:
compressed_data.append(RLE_BYTE)
compressed_data.append(RLE_BYTE)
index += 1
elif current_byte == SPECIAL_BYTE:
compressed_data.append(SPECIAL_BYTE)
compressed_data.append(SPECIAL_BYTE)
index += 1
elif is_default_instrument(index):
counter = 1
index += len(DEFAULT_INSTRUMENT_FILEPACK)
while (is_default_instrument(index) and
counter < 0x100):
counter += 1
index += len(DEFAULT_INSTRUMENT_FILEPACK)
compressed_data.append(SPECIAL_BYTE)
compressed_data.append(DEFAULT_INSTR_BYTE)
compressed_data.append(counter)
elif is_default_wave(index):
counter = 1
index += len(DEFAULT_WAVE)
while is_default_wave(index) and counter < 0xff:
counter += 1
index += len(DEFAULT_WAVE)
compressed_data.append(SPECIAL_BYTE)
compressed_data.append(DEFAULT_WAVE_BYTE)
compressed_data.append(counter)
elif (current_byte == next_bytes[0] and
next_bytes[0] == next_bytes[1] and
next_bytes[1] == next_bytes[2]):
# Do RLE compression
compressed_data.append(RLE_BYTE)
compressed_data.append(current_byte)
counter = 0
while (index < data_size and
raw_data[index] == current_byte and
counter < 0xff):
index += 1
counter += 1
compressed_data.append(counter)
else:
compressed_data.append(current_byte)
index += 1
return compressed_data
|
[
"def",
"compress",
"(",
"raw_data",
")",
":",
"raw_data",
"=",
"bytearray",
"(",
"raw_data",
")",
"compressed_data",
"=",
"[",
"]",
"data_size",
"=",
"len",
"(",
"raw_data",
")",
"index",
"=",
"0",
"next_bytes",
"=",
"[",
"-",
"1",
",",
"-",
"1",
",",
"-",
"1",
"]",
"def",
"is_default_instrument",
"(",
"index",
")",
":",
"if",
"index",
"+",
"len",
"(",
"DEFAULT_INSTRUMENT_FILEPACK",
")",
">",
"len",
"(",
"raw_data",
")",
":",
"return",
"False",
"instr_bytes",
"=",
"raw_data",
"[",
"index",
":",
"index",
"+",
"len",
"(",
"DEFAULT_INSTRUMENT_FILEPACK",
")",
"]",
"if",
"instr_bytes",
"[",
"0",
"]",
"!=",
"0xa8",
"or",
"instr_bytes",
"[",
"1",
"]",
"!=",
"0",
":",
"return",
"False",
"return",
"instr_bytes",
"==",
"DEFAULT_INSTRUMENT_FILEPACK",
"def",
"is_default_wave",
"(",
"index",
")",
":",
"return",
"(",
"index",
"+",
"len",
"(",
"DEFAULT_WAVE",
")",
"<=",
"len",
"(",
"raw_data",
")",
"and",
"raw_data",
"[",
"index",
":",
"index",
"+",
"len",
"(",
"DEFAULT_WAVE",
")",
"]",
"==",
"DEFAULT_WAVE",
")",
"while",
"index",
"<",
"data_size",
":",
"current_byte",
"=",
"raw_data",
"[",
"index",
"]",
"for",
"i",
"in",
"range",
"(",
"3",
")",
":",
"if",
"index",
"<",
"data_size",
"-",
"(",
"i",
"+",
"1",
")",
":",
"next_bytes",
"[",
"i",
"]",
"=",
"raw_data",
"[",
"index",
"+",
"(",
"i",
"+",
"1",
")",
"]",
"else",
":",
"next_bytes",
"[",
"i",
"]",
"=",
"-",
"1",
"if",
"current_byte",
"==",
"RLE_BYTE",
":",
"compressed_data",
".",
"append",
"(",
"RLE_BYTE",
")",
"compressed_data",
".",
"append",
"(",
"RLE_BYTE",
")",
"index",
"+=",
"1",
"elif",
"current_byte",
"==",
"SPECIAL_BYTE",
":",
"compressed_data",
".",
"append",
"(",
"SPECIAL_BYTE",
")",
"compressed_data",
".",
"append",
"(",
"SPECIAL_BYTE",
")",
"index",
"+=",
"1",
"elif",
"is_default_instrument",
"(",
"index",
")",
":",
"counter",
"=",
"1",
"index",
"+=",
"len",
"(",
"DEFAULT_INSTRUMENT_FILEPACK",
")",
"while",
"(",
"is_default_instrument",
"(",
"index",
")",
"and",
"counter",
"<",
"0x100",
")",
":",
"counter",
"+=",
"1",
"index",
"+=",
"len",
"(",
"DEFAULT_INSTRUMENT_FILEPACK",
")",
"compressed_data",
".",
"append",
"(",
"SPECIAL_BYTE",
")",
"compressed_data",
".",
"append",
"(",
"DEFAULT_INSTR_BYTE",
")",
"compressed_data",
".",
"append",
"(",
"counter",
")",
"elif",
"is_default_wave",
"(",
"index",
")",
":",
"counter",
"=",
"1",
"index",
"+=",
"len",
"(",
"DEFAULT_WAVE",
")",
"while",
"is_default_wave",
"(",
"index",
")",
"and",
"counter",
"<",
"0xff",
":",
"counter",
"+=",
"1",
"index",
"+=",
"len",
"(",
"DEFAULT_WAVE",
")",
"compressed_data",
".",
"append",
"(",
"SPECIAL_BYTE",
")",
"compressed_data",
".",
"append",
"(",
"DEFAULT_WAVE_BYTE",
")",
"compressed_data",
".",
"append",
"(",
"counter",
")",
"elif",
"(",
"current_byte",
"==",
"next_bytes",
"[",
"0",
"]",
"and",
"next_bytes",
"[",
"0",
"]",
"==",
"next_bytes",
"[",
"1",
"]",
"and",
"next_bytes",
"[",
"1",
"]",
"==",
"next_bytes",
"[",
"2",
"]",
")",
":",
"# Do RLE compression",
"compressed_data",
".",
"append",
"(",
"RLE_BYTE",
")",
"compressed_data",
".",
"append",
"(",
"current_byte",
")",
"counter",
"=",
"0",
"while",
"(",
"index",
"<",
"data_size",
"and",
"raw_data",
"[",
"index",
"]",
"==",
"current_byte",
"and",
"counter",
"<",
"0xff",
")",
":",
"index",
"+=",
"1",
"counter",
"+=",
"1",
"compressed_data",
".",
"append",
"(",
"counter",
")",
"else",
":",
"compressed_data",
".",
"append",
"(",
"current_byte",
")",
"index",
"+=",
"1",
"return",
"compressed_data"
] |
Compress raw bytes with the filepack algorithm.
:param raw_data: an array of raw data bytes to compress
:rtype: a list of compressed bytes
|
[
"Compress",
"raw",
"bytes",
"with",
"the",
"filepack",
"algorithm",
"."
] |
1c45a7919dd324e941f76b315558b9647892e4d5
|
https://github.com/alexras/pylsdj/blob/1c45a7919dd324e941f76b315558b9647892e4d5/pylsdj/filepack.py#L341-L433
|
train
|
alexras/pylsdj
|
pylsdj/utils.py
|
name_without_zeroes
|
def name_without_zeroes(name):
"""
Return a human-readable name without LSDJ's trailing zeroes.
:param name: the name from which to strip zeroes
:rtype: the name, without trailing zeroes
"""
first_zero = name.find(b'\0')
if first_zero == -1:
return name
else:
return str(name[:first_zero])
|
python
|
def name_without_zeroes(name):
"""
Return a human-readable name without LSDJ's trailing zeroes.
:param name: the name from which to strip zeroes
:rtype: the name, without trailing zeroes
"""
first_zero = name.find(b'\0')
if first_zero == -1:
return name
else:
return str(name[:first_zero])
|
[
"def",
"name_without_zeroes",
"(",
"name",
")",
":",
"first_zero",
"=",
"name",
".",
"find",
"(",
"b'\\0'",
")",
"if",
"first_zero",
"==",
"-",
"1",
":",
"return",
"name",
"else",
":",
"return",
"str",
"(",
"name",
"[",
":",
"first_zero",
"]",
")"
] |
Return a human-readable name without LSDJ's trailing zeroes.
:param name: the name from which to strip zeroes
:rtype: the name, without trailing zeroes
|
[
"Return",
"a",
"human",
"-",
"readable",
"name",
"without",
"LSDJ",
"s",
"trailing",
"zeroes",
"."
] |
1c45a7919dd324e941f76b315558b9647892e4d5
|
https://github.com/alexras/pylsdj/blob/1c45a7919dd324e941f76b315558b9647892e4d5/pylsdj/utils.py#L32-L44
|
train
|
alexras/pylsdj
|
pylsdj/instrument.py
|
Instrument.name
|
def name(self):
"""the instrument's name (5 characters, zero-padded)"""
instr_name = self.song.song_data.instrument_names[self.index]
if type(instr_name) == bytes:
instr_name = instr_name.decode('utf-8')
return instr_name
|
python
|
def name(self):
"""the instrument's name (5 characters, zero-padded)"""
instr_name = self.song.song_data.instrument_names[self.index]
if type(instr_name) == bytes:
instr_name = instr_name.decode('utf-8')
return instr_name
|
[
"def",
"name",
"(",
"self",
")",
":",
"instr_name",
"=",
"self",
".",
"song",
".",
"song_data",
".",
"instrument_names",
"[",
"self",
".",
"index",
"]",
"if",
"type",
"(",
"instr_name",
")",
"==",
"bytes",
":",
"instr_name",
"=",
"instr_name",
".",
"decode",
"(",
"'utf-8'",
")",
"return",
"instr_name"
] |
the instrument's name (5 characters, zero-padded)
|
[
"the",
"instrument",
"s",
"name",
"(",
"5",
"characters",
"zero",
"-",
"padded",
")"
] |
1c45a7919dd324e941f76b315558b9647892e4d5
|
https://github.com/alexras/pylsdj/blob/1c45a7919dd324e941f76b315558b9647892e4d5/pylsdj/instrument.py#L21-L28
|
train
|
alexras/pylsdj
|
pylsdj/instrument.py
|
Instrument.table
|
def table(self):
"""a ```pylsdj.Table``` referencing the instrument's table, or None
if the instrument doesn't have a table"""
if hasattr(self.data, 'table_on') and self.data.table_on:
assert_index_sane(self.data.table, len(self.song.tables))
return self.song.tables[self.data.table]
|
python
|
def table(self):
"""a ```pylsdj.Table``` referencing the instrument's table, or None
if the instrument doesn't have a table"""
if hasattr(self.data, 'table_on') and self.data.table_on:
assert_index_sane(self.data.table, len(self.song.tables))
return self.song.tables[self.data.table]
|
[
"def",
"table",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"data",
",",
"'table_on'",
")",
"and",
"self",
".",
"data",
".",
"table_on",
":",
"assert_index_sane",
"(",
"self",
".",
"data",
".",
"table",
",",
"len",
"(",
"self",
".",
"song",
".",
"tables",
")",
")",
"return",
"self",
".",
"song",
".",
"tables",
"[",
"self",
".",
"data",
".",
"table",
"]"
] |
a ```pylsdj.Table``` referencing the instrument's table, or None
if the instrument doesn't have a table
|
[
"a",
"pylsdj",
".",
"Table",
"referencing",
"the",
"instrument",
"s",
"table",
"or",
"None",
"if",
"the",
"instrument",
"doesn",
"t",
"have",
"a",
"table"
] |
1c45a7919dd324e941f76b315558b9647892e4d5
|
https://github.com/alexras/pylsdj/blob/1c45a7919dd324e941f76b315558b9647892e4d5/pylsdj/instrument.py#L47-L52
|
train
|
alexras/pylsdj
|
pylsdj/instrument.py
|
Instrument.import_lsdinst
|
def import_lsdinst(self, struct_data):
"""import from an lsdinst struct"""
self.name = struct_data['name']
self.automate = struct_data['data']['automate']
self.pan = struct_data['data']['pan']
if self.table is not None:
self.table.import_lsdinst(struct_data)
|
python
|
def import_lsdinst(self, struct_data):
"""import from an lsdinst struct"""
self.name = struct_data['name']
self.automate = struct_data['data']['automate']
self.pan = struct_data['data']['pan']
if self.table is not None:
self.table.import_lsdinst(struct_data)
|
[
"def",
"import_lsdinst",
"(",
"self",
",",
"struct_data",
")",
":",
"self",
".",
"name",
"=",
"struct_data",
"[",
"'name'",
"]",
"self",
".",
"automate",
"=",
"struct_data",
"[",
"'data'",
"]",
"[",
"'automate'",
"]",
"self",
".",
"pan",
"=",
"struct_data",
"[",
"'data'",
"]",
"[",
"'pan'",
"]",
"if",
"self",
".",
"table",
"is",
"not",
"None",
":",
"self",
".",
"table",
".",
"import_lsdinst",
"(",
"struct_data",
")"
] |
import from an lsdinst struct
|
[
"import",
"from",
"an",
"lsdinst",
"struct"
] |
1c45a7919dd324e941f76b315558b9647892e4d5
|
https://github.com/alexras/pylsdj/blob/1c45a7919dd324e941f76b315558b9647892e4d5/pylsdj/instrument.py#L79-L86
|
train
|
alexras/pylsdj
|
pylsdj/instrument.py
|
Instrument.export_to_file
|
def export_to_file(self, filename):
"""Export this instrument's settings to a file.
:param filename: the name of the file
"""
instr_json = self.export_struct()
with open(filename, 'w') as fp:
json.dump(instr_json, fp, indent=2)
|
python
|
def export_to_file(self, filename):
"""Export this instrument's settings to a file.
:param filename: the name of the file
"""
instr_json = self.export_struct()
with open(filename, 'w') as fp:
json.dump(instr_json, fp, indent=2)
|
[
"def",
"export_to_file",
"(",
"self",
",",
"filename",
")",
":",
"instr_json",
"=",
"self",
".",
"export_struct",
"(",
")",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"fp",
":",
"json",
".",
"dump",
"(",
"instr_json",
",",
"fp",
",",
"indent",
"=",
"2",
")"
] |
Export this instrument's settings to a file.
:param filename: the name of the file
|
[
"Export",
"this",
"instrument",
"s",
"settings",
"to",
"a",
"file",
"."
] |
1c45a7919dd324e941f76b315558b9647892e4d5
|
https://github.com/alexras/pylsdj/blob/1c45a7919dd324e941f76b315558b9647892e4d5/pylsdj/instrument.py#L88-L96
|
train
|
alexras/pylsdj
|
pylsdj/kits.py
|
KitSample.write_wav
|
def write_wav(self, filename):
"""Write this sample to a WAV file.
:param filename: the file to which to write
"""
wave_output = None
try:
wave_output = wave.open(filename, 'w')
wave_output.setparams(WAVE_PARAMS)
frames = bytearray([x << 4 for x in self.sample_data])
wave_output.writeframes(frames)
finally:
if wave_output is not None:
wave_output.close()
|
python
|
def write_wav(self, filename):
"""Write this sample to a WAV file.
:param filename: the file to which to write
"""
wave_output = None
try:
wave_output = wave.open(filename, 'w')
wave_output.setparams(WAVE_PARAMS)
frames = bytearray([x << 4 for x in self.sample_data])
wave_output.writeframes(frames)
finally:
if wave_output is not None:
wave_output.close()
|
[
"def",
"write_wav",
"(",
"self",
",",
"filename",
")",
":",
"wave_output",
"=",
"None",
"try",
":",
"wave_output",
"=",
"wave",
".",
"open",
"(",
"filename",
",",
"'w'",
")",
"wave_output",
".",
"setparams",
"(",
"WAVE_PARAMS",
")",
"frames",
"=",
"bytearray",
"(",
"[",
"x",
"<<",
"4",
"for",
"x",
"in",
"self",
".",
"sample_data",
"]",
")",
"wave_output",
".",
"writeframes",
"(",
"frames",
")",
"finally",
":",
"if",
"wave_output",
"is",
"not",
"None",
":",
"wave_output",
".",
"close",
"(",
")"
] |
Write this sample to a WAV file.
:param filename: the file to which to write
|
[
"Write",
"this",
"sample",
"to",
"a",
"WAV",
"file",
"."
] |
1c45a7919dd324e941f76b315558b9647892e4d5
|
https://github.com/alexras/pylsdj/blob/1c45a7919dd324e941f76b315558b9647892e4d5/pylsdj/kits.py#L229-L246
|
train
|
alexras/pylsdj
|
pylsdj/kits.py
|
KitSample.read_wav
|
def read_wav(self, filename):
"""Read sample data for this sample from a WAV file.
:param filename: the file from which to read
"""
wave_input = None
try:
wave_input = wave.open(filename, 'r')
wave_frames = bytearray(
wave_input.readframes(wave_input.getnframes()))
self.sample_data = [x >> 4 for x in wave_frames]
finally:
if wave_input is not None:
wave_input.close()
|
python
|
def read_wav(self, filename):
"""Read sample data for this sample from a WAV file.
:param filename: the file from which to read
"""
wave_input = None
try:
wave_input = wave.open(filename, 'r')
wave_frames = bytearray(
wave_input.readframes(wave_input.getnframes()))
self.sample_data = [x >> 4 for x in wave_frames]
finally:
if wave_input is not None:
wave_input.close()
|
[
"def",
"read_wav",
"(",
"self",
",",
"filename",
")",
":",
"wave_input",
"=",
"None",
"try",
":",
"wave_input",
"=",
"wave",
".",
"open",
"(",
"filename",
",",
"'r'",
")",
"wave_frames",
"=",
"bytearray",
"(",
"wave_input",
".",
"readframes",
"(",
"wave_input",
".",
"getnframes",
"(",
")",
")",
")",
"self",
".",
"sample_data",
"=",
"[",
"x",
">>",
"4",
"for",
"x",
"in",
"wave_frames",
"]",
"finally",
":",
"if",
"wave_input",
"is",
"not",
"None",
":",
"wave_input",
".",
"close",
"(",
")"
] |
Read sample data for this sample from a WAV file.
:param filename: the file from which to read
|
[
"Read",
"sample",
"data",
"for",
"this",
"sample",
"from",
"a",
"WAV",
"file",
"."
] |
1c45a7919dd324e941f76b315558b9647892e4d5
|
https://github.com/alexras/pylsdj/blob/1c45a7919dd324e941f76b315558b9647892e4d5/pylsdj/kits.py#L248-L264
|
train
|
thusoy/headsup
|
headsup.py
|
get_device_address
|
def get_device_address(device):
""" find the local ip address on the given device """
if device is None:
return None
command = ['ip', 'route', 'list', 'dev', device]
ip_routes = subprocess.check_output(command).strip()
for line in ip_routes.split('\n'):
seen = ''
for a in line.split():
if seen == 'src':
return a
seen = a
return None
|
python
|
def get_device_address(device):
""" find the local ip address on the given device """
if device is None:
return None
command = ['ip', 'route', 'list', 'dev', device]
ip_routes = subprocess.check_output(command).strip()
for line in ip_routes.split('\n'):
seen = ''
for a in line.split():
if seen == 'src':
return a
seen = a
return None
|
[
"def",
"get_device_address",
"(",
"device",
")",
":",
"if",
"device",
"is",
"None",
":",
"return",
"None",
"command",
"=",
"[",
"'ip'",
",",
"'route'",
",",
"'list'",
",",
"'dev'",
",",
"device",
"]",
"ip_routes",
"=",
"subprocess",
".",
"check_output",
"(",
"command",
")",
".",
"strip",
"(",
")",
"for",
"line",
"in",
"ip_routes",
".",
"split",
"(",
"'\\n'",
")",
":",
"seen",
"=",
"''",
"for",
"a",
"in",
"line",
".",
"split",
"(",
")",
":",
"if",
"seen",
"==",
"'src'",
":",
"return",
"a",
"seen",
"=",
"a",
"return",
"None"
] |
find the local ip address on the given device
|
[
"find",
"the",
"local",
"ip",
"address",
"on",
"the",
"given",
"device"
] |
165a63cc6c987f664f2efd901d483ca07b7bc898
|
https://github.com/thusoy/headsup/blob/165a63cc6c987f664f2efd901d483ca07b7bc898/headsup.py#L68-L80
|
train
|
thusoy/headsup
|
headsup.py
|
get_default_net_device
|
def get_default_net_device():
""" Find the device where the default route is. """
with open('/proc/net/route') as fh:
for line in fh:
iface, dest, _ = line.split(None, 2)
if dest == '00000000':
return iface
return None
|
python
|
def get_default_net_device():
""" Find the device where the default route is. """
with open('/proc/net/route') as fh:
for line in fh:
iface, dest, _ = line.split(None, 2)
if dest == '00000000':
return iface
return None
|
[
"def",
"get_default_net_device",
"(",
")",
":",
"with",
"open",
"(",
"'/proc/net/route'",
")",
"as",
"fh",
":",
"for",
"line",
"in",
"fh",
":",
"iface",
",",
"dest",
",",
"_",
"=",
"line",
".",
"split",
"(",
"None",
",",
"2",
")",
"if",
"dest",
"==",
"'00000000'",
":",
"return",
"iface",
"return",
"None"
] |
Find the device where the default route is.
|
[
"Find",
"the",
"device",
"where",
"the",
"default",
"route",
"is",
"."
] |
165a63cc6c987f664f2efd901d483ca07b7bc898
|
https://github.com/thusoy/headsup/blob/165a63cc6c987f664f2efd901d483ca07b7bc898/headsup.py#L83-L90
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/util/argsutils.py
|
add_missing_optional_args_with_value_none
|
def add_missing_optional_args_with_value_none(args, optional_args):
'''
Adds key-value pairs to the passed dictionary, so that
afterwards, the dictionary can be used without needing
to check for KeyErrors.
If the keys passed as a second argument are not present,
they are added with None as a value.
:args: The dictionary to be completed.
:optional_args: The keys that need to be added, if
they are not present.
:return: The modified dictionary.
'''
for name in optional_args:
if not name in args.keys():
args[name] = None
return args
|
python
|
def add_missing_optional_args_with_value_none(args, optional_args):
'''
Adds key-value pairs to the passed dictionary, so that
afterwards, the dictionary can be used without needing
to check for KeyErrors.
If the keys passed as a second argument are not present,
they are added with None as a value.
:args: The dictionary to be completed.
:optional_args: The keys that need to be added, if
they are not present.
:return: The modified dictionary.
'''
for name in optional_args:
if not name in args.keys():
args[name] = None
return args
|
[
"def",
"add_missing_optional_args_with_value_none",
"(",
"args",
",",
"optional_args",
")",
":",
"for",
"name",
"in",
"optional_args",
":",
"if",
"not",
"name",
"in",
"args",
".",
"keys",
"(",
")",
":",
"args",
"[",
"name",
"]",
"=",
"None",
"return",
"args"
] |
Adds key-value pairs to the passed dictionary, so that
afterwards, the dictionary can be used without needing
to check for KeyErrors.
If the keys passed as a second argument are not present,
they are added with None as a value.
:args: The dictionary to be completed.
:optional_args: The keys that need to be added, if
they are not present.
:return: The modified dictionary.
|
[
"Adds",
"key",
"-",
"value",
"pairs",
"to",
"the",
"passed",
"dictionary",
"so",
"that",
"afterwards",
"the",
"dictionary",
"can",
"be",
"used",
"without",
"needing",
"to",
"check",
"for",
"KeyErrors",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/util/argsutils.py#L3-L21
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/util/argsutils.py
|
check_presence_of_mandatory_args
|
def check_presence_of_mandatory_args(args, mandatory_args):
'''
Checks whether all mandatory arguments are passed.
This function aims at methods with many arguments
which are passed as kwargs so that the order
in which the are passed does not matter.
:args: The dictionary passed as args.
:mandatory_args: A list of keys that have to be
present in the dictionary.
:raise: :exc:`~ValueError`
:returns: True, if all mandatory args are passed. If not,
an exception is raised.
'''
missing_args = []
for name in mandatory_args:
if name not in args.keys():
missing_args.append(name)
if len(missing_args) > 0:
raise ValueError('Missing mandatory arguments: '+', '.join(missing_args))
else:
return True
|
python
|
def check_presence_of_mandatory_args(args, mandatory_args):
'''
Checks whether all mandatory arguments are passed.
This function aims at methods with many arguments
which are passed as kwargs so that the order
in which the are passed does not matter.
:args: The dictionary passed as args.
:mandatory_args: A list of keys that have to be
present in the dictionary.
:raise: :exc:`~ValueError`
:returns: True, if all mandatory args are passed. If not,
an exception is raised.
'''
missing_args = []
for name in mandatory_args:
if name not in args.keys():
missing_args.append(name)
if len(missing_args) > 0:
raise ValueError('Missing mandatory arguments: '+', '.join(missing_args))
else:
return True
|
[
"def",
"check_presence_of_mandatory_args",
"(",
"args",
",",
"mandatory_args",
")",
":",
"missing_args",
"=",
"[",
"]",
"for",
"name",
"in",
"mandatory_args",
":",
"if",
"name",
"not",
"in",
"args",
".",
"keys",
"(",
")",
":",
"missing_args",
".",
"append",
"(",
"name",
")",
"if",
"len",
"(",
"missing_args",
")",
">",
"0",
":",
"raise",
"ValueError",
"(",
"'Missing mandatory arguments: '",
"+",
"', '",
".",
"join",
"(",
"missing_args",
")",
")",
"else",
":",
"return",
"True"
] |
Checks whether all mandatory arguments are passed.
This function aims at methods with many arguments
which are passed as kwargs so that the order
in which the are passed does not matter.
:args: The dictionary passed as args.
:mandatory_args: A list of keys that have to be
present in the dictionary.
:raise: :exc:`~ValueError`
:returns: True, if all mandatory args are passed. If not,
an exception is raised.
|
[
"Checks",
"whether",
"all",
"mandatory",
"arguments",
"are",
"passed",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/util/argsutils.py#L24-L47
|
train
|
ipazc/pyzip
|
pyzip/__init__.py
|
PyZip.size
|
def size(self, store_hashes=True):
"""
Retrieves the size in bytes of this ZIP content.
:return: Size of the zip content in bytes
"""
if self.modified:
self.__cache_content(store_hashes)
return len(self.cached_content)
|
python
|
def size(self, store_hashes=True):
"""
Retrieves the size in bytes of this ZIP content.
:return: Size of the zip content in bytes
"""
if self.modified:
self.__cache_content(store_hashes)
return len(self.cached_content)
|
[
"def",
"size",
"(",
"self",
",",
"store_hashes",
"=",
"True",
")",
":",
"if",
"self",
".",
"modified",
":",
"self",
".",
"__cache_content",
"(",
"store_hashes",
")",
"return",
"len",
"(",
"self",
".",
"cached_content",
")"
] |
Retrieves the size in bytes of this ZIP content.
:return: Size of the zip content in bytes
|
[
"Retrieves",
"the",
"size",
"in",
"bytes",
"of",
"this",
"ZIP",
"content",
".",
":",
"return",
":",
"Size",
"of",
"the",
"zip",
"content",
"in",
"bytes"
] |
8680775ddba079a9a04ef3904252a9afb62cb7cc
|
https://github.com/ipazc/pyzip/blob/8680775ddba079a9a04ef3904252a9afb62cb7cc/pyzip/__init__.py#L171-L179
|
train
|
alexhayes/django-migration-fixture
|
django_migration_fixture/management/commands/create_initial_data_fixtures.py
|
Command.monkey_patch_migration_template
|
def monkey_patch_migration_template(self, app, fixture_path):
"""
Monkey patch the django.db.migrations.writer.MIGRATION_TEMPLATE
Monkey patching django.db.migrations.writer.MIGRATION_TEMPLATE means that we
don't have to do any complex regex or reflection.
It's hacky... but works atm.
"""
self._MIGRATION_TEMPLATE = writer.MIGRATION_TEMPLATE
module_split = app.module.__name__.split('.')
if len(module_split) == 1:
module_import = "import %s\n" % module_split[0]
else:
module_import = "from %s import %s\n" % (
'.'.join(module_split[:-1]),
module_split[-1:][0],
)
writer.MIGRATION_TEMPLATE = writer.MIGRATION_TEMPLATE\
.replace(
'%(imports)s',
"%(imports)s" + "\nfrom django_migration_fixture import fixture\n%s" % module_import
)\
.replace(
'%(operations)s',
" migrations.RunPython(**fixture(%s, ['%s'])),\n" % (
app.label,
os.path.basename(fixture_path)
) + "%(operations)s\n"
)
|
python
|
def monkey_patch_migration_template(self, app, fixture_path):
"""
Monkey patch the django.db.migrations.writer.MIGRATION_TEMPLATE
Monkey patching django.db.migrations.writer.MIGRATION_TEMPLATE means that we
don't have to do any complex regex or reflection.
It's hacky... but works atm.
"""
self._MIGRATION_TEMPLATE = writer.MIGRATION_TEMPLATE
module_split = app.module.__name__.split('.')
if len(module_split) == 1:
module_import = "import %s\n" % module_split[0]
else:
module_import = "from %s import %s\n" % (
'.'.join(module_split[:-1]),
module_split[-1:][0],
)
writer.MIGRATION_TEMPLATE = writer.MIGRATION_TEMPLATE\
.replace(
'%(imports)s',
"%(imports)s" + "\nfrom django_migration_fixture import fixture\n%s" % module_import
)\
.replace(
'%(operations)s',
" migrations.RunPython(**fixture(%s, ['%s'])),\n" % (
app.label,
os.path.basename(fixture_path)
) + "%(operations)s\n"
)
|
[
"def",
"monkey_patch_migration_template",
"(",
"self",
",",
"app",
",",
"fixture_path",
")",
":",
"self",
".",
"_MIGRATION_TEMPLATE",
"=",
"writer",
".",
"MIGRATION_TEMPLATE",
"module_split",
"=",
"app",
".",
"module",
".",
"__name__",
".",
"split",
"(",
"'.'",
")",
"if",
"len",
"(",
"module_split",
")",
"==",
"1",
":",
"module_import",
"=",
"\"import %s\\n\"",
"%",
"module_split",
"[",
"0",
"]",
"else",
":",
"module_import",
"=",
"\"from %s import %s\\n\"",
"%",
"(",
"'.'",
".",
"join",
"(",
"module_split",
"[",
":",
"-",
"1",
"]",
")",
",",
"module_split",
"[",
"-",
"1",
":",
"]",
"[",
"0",
"]",
",",
")",
"writer",
".",
"MIGRATION_TEMPLATE",
"=",
"writer",
".",
"MIGRATION_TEMPLATE",
".",
"replace",
"(",
"'%(imports)s'",
",",
"\"%(imports)s\"",
"+",
"\"\\nfrom django_migration_fixture import fixture\\n%s\"",
"%",
"module_import",
")",
".",
"replace",
"(",
"'%(operations)s'",
",",
"\" migrations.RunPython(**fixture(%s, ['%s'])),\\n\"",
"%",
"(",
"app",
".",
"label",
",",
"os",
".",
"path",
".",
"basename",
"(",
"fixture_path",
")",
")",
"+",
"\"%(operations)s\\n\"",
")"
] |
Monkey patch the django.db.migrations.writer.MIGRATION_TEMPLATE
Monkey patching django.db.migrations.writer.MIGRATION_TEMPLATE means that we
don't have to do any complex regex or reflection.
It's hacky... but works atm.
|
[
"Monkey",
"patch",
"the",
"django",
".",
"db",
".",
"migrations",
".",
"writer",
".",
"MIGRATION_TEMPLATE"
] |
c0463edc599d96bc6f645084eb50e6e94e1f681a
|
https://github.com/alexhayes/django-migration-fixture/blob/c0463edc599d96bc6f645084eb50e6e94e1f681a/django_migration_fixture/management/commands/create_initial_data_fixtures.py#L38-L69
|
train
|
alexhayes/django-migration-fixture
|
django_migration_fixture/management/commands/create_initial_data_fixtures.py
|
Command.migration_exists
|
def migration_exists(self, app, fixture_path):
"""
Return true if it looks like a migration already exists.
"""
base_name = os.path.basename(fixture_path)
# Loop through all migrations
for migration_path in glob.glob(os.path.join(app.path, 'migrations', '*.py')):
if base_name in open(migration_path).read():
return True
return False
|
python
|
def migration_exists(self, app, fixture_path):
"""
Return true if it looks like a migration already exists.
"""
base_name = os.path.basename(fixture_path)
# Loop through all migrations
for migration_path in glob.glob(os.path.join(app.path, 'migrations', '*.py')):
if base_name in open(migration_path).read():
return True
return False
|
[
"def",
"migration_exists",
"(",
"self",
",",
"app",
",",
"fixture_path",
")",
":",
"base_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"fixture_path",
")",
"# Loop through all migrations",
"for",
"migration_path",
"in",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"app",
".",
"path",
",",
"'migrations'",
",",
"'*.py'",
")",
")",
":",
"if",
"base_name",
"in",
"open",
"(",
"migration_path",
")",
".",
"read",
"(",
")",
":",
"return",
"True",
"return",
"False"
] |
Return true if it looks like a migration already exists.
|
[
"Return",
"true",
"if",
"it",
"looks",
"like",
"a",
"migration",
"already",
"exists",
"."
] |
c0463edc599d96bc6f645084eb50e6e94e1f681a
|
https://github.com/alexhayes/django-migration-fixture/blob/c0463edc599d96bc6f645084eb50e6e94e1f681a/django_migration_fixture/management/commands/create_initial_data_fixtures.py#L77-L86
|
train
|
alexhayes/django-migration-fixture
|
django_migration_fixture/management/commands/create_initial_data_fixtures.py
|
Command.create_migration
|
def create_migration(self, app, fixture_path):
"""
Create a data migration for app that uses fixture_path.
"""
self.monkey_patch_migration_template(app, fixture_path)
out = StringIO()
management.call_command('makemigrations', app.label, empty=True, stdout=out)
self.restore_migration_template()
self.stdout.write(out.getvalue())
|
python
|
def create_migration(self, app, fixture_path):
"""
Create a data migration for app that uses fixture_path.
"""
self.monkey_patch_migration_template(app, fixture_path)
out = StringIO()
management.call_command('makemigrations', app.label, empty=True, stdout=out)
self.restore_migration_template()
self.stdout.write(out.getvalue())
|
[
"def",
"create_migration",
"(",
"self",
",",
"app",
",",
"fixture_path",
")",
":",
"self",
".",
"monkey_patch_migration_template",
"(",
"app",
",",
"fixture_path",
")",
"out",
"=",
"StringIO",
"(",
")",
"management",
".",
"call_command",
"(",
"'makemigrations'",
",",
"app",
".",
"label",
",",
"empty",
"=",
"True",
",",
"stdout",
"=",
"out",
")",
"self",
".",
"restore_migration_template",
"(",
")",
"self",
".",
"stdout",
".",
"write",
"(",
"out",
".",
"getvalue",
"(",
")",
")"
] |
Create a data migration for app that uses fixture_path.
|
[
"Create",
"a",
"data",
"migration",
"for",
"app",
"that",
"uses",
"fixture_path",
"."
] |
c0463edc599d96bc6f645084eb50e6e94e1f681a
|
https://github.com/alexhayes/django-migration-fixture/blob/c0463edc599d96bc6f645084eb50e6e94e1f681a/django_migration_fixture/management/commands/create_initial_data_fixtures.py#L88-L99
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/handleclient.py
|
EUDATHandleClient.instantiate_for_read_and_search
|
def instantiate_for_read_and_search(handle_server_url, reverselookup_username, reverselookup_password, **config):
'''
Initialize client with read access and with search function.
:param handle_server_url: The URL of the Handle Server. May be None
(then, the default 'https://hdl.handle.net' is used).
:param reverselookup_username: The username to authenticate at the
reverse lookup servlet.
:param reverselookup_password: The password to authenticate at the
reverse lookup servlet.
:param \**config: More key-value pairs may be passed that will be passed
on to the constructor as config. Config options from the
credentials object are overwritten by this.
:return: An instance of the client.
'''
if handle_server_url is None and 'reverselookup_baseuri' not in config.keys():
raise TypeError('You must specify either "handle_server_url" or "reverselookup_baseuri".' + \
' Searching not possible without the URL of a search servlet.')
inst = EUDATHandleClient(
handle_server_url,
reverselookup_username=reverselookup_username,
reverselookup_password=reverselookup_password,
**config
)
return inst
|
python
|
def instantiate_for_read_and_search(handle_server_url, reverselookup_username, reverselookup_password, **config):
'''
Initialize client with read access and with search function.
:param handle_server_url: The URL of the Handle Server. May be None
(then, the default 'https://hdl.handle.net' is used).
:param reverselookup_username: The username to authenticate at the
reverse lookup servlet.
:param reverselookup_password: The password to authenticate at the
reverse lookup servlet.
:param \**config: More key-value pairs may be passed that will be passed
on to the constructor as config. Config options from the
credentials object are overwritten by this.
:return: An instance of the client.
'''
if handle_server_url is None and 'reverselookup_baseuri' not in config.keys():
raise TypeError('You must specify either "handle_server_url" or "reverselookup_baseuri".' + \
' Searching not possible without the URL of a search servlet.')
inst = EUDATHandleClient(
handle_server_url,
reverselookup_username=reverselookup_username,
reverselookup_password=reverselookup_password,
**config
)
return inst
|
[
"def",
"instantiate_for_read_and_search",
"(",
"handle_server_url",
",",
"reverselookup_username",
",",
"reverselookup_password",
",",
"*",
"*",
"config",
")",
":",
"if",
"handle_server_url",
"is",
"None",
"and",
"'reverselookup_baseuri'",
"not",
"in",
"config",
".",
"keys",
"(",
")",
":",
"raise",
"TypeError",
"(",
"'You must specify either \"handle_server_url\" or \"reverselookup_baseuri\".'",
"+",
"' Searching not possible without the URL of a search servlet.'",
")",
"inst",
"=",
"EUDATHandleClient",
"(",
"handle_server_url",
",",
"reverselookup_username",
"=",
"reverselookup_username",
",",
"reverselookup_password",
"=",
"reverselookup_password",
",",
"*",
"*",
"config",
")",
"return",
"inst"
] |
Initialize client with read access and with search function.
:param handle_server_url: The URL of the Handle Server. May be None
(then, the default 'https://hdl.handle.net' is used).
:param reverselookup_username: The username to authenticate at the
reverse lookup servlet.
:param reverselookup_password: The password to authenticate at the
reverse lookup servlet.
:param \**config: More key-value pairs may be passed that will be passed
on to the constructor as config. Config options from the
credentials object are overwritten by this.
:return: An instance of the client.
|
[
"Initialize",
"client",
"with",
"read",
"access",
"and",
"with",
"search",
"function",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handleclient.py#L183-L209
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/handleclient.py
|
EUDATHandleClient.instantiate_with_username_and_password
|
def instantiate_with_username_and_password(handle_server_url, username, password, **config):
'''
Initialize client against an HSv8 instance with full read/write access.
The method will throw an exception upon bad syntax or non-existing
Handle. The existence or validity of the password in the handle is
not checked at this moment.
:param handle_server_url: The URL of the Handle System server.
:param username: This must be a handle value reference in the format
"index:prefix/suffix".
:param password: This is the password stored as secret key in the
actual Handle value the username points to.
:param \**config: More key-value pairs may be passed that will be passed
on to the constructor as config.
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`: If the username handle is not found.
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
:return: An instance of the client.
'''
inst = EUDATHandleClient(handle_server_url, username=username, password=password, **config)
return inst
|
python
|
def instantiate_with_username_and_password(handle_server_url, username, password, **config):
'''
Initialize client against an HSv8 instance with full read/write access.
The method will throw an exception upon bad syntax or non-existing
Handle. The existence or validity of the password in the handle is
not checked at this moment.
:param handle_server_url: The URL of the Handle System server.
:param username: This must be a handle value reference in the format
"index:prefix/suffix".
:param password: This is the password stored as secret key in the
actual Handle value the username points to.
:param \**config: More key-value pairs may be passed that will be passed
on to the constructor as config.
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`: If the username handle is not found.
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
:return: An instance of the client.
'''
inst = EUDATHandleClient(handle_server_url, username=username, password=password, **config)
return inst
|
[
"def",
"instantiate_with_username_and_password",
"(",
"handle_server_url",
",",
"username",
",",
"password",
",",
"*",
"*",
"config",
")",
":",
"inst",
"=",
"EUDATHandleClient",
"(",
"handle_server_url",
",",
"username",
"=",
"username",
",",
"password",
"=",
"password",
",",
"*",
"*",
"config",
")",
"return",
"inst"
] |
Initialize client against an HSv8 instance with full read/write access.
The method will throw an exception upon bad syntax or non-existing
Handle. The existence or validity of the password in the handle is
not checked at this moment.
:param handle_server_url: The URL of the Handle System server.
:param username: This must be a handle value reference in the format
"index:prefix/suffix".
:param password: This is the password stored as secret key in the
actual Handle value the username points to.
:param \**config: More key-value pairs may be passed that will be passed
on to the constructor as config.
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`: If the username handle is not found.
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
:return: An instance of the client.
|
[
"Initialize",
"client",
"against",
"an",
"HSv8",
"instance",
"with",
"full",
"read",
"/",
"write",
"access",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handleclient.py#L212-L233
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/handleclient.py
|
EUDATHandleClient.instantiate_with_credentials
|
def instantiate_with_credentials(credentials, **config):
'''
Initialize the client against an HSv8 instance with full read/write
access.
:param credentials: A credentials object, see separate class
PIDClientCredentials.
:param \**config: More key-value pairs may be passed that will be passed
on to the constructor as config. Config options from the
credentials object are overwritten by this.
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`: If the username handle is not found.
:return: An instance of the client.
'''
key_value_pairs = credentials.get_all_args()
if config is not None:
key_value_pairs.update(**config) # passed config overrides json file
inst = EUDATHandleClient(**key_value_pairs)
return inst
|
python
|
def instantiate_with_credentials(credentials, **config):
'''
Initialize the client against an HSv8 instance with full read/write
access.
:param credentials: A credentials object, see separate class
PIDClientCredentials.
:param \**config: More key-value pairs may be passed that will be passed
on to the constructor as config. Config options from the
credentials object are overwritten by this.
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`: If the username handle is not found.
:return: An instance of the client.
'''
key_value_pairs = credentials.get_all_args()
if config is not None:
key_value_pairs.update(**config) # passed config overrides json file
inst = EUDATHandleClient(**key_value_pairs)
return inst
|
[
"def",
"instantiate_with_credentials",
"(",
"credentials",
",",
"*",
"*",
"config",
")",
":",
"key_value_pairs",
"=",
"credentials",
".",
"get_all_args",
"(",
")",
"if",
"config",
"is",
"not",
"None",
":",
"key_value_pairs",
".",
"update",
"(",
"*",
"*",
"config",
")",
"# passed config overrides json file",
"inst",
"=",
"EUDATHandleClient",
"(",
"*",
"*",
"key_value_pairs",
")",
"return",
"inst"
] |
Initialize the client against an HSv8 instance with full read/write
access.
:param credentials: A credentials object, see separate class
PIDClientCredentials.
:param \**config: More key-value pairs may be passed that will be passed
on to the constructor as config. Config options from the
credentials object are overwritten by this.
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`: If the username handle is not found.
:return: An instance of the client.
|
[
"Initialize",
"the",
"client",
"against",
"an",
"HSv8",
"instance",
"with",
"full",
"read",
"/",
"write",
"access",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handleclient.py#L236-L255
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/handleclient.py
|
EUDATHandleClient.retrieve_handle_record_json
|
def retrieve_handle_record_json(self, handle):
'''
Retrieve a handle record from the Handle server as a complete nested
dict (including index, ttl, timestamp, ...) for later use.
Note: For retrieving a simple dict with only the keys and values,
please use :meth:`~b2handle.handleclient.EUDATHandleClient.retrieve_handle_record`.
:param handle: The Handle whose record to retrieve.
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
:return: The handle record as a nested dict. If the handle does not
exist, returns None.
'''
LOGGER.debug('retrieve_handle_record_json...')
utilhandle.check_handle_syntax(handle)
response = self.__send_handle_get_request(handle)
response_content = decoded_response(response)
if hsresponses.handle_not_found(response):
return None
elif hsresponses.does_handle_exist(response):
handlerecord_json = json.loads(response_content)
if not handlerecord_json['handle'] == handle:
raise GenericHandleError(
operation='retrieving handle record',
handle=handle,
response=response,
custom_message='The retrieve returned a different handle than was asked for.'
)
return handlerecord_json
elif hsresponses.is_handle_empty(response):
handlerecord_json = json.loads(response_content)
return handlerecord_json
else:
raise GenericHandleError(
operation='retrieving',
handle=handle,
response=response
)
|
python
|
def retrieve_handle_record_json(self, handle):
'''
Retrieve a handle record from the Handle server as a complete nested
dict (including index, ttl, timestamp, ...) for later use.
Note: For retrieving a simple dict with only the keys and values,
please use :meth:`~b2handle.handleclient.EUDATHandleClient.retrieve_handle_record`.
:param handle: The Handle whose record to retrieve.
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
:return: The handle record as a nested dict. If the handle does not
exist, returns None.
'''
LOGGER.debug('retrieve_handle_record_json...')
utilhandle.check_handle_syntax(handle)
response = self.__send_handle_get_request(handle)
response_content = decoded_response(response)
if hsresponses.handle_not_found(response):
return None
elif hsresponses.does_handle_exist(response):
handlerecord_json = json.loads(response_content)
if not handlerecord_json['handle'] == handle:
raise GenericHandleError(
operation='retrieving handle record',
handle=handle,
response=response,
custom_message='The retrieve returned a different handle than was asked for.'
)
return handlerecord_json
elif hsresponses.is_handle_empty(response):
handlerecord_json = json.loads(response_content)
return handlerecord_json
else:
raise GenericHandleError(
operation='retrieving',
handle=handle,
response=response
)
|
[
"def",
"retrieve_handle_record_json",
"(",
"self",
",",
"handle",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'retrieve_handle_record_json...'",
")",
"utilhandle",
".",
"check_handle_syntax",
"(",
"handle",
")",
"response",
"=",
"self",
".",
"__send_handle_get_request",
"(",
"handle",
")",
"response_content",
"=",
"decoded_response",
"(",
"response",
")",
"if",
"hsresponses",
".",
"handle_not_found",
"(",
"response",
")",
":",
"return",
"None",
"elif",
"hsresponses",
".",
"does_handle_exist",
"(",
"response",
")",
":",
"handlerecord_json",
"=",
"json",
".",
"loads",
"(",
"response_content",
")",
"if",
"not",
"handlerecord_json",
"[",
"'handle'",
"]",
"==",
"handle",
":",
"raise",
"GenericHandleError",
"(",
"operation",
"=",
"'retrieving handle record'",
",",
"handle",
"=",
"handle",
",",
"response",
"=",
"response",
",",
"custom_message",
"=",
"'The retrieve returned a different handle than was asked for.'",
")",
"return",
"handlerecord_json",
"elif",
"hsresponses",
".",
"is_handle_empty",
"(",
"response",
")",
":",
"handlerecord_json",
"=",
"json",
".",
"loads",
"(",
"response_content",
")",
"return",
"handlerecord_json",
"else",
":",
"raise",
"GenericHandleError",
"(",
"operation",
"=",
"'retrieving'",
",",
"handle",
"=",
"handle",
",",
"response",
"=",
"response",
")"
] |
Retrieve a handle record from the Handle server as a complete nested
dict (including index, ttl, timestamp, ...) for later use.
Note: For retrieving a simple dict with only the keys and values,
please use :meth:`~b2handle.handleclient.EUDATHandleClient.retrieve_handle_record`.
:param handle: The Handle whose record to retrieve.
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
:return: The handle record as a nested dict. If the handle does not
exist, returns None.
|
[
"Retrieve",
"a",
"handle",
"record",
"from",
"the",
"Handle",
"server",
"as",
"a",
"complete",
"nested",
"dict",
"(",
"including",
"index",
"ttl",
"timestamp",
"...",
")",
"for",
"later",
"use",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handleclient.py#L259-L299
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/handleclient.py
|
EUDATHandleClient.retrieve_handle_record
|
def retrieve_handle_record(self, handle, handlerecord_json=None):
'''
Retrieve a handle record from the Handle server as a dict. If there
is several entries of the same type, only the first one is
returned. Values of complex types (such as HS_ADMIN) are
transformed to strings.
:param handle: The handle whose record to retrieve.
:param handlerecord_json: Optional. If the handlerecord has already
been retrieved from the server, it can be reused.
:return: A dict where the keys are keys from the Handle record (except
for hidden entries) and every value is a string. The result will be
None if the Handle does not exist.
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
'''
LOGGER.debug('retrieve_handle_record...')
handlerecord_json = self.__get_handle_record_if_necessary(handle, handlerecord_json)
if handlerecord_json is None:
return None # Instead of HandleNotFoundException!
list_of_entries = handlerecord_json['values']
record_as_dict = {}
for entry in list_of_entries:
key = entry['type']
if not key in record_as_dict.keys():
record_as_dict[key] = str(entry['data']['value'])
return record_as_dict
|
python
|
def retrieve_handle_record(self, handle, handlerecord_json=None):
'''
Retrieve a handle record from the Handle server as a dict. If there
is several entries of the same type, only the first one is
returned. Values of complex types (such as HS_ADMIN) are
transformed to strings.
:param handle: The handle whose record to retrieve.
:param handlerecord_json: Optional. If the handlerecord has already
been retrieved from the server, it can be reused.
:return: A dict where the keys are keys from the Handle record (except
for hidden entries) and every value is a string. The result will be
None if the Handle does not exist.
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
'''
LOGGER.debug('retrieve_handle_record...')
handlerecord_json = self.__get_handle_record_if_necessary(handle, handlerecord_json)
if handlerecord_json is None:
return None # Instead of HandleNotFoundException!
list_of_entries = handlerecord_json['values']
record_as_dict = {}
for entry in list_of_entries:
key = entry['type']
if not key in record_as_dict.keys():
record_as_dict[key] = str(entry['data']['value'])
return record_as_dict
|
[
"def",
"retrieve_handle_record",
"(",
"self",
",",
"handle",
",",
"handlerecord_json",
"=",
"None",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'retrieve_handle_record...'",
")",
"handlerecord_json",
"=",
"self",
".",
"__get_handle_record_if_necessary",
"(",
"handle",
",",
"handlerecord_json",
")",
"if",
"handlerecord_json",
"is",
"None",
":",
"return",
"None",
"# Instead of HandleNotFoundException!",
"list_of_entries",
"=",
"handlerecord_json",
"[",
"'values'",
"]",
"record_as_dict",
"=",
"{",
"}",
"for",
"entry",
"in",
"list_of_entries",
":",
"key",
"=",
"entry",
"[",
"'type'",
"]",
"if",
"not",
"key",
"in",
"record_as_dict",
".",
"keys",
"(",
")",
":",
"record_as_dict",
"[",
"key",
"]",
"=",
"str",
"(",
"entry",
"[",
"'data'",
"]",
"[",
"'value'",
"]",
")",
"return",
"record_as_dict"
] |
Retrieve a handle record from the Handle server as a dict. If there
is several entries of the same type, only the first one is
returned. Values of complex types (such as HS_ADMIN) are
transformed to strings.
:param handle: The handle whose record to retrieve.
:param handlerecord_json: Optional. If the handlerecord has already
been retrieved from the server, it can be reused.
:return: A dict where the keys are keys from the Handle record (except
for hidden entries) and every value is a string. The result will be
None if the Handle does not exist.
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
|
[
"Retrieve",
"a",
"handle",
"record",
"from",
"the",
"Handle",
"server",
"as",
"a",
"dict",
".",
"If",
"there",
"is",
"several",
"entries",
"of",
"the",
"same",
"type",
"only",
"the",
"first",
"one",
"is",
"returned",
".",
"Values",
"of",
"complex",
"types",
"(",
"such",
"as",
"HS_ADMIN",
")",
"are",
"transformed",
"to",
"strings",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handleclient.py#L302-L329
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/handleclient.py
|
EUDATHandleClient.get_value_from_handle
|
def get_value_from_handle(self, handle, key, handlerecord_json=None):
'''
Retrieve a single value from a single Handle. If several entries with
this key exist, the methods returns the first one. If the handle
does not exist, the method will raise a HandleNotFoundException.
:param handle: The handle to take the value from.
:param key: The key.
:return: A string containing the value or None if the Handle record
does not contain the key.
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
'''
LOGGER.debug('get_value_from_handle...')
handlerecord_json = self.__get_handle_record_if_necessary(handle, handlerecord_json)
if handlerecord_json is None:
raise HandleNotFoundException(handle=handle)
list_of_entries = handlerecord_json['values']
indices = []
for i in xrange(len(list_of_entries)):
if list_of_entries[i]['type'] == key:
indices.append(i)
if len(indices) == 0:
return None
else:
if len(indices) > 1:
LOGGER.debug('get_value_from_handle: The handle ' + handle + \
' contains several entries of type "' + key + \
'". Only the first one is returned.')
return list_of_entries[indices[0]]['data']['value']
|
python
|
def get_value_from_handle(self, handle, key, handlerecord_json=None):
'''
Retrieve a single value from a single Handle. If several entries with
this key exist, the methods returns the first one. If the handle
does not exist, the method will raise a HandleNotFoundException.
:param handle: The handle to take the value from.
:param key: The key.
:return: A string containing the value or None if the Handle record
does not contain the key.
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
'''
LOGGER.debug('get_value_from_handle...')
handlerecord_json = self.__get_handle_record_if_necessary(handle, handlerecord_json)
if handlerecord_json is None:
raise HandleNotFoundException(handle=handle)
list_of_entries = handlerecord_json['values']
indices = []
for i in xrange(len(list_of_entries)):
if list_of_entries[i]['type'] == key:
indices.append(i)
if len(indices) == 0:
return None
else:
if len(indices) > 1:
LOGGER.debug('get_value_from_handle: The handle ' + handle + \
' contains several entries of type "' + key + \
'". Only the first one is returned.')
return list_of_entries[indices[0]]['data']['value']
|
[
"def",
"get_value_from_handle",
"(",
"self",
",",
"handle",
",",
"key",
",",
"handlerecord_json",
"=",
"None",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'get_value_from_handle...'",
")",
"handlerecord_json",
"=",
"self",
".",
"__get_handle_record_if_necessary",
"(",
"handle",
",",
"handlerecord_json",
")",
"if",
"handlerecord_json",
"is",
"None",
":",
"raise",
"HandleNotFoundException",
"(",
"handle",
"=",
"handle",
")",
"list_of_entries",
"=",
"handlerecord_json",
"[",
"'values'",
"]",
"indices",
"=",
"[",
"]",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"list_of_entries",
")",
")",
":",
"if",
"list_of_entries",
"[",
"i",
"]",
"[",
"'type'",
"]",
"==",
"key",
":",
"indices",
".",
"append",
"(",
"i",
")",
"if",
"len",
"(",
"indices",
")",
"==",
"0",
":",
"return",
"None",
"else",
":",
"if",
"len",
"(",
"indices",
")",
">",
"1",
":",
"LOGGER",
".",
"debug",
"(",
"'get_value_from_handle: The handle '",
"+",
"handle",
"+",
"' contains several entries of type \"'",
"+",
"key",
"+",
"'\". Only the first one is returned.'",
")",
"return",
"list_of_entries",
"[",
"indices",
"[",
"0",
"]",
"]",
"[",
"'data'",
"]",
"[",
"'value'",
"]"
] |
Retrieve a single value from a single Handle. If several entries with
this key exist, the methods returns the first one. If the handle
does not exist, the method will raise a HandleNotFoundException.
:param handle: The handle to take the value from.
:param key: The key.
:return: A string containing the value or None if the Handle record
does not contain the key.
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
|
[
"Retrieve",
"a",
"single",
"value",
"from",
"a",
"single",
"Handle",
".",
"If",
"several",
"entries",
"with",
"this",
"key",
"exist",
"the",
"methods",
"returns",
"the",
"first",
"one",
".",
"If",
"the",
"handle",
"does",
"not",
"exist",
"the",
"method",
"will",
"raise",
"a",
"HandleNotFoundException",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handleclient.py#L331-L363
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/handleclient.py
|
EUDATHandleClient.is_10320LOC_empty
|
def is_10320LOC_empty(self, handle, handlerecord_json=None):
'''
Checks if there is a 10320/LOC entry in the handle record.
*Note:* In the unlikely case that there is a 10320/LOC entry, but it does
not contain any locations, it is treated as if there was none.
:param handle: The handle.
:param handlerecord_json: Optional. The content of the response of a
GET request for the handle as a dict. Avoids another GET request.
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
:return: True if the record contains NO 10320/LOC entry; False if it
does contain one.
'''
LOGGER.debug('is_10320LOC_empty...')
handlerecord_json = self.__get_handle_record_if_necessary(handle, handlerecord_json)
if handlerecord_json is None:
raise HandleNotFoundException(handle=handle)
list_of_entries = handlerecord_json['values']
num_entries = 0
num_URL = 0
for entry in list_of_entries:
if entry['type'] == '10320/LOC':
num_entries += 1
xmlroot = ET.fromstring(entry['data']['value'])
list_of_locations = xmlroot.findall('location')
for item in list_of_locations:
if item.get('href') is not None:
num_URL += 1
if num_entries == 0:
return True
else:
if num_URL == 0:
return True
else:
return False
|
python
|
def is_10320LOC_empty(self, handle, handlerecord_json=None):
'''
Checks if there is a 10320/LOC entry in the handle record.
*Note:* In the unlikely case that there is a 10320/LOC entry, but it does
not contain any locations, it is treated as if there was none.
:param handle: The handle.
:param handlerecord_json: Optional. The content of the response of a
GET request for the handle as a dict. Avoids another GET request.
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
:return: True if the record contains NO 10320/LOC entry; False if it
does contain one.
'''
LOGGER.debug('is_10320LOC_empty...')
handlerecord_json = self.__get_handle_record_if_necessary(handle, handlerecord_json)
if handlerecord_json is None:
raise HandleNotFoundException(handle=handle)
list_of_entries = handlerecord_json['values']
num_entries = 0
num_URL = 0
for entry in list_of_entries:
if entry['type'] == '10320/LOC':
num_entries += 1
xmlroot = ET.fromstring(entry['data']['value'])
list_of_locations = xmlroot.findall('location')
for item in list_of_locations:
if item.get('href') is not None:
num_URL += 1
if num_entries == 0:
return True
else:
if num_URL == 0:
return True
else:
return False
|
[
"def",
"is_10320LOC_empty",
"(",
"self",
",",
"handle",
",",
"handlerecord_json",
"=",
"None",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'is_10320LOC_empty...'",
")",
"handlerecord_json",
"=",
"self",
".",
"__get_handle_record_if_necessary",
"(",
"handle",
",",
"handlerecord_json",
")",
"if",
"handlerecord_json",
"is",
"None",
":",
"raise",
"HandleNotFoundException",
"(",
"handle",
"=",
"handle",
")",
"list_of_entries",
"=",
"handlerecord_json",
"[",
"'values'",
"]",
"num_entries",
"=",
"0",
"num_URL",
"=",
"0",
"for",
"entry",
"in",
"list_of_entries",
":",
"if",
"entry",
"[",
"'type'",
"]",
"==",
"'10320/LOC'",
":",
"num_entries",
"+=",
"1",
"xmlroot",
"=",
"ET",
".",
"fromstring",
"(",
"entry",
"[",
"'data'",
"]",
"[",
"'value'",
"]",
")",
"list_of_locations",
"=",
"xmlroot",
".",
"findall",
"(",
"'location'",
")",
"for",
"item",
"in",
"list_of_locations",
":",
"if",
"item",
".",
"get",
"(",
"'href'",
")",
"is",
"not",
"None",
":",
"num_URL",
"+=",
"1",
"if",
"num_entries",
"==",
"0",
":",
"return",
"True",
"else",
":",
"if",
"num_URL",
"==",
"0",
":",
"return",
"True",
"else",
":",
"return",
"False"
] |
Checks if there is a 10320/LOC entry in the handle record.
*Note:* In the unlikely case that there is a 10320/LOC entry, but it does
not contain any locations, it is treated as if there was none.
:param handle: The handle.
:param handlerecord_json: Optional. The content of the response of a
GET request for the handle as a dict. Avoids another GET request.
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
:return: True if the record contains NO 10320/LOC entry; False if it
does contain one.
|
[
"Checks",
"if",
"there",
"is",
"a",
"10320",
"/",
"LOC",
"entry",
"in",
"the",
"handle",
"record",
".",
"*",
"Note",
":",
"*",
"In",
"the",
"unlikely",
"case",
"that",
"there",
"is",
"a",
"10320",
"/",
"LOC",
"entry",
"but",
"it",
"does",
"not",
"contain",
"any",
"locations",
"it",
"is",
"treated",
"as",
"if",
"there",
"was",
"none",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handleclient.py#L365-L402
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/handleclient.py
|
EUDATHandleClient.generate_and_register_handle
|
def generate_and_register_handle(self, prefix, location, checksum=None, additional_URLs=None, **extratypes):
'''
Register a new Handle with a unique random name (random UUID).
:param prefix: The prefix of the handle to be registered. The method
will generate a suffix.
:param location: The URL of the data entity to be referenced.
:param checksum: Optional. The checksum string.
:param extratypes: Optional. Additional key value pairs as dict.
:param additional_URLs: Optional. A list of URLs (as strings) to be
added to the handle record as 10320/LOC entry.
:raises: :exc:`~b2handle.handleexceptions.HandleAuthenticationError`
:return: The new handle name.
'''
LOGGER.debug('generate_and_register_handle...')
handle = self.generate_PID_name(prefix)
handle = self.register_handle(
handle,
location,
checksum,
additional_URLs,
overwrite=True,
**extratypes
)
return handle
|
python
|
def generate_and_register_handle(self, prefix, location, checksum=None, additional_URLs=None, **extratypes):
'''
Register a new Handle with a unique random name (random UUID).
:param prefix: The prefix of the handle to be registered. The method
will generate a suffix.
:param location: The URL of the data entity to be referenced.
:param checksum: Optional. The checksum string.
:param extratypes: Optional. Additional key value pairs as dict.
:param additional_URLs: Optional. A list of URLs (as strings) to be
added to the handle record as 10320/LOC entry.
:raises: :exc:`~b2handle.handleexceptions.HandleAuthenticationError`
:return: The new handle name.
'''
LOGGER.debug('generate_and_register_handle...')
handle = self.generate_PID_name(prefix)
handle = self.register_handle(
handle,
location,
checksum,
additional_URLs,
overwrite=True,
**extratypes
)
return handle
|
[
"def",
"generate_and_register_handle",
"(",
"self",
",",
"prefix",
",",
"location",
",",
"checksum",
"=",
"None",
",",
"additional_URLs",
"=",
"None",
",",
"*",
"*",
"extratypes",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'generate_and_register_handle...'",
")",
"handle",
"=",
"self",
".",
"generate_PID_name",
"(",
"prefix",
")",
"handle",
"=",
"self",
".",
"register_handle",
"(",
"handle",
",",
"location",
",",
"checksum",
",",
"additional_URLs",
",",
"overwrite",
"=",
"True",
",",
"*",
"*",
"extratypes",
")",
"return",
"handle"
] |
Register a new Handle with a unique random name (random UUID).
:param prefix: The prefix of the handle to be registered. The method
will generate a suffix.
:param location: The URL of the data entity to be referenced.
:param checksum: Optional. The checksum string.
:param extratypes: Optional. Additional key value pairs as dict.
:param additional_URLs: Optional. A list of URLs (as strings) to be
added to the handle record as 10320/LOC entry.
:raises: :exc:`~b2handle.handleexceptions.HandleAuthenticationError`
:return: The new handle name.
|
[
"Register",
"a",
"new",
"Handle",
"with",
"a",
"unique",
"random",
"name",
"(",
"random",
"UUID",
")",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handleclient.py#L445-L471
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/handleclient.py
|
EUDATHandleClient.modify_handle_value
|
def modify_handle_value(self, handle, ttl=None, add_if_not_exist=True, **kvpairs):
'''
Modify entries (key-value-pairs) in a handle record. If the key
does not exist yet, it is created.
*Note:* We assume that a key exists only once. In case a key exists
several time, an exception will be raised.
*Note:* To modify 10320/LOC, please use :meth:`~b2handle.handleclient.EUDATHandleClient.add_additional_URL` or
:meth:`~b2handle.handleclient.EUDATHandleClient.remove_additional_URL`.
:param handle: Handle whose record is to be modified
:param ttl: Optional. Integer value. If ttl should be set to a
non-default value.
:param all other args: The user can specify several key-value-pairs.
These will be the handle value types and values that will be
modified. The keys are the names or the handle value types (e.g.
"URL"). The values are the new values to store in "data". If the
key is 'HS_ADMIN', the new value needs to be of the form
{'handle':'xyz', 'index':xyz}. The permissions will be set to the
default permissions.
:raises: :exc:`~b2handle.handleexceptions.HandleAuthenticationError`
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
'''
LOGGER.debug('modify_handle_value...')
# Read handle record:
handlerecord_json = self.retrieve_handle_record_json(handle)
if handlerecord_json is None:
msg = 'Cannot modify unexisting handle'
raise HandleNotFoundException(handle=handle, msg=msg)
list_of_entries = handlerecord_json['values']
# HS_ADMIN
if 'HS_ADMIN' in kvpairs.keys() and not self.__modify_HS_ADMIN:
msg = 'You may not modify HS_ADMIN'
raise IllegalOperationException(
msg=msg,
operation='modifying HS_ADMIN',
handle=handle
)
nothingchanged = True
new_list_of_entries = []
list_of_old_and_new_entries = list_of_entries[:]
keys = kvpairs.keys()
for key, newval in kvpairs.items():
# Change existing entry:
changed = False
for i in xrange(len(list_of_entries)):
if list_of_entries[i]['type'] == key:
if not changed:
list_of_entries[i]['data'] = newval
list_of_entries[i].pop('timestamp') # will be ignored anyway
if key == 'HS_ADMIN':
newval['permissions'] = self.__HS_ADMIN_permissions
list_of_entries[i].pop('timestamp') # will be ignored anyway
list_of_entries[i]['data'] = {
'format':'admin',
'value':newval
}
LOGGER.info('Modified' + \
' "HS_ADMIN" of handle ' + handle)
changed = True
nothingchanged = False
new_list_of_entries.append(list_of_entries[i])
list_of_old_and_new_entries.append(list_of_entries[i])
else:
msg = 'There is several entries of type "' + key + '".' + \
' This can lead to unexpected behaviour.' + \
' Please clean up before modifying the record.'
raise BrokenHandleRecordException(handle=handle, msg=msg)
# If the entry doesn't exist yet, add it:
if not changed:
if add_if_not_exist:
LOGGER.debug('modify_handle_value: Adding entry "' + key + '"' + \
' to handle ' + handle)
index = self.__make_another_index(list_of_old_and_new_entries)
entry_to_add = self.__create_entry(key, newval, index, ttl)
new_list_of_entries.append(entry_to_add)
list_of_old_and_new_entries.append(entry_to_add)
changed = True
nothingchanged = False
# Add the indices
indices = []
for i in xrange(len(new_list_of_entries)):
indices.append(new_list_of_entries[i]['index'])
# append to the old record:
if nothingchanged:
LOGGER.debug('modify_handle_value: There was no entries ' + \
str(kvpairs.keys()) + ' to be modified (handle ' + handle + ').' + \
' To add them, set add_if_not_exist = True')
else:
op = 'modifying handle values'
resp, put_payload = self.__send_handle_put_request(
handle,
new_list_of_entries,
indices=indices,
overwrite=True,
op=op)
if hsresponses.handle_success(resp):
LOGGER.info('Handle modified: ' + handle)
else:
msg = 'Values: ' + str(kvpairs)
raise GenericHandleError(
operation=op,
handle=handle,
response=resp,
msg=msg,
payload=put_payload
)
|
python
|
def modify_handle_value(self, handle, ttl=None, add_if_not_exist=True, **kvpairs):
'''
Modify entries (key-value-pairs) in a handle record. If the key
does not exist yet, it is created.
*Note:* We assume that a key exists only once. In case a key exists
several time, an exception will be raised.
*Note:* To modify 10320/LOC, please use :meth:`~b2handle.handleclient.EUDATHandleClient.add_additional_URL` or
:meth:`~b2handle.handleclient.EUDATHandleClient.remove_additional_URL`.
:param handle: Handle whose record is to be modified
:param ttl: Optional. Integer value. If ttl should be set to a
non-default value.
:param all other args: The user can specify several key-value-pairs.
These will be the handle value types and values that will be
modified. The keys are the names or the handle value types (e.g.
"URL"). The values are the new values to store in "data". If the
key is 'HS_ADMIN', the new value needs to be of the form
{'handle':'xyz', 'index':xyz}. The permissions will be set to the
default permissions.
:raises: :exc:`~b2handle.handleexceptions.HandleAuthenticationError`
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
'''
LOGGER.debug('modify_handle_value...')
# Read handle record:
handlerecord_json = self.retrieve_handle_record_json(handle)
if handlerecord_json is None:
msg = 'Cannot modify unexisting handle'
raise HandleNotFoundException(handle=handle, msg=msg)
list_of_entries = handlerecord_json['values']
# HS_ADMIN
if 'HS_ADMIN' in kvpairs.keys() and not self.__modify_HS_ADMIN:
msg = 'You may not modify HS_ADMIN'
raise IllegalOperationException(
msg=msg,
operation='modifying HS_ADMIN',
handle=handle
)
nothingchanged = True
new_list_of_entries = []
list_of_old_and_new_entries = list_of_entries[:]
keys = kvpairs.keys()
for key, newval in kvpairs.items():
# Change existing entry:
changed = False
for i in xrange(len(list_of_entries)):
if list_of_entries[i]['type'] == key:
if not changed:
list_of_entries[i]['data'] = newval
list_of_entries[i].pop('timestamp') # will be ignored anyway
if key == 'HS_ADMIN':
newval['permissions'] = self.__HS_ADMIN_permissions
list_of_entries[i].pop('timestamp') # will be ignored anyway
list_of_entries[i]['data'] = {
'format':'admin',
'value':newval
}
LOGGER.info('Modified' + \
' "HS_ADMIN" of handle ' + handle)
changed = True
nothingchanged = False
new_list_of_entries.append(list_of_entries[i])
list_of_old_and_new_entries.append(list_of_entries[i])
else:
msg = 'There is several entries of type "' + key + '".' + \
' This can lead to unexpected behaviour.' + \
' Please clean up before modifying the record.'
raise BrokenHandleRecordException(handle=handle, msg=msg)
# If the entry doesn't exist yet, add it:
if not changed:
if add_if_not_exist:
LOGGER.debug('modify_handle_value: Adding entry "' + key + '"' + \
' to handle ' + handle)
index = self.__make_another_index(list_of_old_and_new_entries)
entry_to_add = self.__create_entry(key, newval, index, ttl)
new_list_of_entries.append(entry_to_add)
list_of_old_and_new_entries.append(entry_to_add)
changed = True
nothingchanged = False
# Add the indices
indices = []
for i in xrange(len(new_list_of_entries)):
indices.append(new_list_of_entries[i]['index'])
# append to the old record:
if nothingchanged:
LOGGER.debug('modify_handle_value: There was no entries ' + \
str(kvpairs.keys()) + ' to be modified (handle ' + handle + ').' + \
' To add them, set add_if_not_exist = True')
else:
op = 'modifying handle values'
resp, put_payload = self.__send_handle_put_request(
handle,
new_list_of_entries,
indices=indices,
overwrite=True,
op=op)
if hsresponses.handle_success(resp):
LOGGER.info('Handle modified: ' + handle)
else:
msg = 'Values: ' + str(kvpairs)
raise GenericHandleError(
operation=op,
handle=handle,
response=resp,
msg=msg,
payload=put_payload
)
|
[
"def",
"modify_handle_value",
"(",
"self",
",",
"handle",
",",
"ttl",
"=",
"None",
",",
"add_if_not_exist",
"=",
"True",
",",
"*",
"*",
"kvpairs",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'modify_handle_value...'",
")",
"# Read handle record:",
"handlerecord_json",
"=",
"self",
".",
"retrieve_handle_record_json",
"(",
"handle",
")",
"if",
"handlerecord_json",
"is",
"None",
":",
"msg",
"=",
"'Cannot modify unexisting handle'",
"raise",
"HandleNotFoundException",
"(",
"handle",
"=",
"handle",
",",
"msg",
"=",
"msg",
")",
"list_of_entries",
"=",
"handlerecord_json",
"[",
"'values'",
"]",
"# HS_ADMIN",
"if",
"'HS_ADMIN'",
"in",
"kvpairs",
".",
"keys",
"(",
")",
"and",
"not",
"self",
".",
"__modify_HS_ADMIN",
":",
"msg",
"=",
"'You may not modify HS_ADMIN'",
"raise",
"IllegalOperationException",
"(",
"msg",
"=",
"msg",
",",
"operation",
"=",
"'modifying HS_ADMIN'",
",",
"handle",
"=",
"handle",
")",
"nothingchanged",
"=",
"True",
"new_list_of_entries",
"=",
"[",
"]",
"list_of_old_and_new_entries",
"=",
"list_of_entries",
"[",
":",
"]",
"keys",
"=",
"kvpairs",
".",
"keys",
"(",
")",
"for",
"key",
",",
"newval",
"in",
"kvpairs",
".",
"items",
"(",
")",
":",
"# Change existing entry:",
"changed",
"=",
"False",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"list_of_entries",
")",
")",
":",
"if",
"list_of_entries",
"[",
"i",
"]",
"[",
"'type'",
"]",
"==",
"key",
":",
"if",
"not",
"changed",
":",
"list_of_entries",
"[",
"i",
"]",
"[",
"'data'",
"]",
"=",
"newval",
"list_of_entries",
"[",
"i",
"]",
".",
"pop",
"(",
"'timestamp'",
")",
"# will be ignored anyway",
"if",
"key",
"==",
"'HS_ADMIN'",
":",
"newval",
"[",
"'permissions'",
"]",
"=",
"self",
".",
"__HS_ADMIN_permissions",
"list_of_entries",
"[",
"i",
"]",
".",
"pop",
"(",
"'timestamp'",
")",
"# will be ignored anyway",
"list_of_entries",
"[",
"i",
"]",
"[",
"'data'",
"]",
"=",
"{",
"'format'",
":",
"'admin'",
",",
"'value'",
":",
"newval",
"}",
"LOGGER",
".",
"info",
"(",
"'Modified'",
"+",
"' \"HS_ADMIN\" of handle '",
"+",
"handle",
")",
"changed",
"=",
"True",
"nothingchanged",
"=",
"False",
"new_list_of_entries",
".",
"append",
"(",
"list_of_entries",
"[",
"i",
"]",
")",
"list_of_old_and_new_entries",
".",
"append",
"(",
"list_of_entries",
"[",
"i",
"]",
")",
"else",
":",
"msg",
"=",
"'There is several entries of type \"'",
"+",
"key",
"+",
"'\".'",
"+",
"' This can lead to unexpected behaviour.'",
"+",
"' Please clean up before modifying the record.'",
"raise",
"BrokenHandleRecordException",
"(",
"handle",
"=",
"handle",
",",
"msg",
"=",
"msg",
")",
"# If the entry doesn't exist yet, add it:",
"if",
"not",
"changed",
":",
"if",
"add_if_not_exist",
":",
"LOGGER",
".",
"debug",
"(",
"'modify_handle_value: Adding entry \"'",
"+",
"key",
"+",
"'\"'",
"+",
"' to handle '",
"+",
"handle",
")",
"index",
"=",
"self",
".",
"__make_another_index",
"(",
"list_of_old_and_new_entries",
")",
"entry_to_add",
"=",
"self",
".",
"__create_entry",
"(",
"key",
",",
"newval",
",",
"index",
",",
"ttl",
")",
"new_list_of_entries",
".",
"append",
"(",
"entry_to_add",
")",
"list_of_old_and_new_entries",
".",
"append",
"(",
"entry_to_add",
")",
"changed",
"=",
"True",
"nothingchanged",
"=",
"False",
"# Add the indices",
"indices",
"=",
"[",
"]",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"new_list_of_entries",
")",
")",
":",
"indices",
".",
"append",
"(",
"new_list_of_entries",
"[",
"i",
"]",
"[",
"'index'",
"]",
")",
"# append to the old record:",
"if",
"nothingchanged",
":",
"LOGGER",
".",
"debug",
"(",
"'modify_handle_value: There was no entries '",
"+",
"str",
"(",
"kvpairs",
".",
"keys",
"(",
")",
")",
"+",
"' to be modified (handle '",
"+",
"handle",
"+",
"').'",
"+",
"' To add them, set add_if_not_exist = True'",
")",
"else",
":",
"op",
"=",
"'modifying handle values'",
"resp",
",",
"put_payload",
"=",
"self",
".",
"__send_handle_put_request",
"(",
"handle",
",",
"new_list_of_entries",
",",
"indices",
"=",
"indices",
",",
"overwrite",
"=",
"True",
",",
"op",
"=",
"op",
")",
"if",
"hsresponses",
".",
"handle_success",
"(",
"resp",
")",
":",
"LOGGER",
".",
"info",
"(",
"'Handle modified: '",
"+",
"handle",
")",
"else",
":",
"msg",
"=",
"'Values: '",
"+",
"str",
"(",
"kvpairs",
")",
"raise",
"GenericHandleError",
"(",
"operation",
"=",
"op",
",",
"handle",
"=",
"handle",
",",
"response",
"=",
"resp",
",",
"msg",
"=",
"msg",
",",
"payload",
"=",
"put_payload",
")"
] |
Modify entries (key-value-pairs) in a handle record. If the key
does not exist yet, it is created.
*Note:* We assume that a key exists only once. In case a key exists
several time, an exception will be raised.
*Note:* To modify 10320/LOC, please use :meth:`~b2handle.handleclient.EUDATHandleClient.add_additional_URL` or
:meth:`~b2handle.handleclient.EUDATHandleClient.remove_additional_URL`.
:param handle: Handle whose record is to be modified
:param ttl: Optional. Integer value. If ttl should be set to a
non-default value.
:param all other args: The user can specify several key-value-pairs.
These will be the handle value types and values that will be
modified. The keys are the names or the handle value types (e.g.
"URL"). The values are the new values to store in "data". If the
key is 'HS_ADMIN', the new value needs to be of the form
{'handle':'xyz', 'index':xyz}. The permissions will be set to the
default permissions.
:raises: :exc:`~b2handle.handleexceptions.HandleAuthenticationError`
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
|
[
"Modify",
"entries",
"(",
"key",
"-",
"value",
"-",
"pairs",
")",
"in",
"a",
"handle",
"record",
".",
"If",
"the",
"key",
"does",
"not",
"exist",
"yet",
"it",
"is",
"created",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handleclient.py#L473-L587
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/handleclient.py
|
EUDATHandleClient.delete_handle_value
|
def delete_handle_value(self, handle, key):
'''
Delete a key-value pair from a handle record. If the key exists more
than once, all key-value pairs with this key are deleted.
:param handle: Handle from whose record the entry should be deleted.
:param key: Key to be deleted. Also accepts a list of keys.
:raises: :exc:`~b2handle.handleexceptions.HandleAuthenticationError`
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
'''
LOGGER.debug('delete_handle_value...')
# read handle record:
handlerecord_json = self.retrieve_handle_record_json(handle)
if handlerecord_json is None:
msg = 'Cannot modify unexisting handle'
raise HandleNotFoundException(handle=handle, msg=msg)
list_of_entries = handlerecord_json['values']
# find indices to delete:
keys = None
indices = []
if type(key) != type([]):
keys = [key]
else:
keys = key
keys_done = []
for key in keys:
# filter HS_ADMIN
if key == 'HS_ADMIN':
op = 'deleting "HS_ADMIN"'
raise IllegalOperationException(operation=op, handle=handle)
if key not in keys_done:
indices_onekey = self.get_handlerecord_indices_for_key(key, list_of_entries)
indices = indices + indices_onekey
keys_done.append(key)
# Important: If key not found, do not continue, as deleting without indices would delete the entire handle!!
if not len(indices) > 0:
LOGGER.debug('delete_handle_value: No values for key(s) ' + str(keys))
return None
else:
# delete and process response:
op = 'deleting "' + str(keys) + '"'
resp = self.__send_handle_delete_request(handle, indices=indices, op=op)
if hsresponses.handle_success(resp):
LOGGER.debug("delete_handle_value: Deleted handle values " + str(keys) + "of handle " + handle)
elif hsresponses.values_not_found(resp):
pass
else:
raise GenericHandleError(
operation=op,
handle=handle,
response=resp
)
|
python
|
def delete_handle_value(self, handle, key):
'''
Delete a key-value pair from a handle record. If the key exists more
than once, all key-value pairs with this key are deleted.
:param handle: Handle from whose record the entry should be deleted.
:param key: Key to be deleted. Also accepts a list of keys.
:raises: :exc:`~b2handle.handleexceptions.HandleAuthenticationError`
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
'''
LOGGER.debug('delete_handle_value...')
# read handle record:
handlerecord_json = self.retrieve_handle_record_json(handle)
if handlerecord_json is None:
msg = 'Cannot modify unexisting handle'
raise HandleNotFoundException(handle=handle, msg=msg)
list_of_entries = handlerecord_json['values']
# find indices to delete:
keys = None
indices = []
if type(key) != type([]):
keys = [key]
else:
keys = key
keys_done = []
for key in keys:
# filter HS_ADMIN
if key == 'HS_ADMIN':
op = 'deleting "HS_ADMIN"'
raise IllegalOperationException(operation=op, handle=handle)
if key not in keys_done:
indices_onekey = self.get_handlerecord_indices_for_key(key, list_of_entries)
indices = indices + indices_onekey
keys_done.append(key)
# Important: If key not found, do not continue, as deleting without indices would delete the entire handle!!
if not len(indices) > 0:
LOGGER.debug('delete_handle_value: No values for key(s) ' + str(keys))
return None
else:
# delete and process response:
op = 'deleting "' + str(keys) + '"'
resp = self.__send_handle_delete_request(handle, indices=indices, op=op)
if hsresponses.handle_success(resp):
LOGGER.debug("delete_handle_value: Deleted handle values " + str(keys) + "of handle " + handle)
elif hsresponses.values_not_found(resp):
pass
else:
raise GenericHandleError(
operation=op,
handle=handle,
response=resp
)
|
[
"def",
"delete_handle_value",
"(",
"self",
",",
"handle",
",",
"key",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'delete_handle_value...'",
")",
"# read handle record:",
"handlerecord_json",
"=",
"self",
".",
"retrieve_handle_record_json",
"(",
"handle",
")",
"if",
"handlerecord_json",
"is",
"None",
":",
"msg",
"=",
"'Cannot modify unexisting handle'",
"raise",
"HandleNotFoundException",
"(",
"handle",
"=",
"handle",
",",
"msg",
"=",
"msg",
")",
"list_of_entries",
"=",
"handlerecord_json",
"[",
"'values'",
"]",
"# find indices to delete:",
"keys",
"=",
"None",
"indices",
"=",
"[",
"]",
"if",
"type",
"(",
"key",
")",
"!=",
"type",
"(",
"[",
"]",
")",
":",
"keys",
"=",
"[",
"key",
"]",
"else",
":",
"keys",
"=",
"key",
"keys_done",
"=",
"[",
"]",
"for",
"key",
"in",
"keys",
":",
"# filter HS_ADMIN",
"if",
"key",
"==",
"'HS_ADMIN'",
":",
"op",
"=",
"'deleting \"HS_ADMIN\"'",
"raise",
"IllegalOperationException",
"(",
"operation",
"=",
"op",
",",
"handle",
"=",
"handle",
")",
"if",
"key",
"not",
"in",
"keys_done",
":",
"indices_onekey",
"=",
"self",
".",
"get_handlerecord_indices_for_key",
"(",
"key",
",",
"list_of_entries",
")",
"indices",
"=",
"indices",
"+",
"indices_onekey",
"keys_done",
".",
"append",
"(",
"key",
")",
"# Important: If key not found, do not continue, as deleting without indices would delete the entire handle!!",
"if",
"not",
"len",
"(",
"indices",
")",
">",
"0",
":",
"LOGGER",
".",
"debug",
"(",
"'delete_handle_value: No values for key(s) '",
"+",
"str",
"(",
"keys",
")",
")",
"return",
"None",
"else",
":",
"# delete and process response:",
"op",
"=",
"'deleting \"'",
"+",
"str",
"(",
"keys",
")",
"+",
"'\"'",
"resp",
"=",
"self",
".",
"__send_handle_delete_request",
"(",
"handle",
",",
"indices",
"=",
"indices",
",",
"op",
"=",
"op",
")",
"if",
"hsresponses",
".",
"handle_success",
"(",
"resp",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"delete_handle_value: Deleted handle values \"",
"+",
"str",
"(",
"keys",
")",
"+",
"\"of handle \"",
"+",
"handle",
")",
"elif",
"hsresponses",
".",
"values_not_found",
"(",
"resp",
")",
":",
"pass",
"else",
":",
"raise",
"GenericHandleError",
"(",
"operation",
"=",
"op",
",",
"handle",
"=",
"handle",
",",
"response",
"=",
"resp",
")"
] |
Delete a key-value pair from a handle record. If the key exists more
than once, all key-value pairs with this key are deleted.
:param handle: Handle from whose record the entry should be deleted.
:param key: Key to be deleted. Also accepts a list of keys.
:raises: :exc:`~b2handle.handleexceptions.HandleAuthenticationError`
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
|
[
"Delete",
"a",
"key",
"-",
"value",
"pair",
"from",
"a",
"handle",
"record",
".",
"If",
"the",
"key",
"exists",
"more",
"than",
"once",
"all",
"key",
"-",
"value",
"pairs",
"with",
"this",
"key",
"are",
"deleted",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handleclient.py#L589-L648
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/handleclient.py
|
EUDATHandleClient.delete_handle
|
def delete_handle(self, handle, *other):
'''Delete the handle and its handle record. If the Handle is not found, an Exception is raised.
:param handle: Handle to be deleted.
:param other: Deprecated. This only exists to catch wrong method usage
by users who are used to delete handle VALUES with the method.
:raises: :exc:`~b2handle.handleexceptions.HandleAuthenticationError`
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
'''
LOGGER.debug('delete_handle...')
utilhandle.check_handle_syntax(handle)
# Safety check. In old epic client, the method could be used for
# deleting handle values (not entire handle) by specifying more
# parameters.
if len(other) > 0:
message = 'You specified more than one argument. If you wanted' + \
' to delete just some values from a handle, please use the' + \
' new method "delete_handle_value()".'
raise TypeError(message)
op = 'deleting handle'
resp = self.__send_handle_delete_request(handle, op=op)
if hsresponses.handle_success(resp):
LOGGER.info('Handle ' + handle + ' deleted.')
elif hsresponses.handle_not_found(resp):
msg = ('delete_handle: Handle ' + handle + ' did not exist, '
'so it could not be deleted.')
LOGGER.debug(msg)
raise HandleNotFoundException(msg=msg, handle=handle, response=resp)
else:
raise GenericHandleError(op=op, handle=handle, response=resp)
|
python
|
def delete_handle(self, handle, *other):
'''Delete the handle and its handle record. If the Handle is not found, an Exception is raised.
:param handle: Handle to be deleted.
:param other: Deprecated. This only exists to catch wrong method usage
by users who are used to delete handle VALUES with the method.
:raises: :exc:`~b2handle.handleexceptions.HandleAuthenticationError`
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
'''
LOGGER.debug('delete_handle...')
utilhandle.check_handle_syntax(handle)
# Safety check. In old epic client, the method could be used for
# deleting handle values (not entire handle) by specifying more
# parameters.
if len(other) > 0:
message = 'You specified more than one argument. If you wanted' + \
' to delete just some values from a handle, please use the' + \
' new method "delete_handle_value()".'
raise TypeError(message)
op = 'deleting handle'
resp = self.__send_handle_delete_request(handle, op=op)
if hsresponses.handle_success(resp):
LOGGER.info('Handle ' + handle + ' deleted.')
elif hsresponses.handle_not_found(resp):
msg = ('delete_handle: Handle ' + handle + ' did not exist, '
'so it could not be deleted.')
LOGGER.debug(msg)
raise HandleNotFoundException(msg=msg, handle=handle, response=resp)
else:
raise GenericHandleError(op=op, handle=handle, response=resp)
|
[
"def",
"delete_handle",
"(",
"self",
",",
"handle",
",",
"*",
"other",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'delete_handle...'",
")",
"utilhandle",
".",
"check_handle_syntax",
"(",
"handle",
")",
"# Safety check. In old epic client, the method could be used for",
"# deleting handle values (not entire handle) by specifying more",
"# parameters.",
"if",
"len",
"(",
"other",
")",
">",
"0",
":",
"message",
"=",
"'You specified more than one argument. If you wanted'",
"+",
"' to delete just some values from a handle, please use the'",
"+",
"' new method \"delete_handle_value()\".'",
"raise",
"TypeError",
"(",
"message",
")",
"op",
"=",
"'deleting handle'",
"resp",
"=",
"self",
".",
"__send_handle_delete_request",
"(",
"handle",
",",
"op",
"=",
"op",
")",
"if",
"hsresponses",
".",
"handle_success",
"(",
"resp",
")",
":",
"LOGGER",
".",
"info",
"(",
"'Handle '",
"+",
"handle",
"+",
"' deleted.'",
")",
"elif",
"hsresponses",
".",
"handle_not_found",
"(",
"resp",
")",
":",
"msg",
"=",
"(",
"'delete_handle: Handle '",
"+",
"handle",
"+",
"' did not exist, '",
"'so it could not be deleted.'",
")",
"LOGGER",
".",
"debug",
"(",
"msg",
")",
"raise",
"HandleNotFoundException",
"(",
"msg",
"=",
"msg",
",",
"handle",
"=",
"handle",
",",
"response",
"=",
"resp",
")",
"else",
":",
"raise",
"GenericHandleError",
"(",
"op",
"=",
"op",
",",
"handle",
"=",
"handle",
",",
"response",
"=",
"resp",
")"
] |
Delete the handle and its handle record. If the Handle is not found, an Exception is raised.
:param handle: Handle to be deleted.
:param other: Deprecated. This only exists to catch wrong method usage
by users who are used to delete handle VALUES with the method.
:raises: :exc:`~b2handle.handleexceptions.HandleAuthenticationError`
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
|
[
"Delete",
"the",
"handle",
"and",
"its",
"handle",
"record",
".",
"If",
"the",
"Handle",
"is",
"not",
"found",
"an",
"Exception",
"is",
"raised",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handleclient.py#L650-L684
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/handleclient.py
|
EUDATHandleClient.exchange_additional_URL
|
def exchange_additional_URL(self, handle, old, new):
'''
Exchange an URL in the 10320/LOC entry against another, keeping the same id
and other attributes.
:param handle: The handle to modify.
:param old: The URL to replace.
:param new: The URL to set as new URL.
'''
LOGGER.debug('exchange_additional_URL...')
handlerecord_json = self.retrieve_handle_record_json(handle)
if handlerecord_json is None:
msg = 'Cannot exchange URLs in unexisting handle'
raise HandleNotFoundException(
handle=handle,
msg=msg
)
list_of_entries = handlerecord_json['values']
if not self.is_URL_contained_in_10320LOC(handle, old, handlerecord_json):
LOGGER.debug('exchange_additional_URL: No URLs exchanged, as the url was not in the record.')
else:
self.__exchange_URL_in_13020loc(old, new, list_of_entries, handle)
op = 'exchanging URLs'
resp, put_payload = self.__send_handle_put_request(
handle,
list_of_entries,
overwrite=True,
op=op
)
# TODO FIXME (one day): Implement overwriting by index (less risky)
if hsresponses.handle_success(resp):
pass
else:
msg = 'Could not exchange URL ' + str(old) + ' against ' + str(new)
raise GenericHandleError(
operation=op,
handle=handle,
reponse=resp,
msg=msg,
payload=put_payload
)
|
python
|
def exchange_additional_URL(self, handle, old, new):
'''
Exchange an URL in the 10320/LOC entry against another, keeping the same id
and other attributes.
:param handle: The handle to modify.
:param old: The URL to replace.
:param new: The URL to set as new URL.
'''
LOGGER.debug('exchange_additional_URL...')
handlerecord_json = self.retrieve_handle_record_json(handle)
if handlerecord_json is None:
msg = 'Cannot exchange URLs in unexisting handle'
raise HandleNotFoundException(
handle=handle,
msg=msg
)
list_of_entries = handlerecord_json['values']
if not self.is_URL_contained_in_10320LOC(handle, old, handlerecord_json):
LOGGER.debug('exchange_additional_URL: No URLs exchanged, as the url was not in the record.')
else:
self.__exchange_URL_in_13020loc(old, new, list_of_entries, handle)
op = 'exchanging URLs'
resp, put_payload = self.__send_handle_put_request(
handle,
list_of_entries,
overwrite=True,
op=op
)
# TODO FIXME (one day): Implement overwriting by index (less risky)
if hsresponses.handle_success(resp):
pass
else:
msg = 'Could not exchange URL ' + str(old) + ' against ' + str(new)
raise GenericHandleError(
operation=op,
handle=handle,
reponse=resp,
msg=msg,
payload=put_payload
)
|
[
"def",
"exchange_additional_URL",
"(",
"self",
",",
"handle",
",",
"old",
",",
"new",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'exchange_additional_URL...'",
")",
"handlerecord_json",
"=",
"self",
".",
"retrieve_handle_record_json",
"(",
"handle",
")",
"if",
"handlerecord_json",
"is",
"None",
":",
"msg",
"=",
"'Cannot exchange URLs in unexisting handle'",
"raise",
"HandleNotFoundException",
"(",
"handle",
"=",
"handle",
",",
"msg",
"=",
"msg",
")",
"list_of_entries",
"=",
"handlerecord_json",
"[",
"'values'",
"]",
"if",
"not",
"self",
".",
"is_URL_contained_in_10320LOC",
"(",
"handle",
",",
"old",
",",
"handlerecord_json",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'exchange_additional_URL: No URLs exchanged, as the url was not in the record.'",
")",
"else",
":",
"self",
".",
"__exchange_URL_in_13020loc",
"(",
"old",
",",
"new",
",",
"list_of_entries",
",",
"handle",
")",
"op",
"=",
"'exchanging URLs'",
"resp",
",",
"put_payload",
"=",
"self",
".",
"__send_handle_put_request",
"(",
"handle",
",",
"list_of_entries",
",",
"overwrite",
"=",
"True",
",",
"op",
"=",
"op",
")",
"# TODO FIXME (one day): Implement overwriting by index (less risky)",
"if",
"hsresponses",
".",
"handle_success",
"(",
"resp",
")",
":",
"pass",
"else",
":",
"msg",
"=",
"'Could not exchange URL '",
"+",
"str",
"(",
"old",
")",
"+",
"' against '",
"+",
"str",
"(",
"new",
")",
"raise",
"GenericHandleError",
"(",
"operation",
"=",
"op",
",",
"handle",
"=",
"handle",
",",
"reponse",
"=",
"resp",
",",
"msg",
"=",
"msg",
",",
"payload",
"=",
"put_payload",
")"
] |
Exchange an URL in the 10320/LOC entry against another, keeping the same id
and other attributes.
:param handle: The handle to modify.
:param old: The URL to replace.
:param new: The URL to set as new URL.
|
[
"Exchange",
"an",
"URL",
"in",
"the",
"10320",
"/",
"LOC",
"entry",
"against",
"another",
"keeping",
"the",
"same",
"id",
"and",
"other",
"attributes",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handleclient.py#L686-L729
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/handleclient.py
|
EUDATHandleClient.add_additional_URL
|
def add_additional_URL(self, handle, *urls, **attributes):
'''
Add a URL entry to the handle record's 10320/LOC entry. If 10320/LOC
does not exist yet, it is created. If the 10320/LOC entry already
contains the URL, it is not added a second time.
:param handle: The handle to add the URL to.
:param urls: The URL(s) to be added. Several URLs may be specified.
:param attributes: Optional. Additional key-value pairs to set as
attributes to the <location> elements, e.g. weight, http_role or
custom attributes. Note: If the URL already exists but the
attributes are different, they are updated!
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
:raises: :exc:`~b2handle.handleexceptions.HandleAuthenticationError`
'''
LOGGER.debug('add_additional_URL...')
handlerecord_json = self.retrieve_handle_record_json(handle)
if handlerecord_json is None:
msg = 'Cannot add URLS to unexisting handle!'
raise HandleNotFoundException(handle=handle, msg=msg)
list_of_entries = handlerecord_json['values']
is_new = False
for url in urls:
if not self.is_URL_contained_in_10320LOC(handle, url, handlerecord_json):
is_new = True
if not is_new:
LOGGER.debug("add_additional_URL: No new URL to be added (so no URL is added at all).")
else:
for url in urls:
self.__add_URL_to_10320LOC(url, list_of_entries, handle)
op = 'adding URLs'
resp, put_payload = self.__send_handle_put_request(handle, list_of_entries, overwrite=True, op=op)
# TODO FIXME (one day) Overwrite by index.
if hsresponses.handle_success(resp):
pass
else:
msg = 'Could not add URLs ' + str(urls)
raise GenericHandleError(
operation=op,
handle=handle,
reponse=resp,
msg=msg,
payload=put_payload
)
|
python
|
def add_additional_URL(self, handle, *urls, **attributes):
'''
Add a URL entry to the handle record's 10320/LOC entry. If 10320/LOC
does not exist yet, it is created. If the 10320/LOC entry already
contains the URL, it is not added a second time.
:param handle: The handle to add the URL to.
:param urls: The URL(s) to be added. Several URLs may be specified.
:param attributes: Optional. Additional key-value pairs to set as
attributes to the <location> elements, e.g. weight, http_role or
custom attributes. Note: If the URL already exists but the
attributes are different, they are updated!
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
:raises: :exc:`~b2handle.handleexceptions.HandleAuthenticationError`
'''
LOGGER.debug('add_additional_URL...')
handlerecord_json = self.retrieve_handle_record_json(handle)
if handlerecord_json is None:
msg = 'Cannot add URLS to unexisting handle!'
raise HandleNotFoundException(handle=handle, msg=msg)
list_of_entries = handlerecord_json['values']
is_new = False
for url in urls:
if not self.is_URL_contained_in_10320LOC(handle, url, handlerecord_json):
is_new = True
if not is_new:
LOGGER.debug("add_additional_URL: No new URL to be added (so no URL is added at all).")
else:
for url in urls:
self.__add_URL_to_10320LOC(url, list_of_entries, handle)
op = 'adding URLs'
resp, put_payload = self.__send_handle_put_request(handle, list_of_entries, overwrite=True, op=op)
# TODO FIXME (one day) Overwrite by index.
if hsresponses.handle_success(resp):
pass
else:
msg = 'Could not add URLs ' + str(urls)
raise GenericHandleError(
operation=op,
handle=handle,
reponse=resp,
msg=msg,
payload=put_payload
)
|
[
"def",
"add_additional_URL",
"(",
"self",
",",
"handle",
",",
"*",
"urls",
",",
"*",
"*",
"attributes",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'add_additional_URL...'",
")",
"handlerecord_json",
"=",
"self",
".",
"retrieve_handle_record_json",
"(",
"handle",
")",
"if",
"handlerecord_json",
"is",
"None",
":",
"msg",
"=",
"'Cannot add URLS to unexisting handle!'",
"raise",
"HandleNotFoundException",
"(",
"handle",
"=",
"handle",
",",
"msg",
"=",
"msg",
")",
"list_of_entries",
"=",
"handlerecord_json",
"[",
"'values'",
"]",
"is_new",
"=",
"False",
"for",
"url",
"in",
"urls",
":",
"if",
"not",
"self",
".",
"is_URL_contained_in_10320LOC",
"(",
"handle",
",",
"url",
",",
"handlerecord_json",
")",
":",
"is_new",
"=",
"True",
"if",
"not",
"is_new",
":",
"LOGGER",
".",
"debug",
"(",
"\"add_additional_URL: No new URL to be added (so no URL is added at all).\"",
")",
"else",
":",
"for",
"url",
"in",
"urls",
":",
"self",
".",
"__add_URL_to_10320LOC",
"(",
"url",
",",
"list_of_entries",
",",
"handle",
")",
"op",
"=",
"'adding URLs'",
"resp",
",",
"put_payload",
"=",
"self",
".",
"__send_handle_put_request",
"(",
"handle",
",",
"list_of_entries",
",",
"overwrite",
"=",
"True",
",",
"op",
"=",
"op",
")",
"# TODO FIXME (one day) Overwrite by index.",
"if",
"hsresponses",
".",
"handle_success",
"(",
"resp",
")",
":",
"pass",
"else",
":",
"msg",
"=",
"'Could not add URLs '",
"+",
"str",
"(",
"urls",
")",
"raise",
"GenericHandleError",
"(",
"operation",
"=",
"op",
",",
"handle",
"=",
"handle",
",",
"reponse",
"=",
"resp",
",",
"msg",
"=",
"msg",
",",
"payload",
"=",
"put_payload",
")"
] |
Add a URL entry to the handle record's 10320/LOC entry. If 10320/LOC
does not exist yet, it is created. If the 10320/LOC entry already
contains the URL, it is not added a second time.
:param handle: The handle to add the URL to.
:param urls: The URL(s) to be added. Several URLs may be specified.
:param attributes: Optional. Additional key-value pairs to set as
attributes to the <location> elements, e.g. weight, http_role or
custom attributes. Note: If the URL already exists but the
attributes are different, they are updated!
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
:raises: :exc:`~b2handle.handleexceptions.HandleAuthenticationError`
|
[
"Add",
"a",
"URL",
"entry",
"to",
"the",
"handle",
"record",
"s",
"10320",
"/",
"LOC",
"entry",
".",
"If",
"10320",
"/",
"LOC",
"does",
"not",
"exist",
"yet",
"it",
"is",
"created",
".",
"If",
"the",
"10320",
"/",
"LOC",
"entry",
"already",
"contains",
"the",
"URL",
"it",
"is",
"not",
"added",
"a",
"second",
"time",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handleclient.py#L731-L781
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/handleclient.py
|
EUDATHandleClient.remove_additional_URL
|
def remove_additional_URL(self, handle, *urls):
'''
Remove a URL from the handle record's 10320/LOC entry.
:param handle: The handle to modify.
:param urls: The URL(s) to be removed. Several URLs may be specified.
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
:raises: :exc:`~b2handle.handleexceptions.HandleAuthenticationError`
'''
LOGGER.debug('remove_additional_URL...')
handlerecord_json = self.retrieve_handle_record_json(handle)
if handlerecord_json is None:
msg = 'Cannot remove URLs from unexisting handle'
raise HandleNotFoundException(handle=handle, msg=msg)
list_of_entries = handlerecord_json['values']
for url in urls:
self.__remove_URL_from_10320LOC(url, list_of_entries, handle)
op = 'removing URLs'
resp, put_payload = self.__send_handle_put_request(
handle,
list_of_entries,
overwrite=True,
op=op
)
# TODO FIXME (one day): Implement overwriting by index (less risky),
# once HS have fixed the issue with the indices.
if hsresponses.handle_success(resp):
pass
else:
op = 'removing "' + str(urls) + '"'
msg = 'Could not remove URLs ' + str(urls)
raise GenericHandleError(
operation=op,
handle=handle,
reponse=resp,
msg=msg,
payload=put_payload
)
|
python
|
def remove_additional_URL(self, handle, *urls):
'''
Remove a URL from the handle record's 10320/LOC entry.
:param handle: The handle to modify.
:param urls: The URL(s) to be removed. Several URLs may be specified.
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
:raises: :exc:`~b2handle.handleexceptions.HandleAuthenticationError`
'''
LOGGER.debug('remove_additional_URL...')
handlerecord_json = self.retrieve_handle_record_json(handle)
if handlerecord_json is None:
msg = 'Cannot remove URLs from unexisting handle'
raise HandleNotFoundException(handle=handle, msg=msg)
list_of_entries = handlerecord_json['values']
for url in urls:
self.__remove_URL_from_10320LOC(url, list_of_entries, handle)
op = 'removing URLs'
resp, put_payload = self.__send_handle_put_request(
handle,
list_of_entries,
overwrite=True,
op=op
)
# TODO FIXME (one day): Implement overwriting by index (less risky),
# once HS have fixed the issue with the indices.
if hsresponses.handle_success(resp):
pass
else:
op = 'removing "' + str(urls) + '"'
msg = 'Could not remove URLs ' + str(urls)
raise GenericHandleError(
operation=op,
handle=handle,
reponse=resp,
msg=msg,
payload=put_payload
)
|
[
"def",
"remove_additional_URL",
"(",
"self",
",",
"handle",
",",
"*",
"urls",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'remove_additional_URL...'",
")",
"handlerecord_json",
"=",
"self",
".",
"retrieve_handle_record_json",
"(",
"handle",
")",
"if",
"handlerecord_json",
"is",
"None",
":",
"msg",
"=",
"'Cannot remove URLs from unexisting handle'",
"raise",
"HandleNotFoundException",
"(",
"handle",
"=",
"handle",
",",
"msg",
"=",
"msg",
")",
"list_of_entries",
"=",
"handlerecord_json",
"[",
"'values'",
"]",
"for",
"url",
"in",
"urls",
":",
"self",
".",
"__remove_URL_from_10320LOC",
"(",
"url",
",",
"list_of_entries",
",",
"handle",
")",
"op",
"=",
"'removing URLs'",
"resp",
",",
"put_payload",
"=",
"self",
".",
"__send_handle_put_request",
"(",
"handle",
",",
"list_of_entries",
",",
"overwrite",
"=",
"True",
",",
"op",
"=",
"op",
")",
"# TODO FIXME (one day): Implement overwriting by index (less risky),",
"# once HS have fixed the issue with the indices.",
"if",
"hsresponses",
".",
"handle_success",
"(",
"resp",
")",
":",
"pass",
"else",
":",
"op",
"=",
"'removing \"'",
"+",
"str",
"(",
"urls",
")",
"+",
"'\"'",
"msg",
"=",
"'Could not remove URLs '",
"+",
"str",
"(",
"urls",
")",
"raise",
"GenericHandleError",
"(",
"operation",
"=",
"op",
",",
"handle",
"=",
"handle",
",",
"reponse",
"=",
"resp",
",",
"msg",
"=",
"msg",
",",
"payload",
"=",
"put_payload",
")"
] |
Remove a URL from the handle record's 10320/LOC entry.
:param handle: The handle to modify.
:param urls: The URL(s) to be removed. Several URLs may be specified.
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
:raises: :exc:`~b2handle.handleexceptions.HandleAuthenticationError`
|
[
"Remove",
"a",
"URL",
"from",
"the",
"handle",
"record",
"s",
"10320",
"/",
"LOC",
"entry",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handleclient.py#L783-L825
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/handleclient.py
|
EUDATHandleClient.register_handle
|
def register_handle(self, handle, location, checksum=None, additional_URLs=None, overwrite=False, **extratypes):
'''
Registers a new Handle with given name. If the handle already exists
and overwrite is not set to True, the method will throw an
exception.
:param handle: The full name of the handle to be registered (prefix
and suffix)
:param location: The URL of the data entity to be referenced
:param checksum: Optional. The checksum string.
:param extratypes: Optional. Additional key value pairs.
:param additional_URLs: Optional. A list of URLs (as strings) to be
added to the handle record as 10320/LOC entry.
:param overwrite: Optional. If set to True, an existing handle record
will be overwritten. Defaults to False.
:raises: :exc:`~b2handle.handleexceptions.HandleAlreadyExistsException` Only if overwrite is not set or
set to False.
:raises: :exc:`~b2handle.handleexceptions.HandleAuthenticationError`
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
:return: The handle name.
'''
LOGGER.debug('register_handle...')
# If already exists and can't be overwritten:
if overwrite == False:
handlerecord_json = self.retrieve_handle_record_json(handle)
if handlerecord_json is not None:
msg = 'Could not register handle'
LOGGER.error(msg + ', as it already exists.')
raise HandleAlreadyExistsException(handle=handle, msg=msg)
# Create admin entry
list_of_entries = []
adminentry = self.__create_admin_entry(
self.__handleowner,
self.__HS_ADMIN_permissions,
self.__make_another_index(list_of_entries, hs_admin=True),
handle
)
list_of_entries.append(adminentry)
# Create other entries
entry_URL = self.__create_entry(
'URL',
location,
self.__make_another_index(list_of_entries, url=True)
)
list_of_entries.append(entry_URL)
if checksum is not None:
entryChecksum = self.__create_entry(
'CHECKSUM',
checksum,
self.__make_another_index(list_of_entries)
)
list_of_entries.append(entryChecksum)
if extratypes is not None:
for key, value in extratypes.items():
entry = self.__create_entry(
key,
value,
self.__make_another_index(list_of_entries)
)
list_of_entries.append(entry)
if additional_URLs is not None and len(additional_URLs) > 0:
for url in additional_URLs:
self.__add_URL_to_10320LOC(url, list_of_entries, handle)
# Create record itself and put to server
op = 'registering handle'
resp, put_payload = self.__send_handle_put_request(
handle,
list_of_entries,
overwrite=overwrite,
op=op
)
resp_content = decoded_response(resp)
if hsresponses.was_handle_created(resp) or hsresponses.handle_success(resp):
LOGGER.info("Handle registered: " + handle)
return json.loads(resp_content)['handle']
elif hsresponses.is_temporary_redirect(resp):
oldurl = resp.url
newurl = resp.headers['location']
raise GenericHandleError(
operation=op,
handle=handle,
response=resp,
payload=put_payload,
msg='Temporary redirect from ' + oldurl + ' to ' + newurl + '.'
)
elif hsresponses.handle_not_found(resp):
raise GenericHandleError(
operation=op,
handle=handle,
response=resp,
payload=put_payload,
msg='Could not create handle. Possibly you used HTTP instead of HTTPS?'
)
else:
raise GenericHandleError(
operation=op,
handle=handle,
reponse=resp,
payload=put_payload
)
|
python
|
def register_handle(self, handle, location, checksum=None, additional_URLs=None, overwrite=False, **extratypes):
'''
Registers a new Handle with given name. If the handle already exists
and overwrite is not set to True, the method will throw an
exception.
:param handle: The full name of the handle to be registered (prefix
and suffix)
:param location: The URL of the data entity to be referenced
:param checksum: Optional. The checksum string.
:param extratypes: Optional. Additional key value pairs.
:param additional_URLs: Optional. A list of URLs (as strings) to be
added to the handle record as 10320/LOC entry.
:param overwrite: Optional. If set to True, an existing handle record
will be overwritten. Defaults to False.
:raises: :exc:`~b2handle.handleexceptions.HandleAlreadyExistsException` Only if overwrite is not set or
set to False.
:raises: :exc:`~b2handle.handleexceptions.HandleAuthenticationError`
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
:return: The handle name.
'''
LOGGER.debug('register_handle...')
# If already exists and can't be overwritten:
if overwrite == False:
handlerecord_json = self.retrieve_handle_record_json(handle)
if handlerecord_json is not None:
msg = 'Could not register handle'
LOGGER.error(msg + ', as it already exists.')
raise HandleAlreadyExistsException(handle=handle, msg=msg)
# Create admin entry
list_of_entries = []
adminentry = self.__create_admin_entry(
self.__handleowner,
self.__HS_ADMIN_permissions,
self.__make_another_index(list_of_entries, hs_admin=True),
handle
)
list_of_entries.append(adminentry)
# Create other entries
entry_URL = self.__create_entry(
'URL',
location,
self.__make_another_index(list_of_entries, url=True)
)
list_of_entries.append(entry_URL)
if checksum is not None:
entryChecksum = self.__create_entry(
'CHECKSUM',
checksum,
self.__make_another_index(list_of_entries)
)
list_of_entries.append(entryChecksum)
if extratypes is not None:
for key, value in extratypes.items():
entry = self.__create_entry(
key,
value,
self.__make_another_index(list_of_entries)
)
list_of_entries.append(entry)
if additional_URLs is not None and len(additional_URLs) > 0:
for url in additional_URLs:
self.__add_URL_to_10320LOC(url, list_of_entries, handle)
# Create record itself and put to server
op = 'registering handle'
resp, put_payload = self.__send_handle_put_request(
handle,
list_of_entries,
overwrite=overwrite,
op=op
)
resp_content = decoded_response(resp)
if hsresponses.was_handle_created(resp) or hsresponses.handle_success(resp):
LOGGER.info("Handle registered: " + handle)
return json.loads(resp_content)['handle']
elif hsresponses.is_temporary_redirect(resp):
oldurl = resp.url
newurl = resp.headers['location']
raise GenericHandleError(
operation=op,
handle=handle,
response=resp,
payload=put_payload,
msg='Temporary redirect from ' + oldurl + ' to ' + newurl + '.'
)
elif hsresponses.handle_not_found(resp):
raise GenericHandleError(
operation=op,
handle=handle,
response=resp,
payload=put_payload,
msg='Could not create handle. Possibly you used HTTP instead of HTTPS?'
)
else:
raise GenericHandleError(
operation=op,
handle=handle,
reponse=resp,
payload=put_payload
)
|
[
"def",
"register_handle",
"(",
"self",
",",
"handle",
",",
"location",
",",
"checksum",
"=",
"None",
",",
"additional_URLs",
"=",
"None",
",",
"overwrite",
"=",
"False",
",",
"*",
"*",
"extratypes",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'register_handle...'",
")",
"# If already exists and can't be overwritten:",
"if",
"overwrite",
"==",
"False",
":",
"handlerecord_json",
"=",
"self",
".",
"retrieve_handle_record_json",
"(",
"handle",
")",
"if",
"handlerecord_json",
"is",
"not",
"None",
":",
"msg",
"=",
"'Could not register handle'",
"LOGGER",
".",
"error",
"(",
"msg",
"+",
"', as it already exists.'",
")",
"raise",
"HandleAlreadyExistsException",
"(",
"handle",
"=",
"handle",
",",
"msg",
"=",
"msg",
")",
"# Create admin entry",
"list_of_entries",
"=",
"[",
"]",
"adminentry",
"=",
"self",
".",
"__create_admin_entry",
"(",
"self",
".",
"__handleowner",
",",
"self",
".",
"__HS_ADMIN_permissions",
",",
"self",
".",
"__make_another_index",
"(",
"list_of_entries",
",",
"hs_admin",
"=",
"True",
")",
",",
"handle",
")",
"list_of_entries",
".",
"append",
"(",
"adminentry",
")",
"# Create other entries",
"entry_URL",
"=",
"self",
".",
"__create_entry",
"(",
"'URL'",
",",
"location",
",",
"self",
".",
"__make_another_index",
"(",
"list_of_entries",
",",
"url",
"=",
"True",
")",
")",
"list_of_entries",
".",
"append",
"(",
"entry_URL",
")",
"if",
"checksum",
"is",
"not",
"None",
":",
"entryChecksum",
"=",
"self",
".",
"__create_entry",
"(",
"'CHECKSUM'",
",",
"checksum",
",",
"self",
".",
"__make_another_index",
"(",
"list_of_entries",
")",
")",
"list_of_entries",
".",
"append",
"(",
"entryChecksum",
")",
"if",
"extratypes",
"is",
"not",
"None",
":",
"for",
"key",
",",
"value",
"in",
"extratypes",
".",
"items",
"(",
")",
":",
"entry",
"=",
"self",
".",
"__create_entry",
"(",
"key",
",",
"value",
",",
"self",
".",
"__make_another_index",
"(",
"list_of_entries",
")",
")",
"list_of_entries",
".",
"append",
"(",
"entry",
")",
"if",
"additional_URLs",
"is",
"not",
"None",
"and",
"len",
"(",
"additional_URLs",
")",
">",
"0",
":",
"for",
"url",
"in",
"additional_URLs",
":",
"self",
".",
"__add_URL_to_10320LOC",
"(",
"url",
",",
"list_of_entries",
",",
"handle",
")",
"# Create record itself and put to server",
"op",
"=",
"'registering handle'",
"resp",
",",
"put_payload",
"=",
"self",
".",
"__send_handle_put_request",
"(",
"handle",
",",
"list_of_entries",
",",
"overwrite",
"=",
"overwrite",
",",
"op",
"=",
"op",
")",
"resp_content",
"=",
"decoded_response",
"(",
"resp",
")",
"if",
"hsresponses",
".",
"was_handle_created",
"(",
"resp",
")",
"or",
"hsresponses",
".",
"handle_success",
"(",
"resp",
")",
":",
"LOGGER",
".",
"info",
"(",
"\"Handle registered: \"",
"+",
"handle",
")",
"return",
"json",
".",
"loads",
"(",
"resp_content",
")",
"[",
"'handle'",
"]",
"elif",
"hsresponses",
".",
"is_temporary_redirect",
"(",
"resp",
")",
":",
"oldurl",
"=",
"resp",
".",
"url",
"newurl",
"=",
"resp",
".",
"headers",
"[",
"'location'",
"]",
"raise",
"GenericHandleError",
"(",
"operation",
"=",
"op",
",",
"handle",
"=",
"handle",
",",
"response",
"=",
"resp",
",",
"payload",
"=",
"put_payload",
",",
"msg",
"=",
"'Temporary redirect from '",
"+",
"oldurl",
"+",
"' to '",
"+",
"newurl",
"+",
"'.'",
")",
"elif",
"hsresponses",
".",
"handle_not_found",
"(",
"resp",
")",
":",
"raise",
"GenericHandleError",
"(",
"operation",
"=",
"op",
",",
"handle",
"=",
"handle",
",",
"response",
"=",
"resp",
",",
"payload",
"=",
"put_payload",
",",
"msg",
"=",
"'Could not create handle. Possibly you used HTTP instead of HTTPS?'",
")",
"else",
":",
"raise",
"GenericHandleError",
"(",
"operation",
"=",
"op",
",",
"handle",
"=",
"handle",
",",
"reponse",
"=",
"resp",
",",
"payload",
"=",
"put_payload",
")"
] |
Registers a new Handle with given name. If the handle already exists
and overwrite is not set to True, the method will throw an
exception.
:param handle: The full name of the handle to be registered (prefix
and suffix)
:param location: The URL of the data entity to be referenced
:param checksum: Optional. The checksum string.
:param extratypes: Optional. Additional key value pairs.
:param additional_URLs: Optional. A list of URLs (as strings) to be
added to the handle record as 10320/LOC entry.
:param overwrite: Optional. If set to True, an existing handle record
will be overwritten. Defaults to False.
:raises: :exc:`~b2handle.handleexceptions.HandleAlreadyExistsException` Only if overwrite is not set or
set to False.
:raises: :exc:`~b2handle.handleexceptions.HandleAuthenticationError`
:raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError`
:return: The handle name.
|
[
"Registers",
"a",
"new",
"Handle",
"with",
"given",
"name",
".",
"If",
"the",
"handle",
"already",
"exists",
"and",
"overwrite",
"is",
"not",
"set",
"to",
"True",
"the",
"method",
"will",
"throw",
"an",
"exception",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handleclient.py#L827-L930
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/handleclient.py
|
EUDATHandleClient.search_handle
|
def search_handle(self, URL=None, prefix=None, **key_value_pairs):
'''
Search for handles containing the specified key with the specified
value. The search terms are passed on to the reverse lookup servlet
as-is. The servlet is supposed to be case-insensitive, but if it
isn't, the wrong case will cause a :exc:`~b2handle.handleexceptions.ReverseLookupException`.
*Note:* If allowed search keys are configured, only these are used. If
no allowed search keys are specified, all key-value pairs are
passed on to the reverse lookup servlet, possibly causing a
:exc:`~b2handle.handleexceptions.ReverseLookupException`.
Example calls:
.. code:: python
list_of_handles = search_handle('http://www.foo.com')
list_of_handles = search_handle('http://www.foo.com', CHECKSUM=99999)
list_of_handles = search_handle(URL='http://www.foo.com', CHECKSUM=99999)
:param URL: Optional. The URL to search for (reverse lookup). [This is
NOT the URL of the search servlet!]
:param prefix: Optional. The Handle prefix to which the search should
be limited to. If unspecified, the method will search across all
prefixes present at the server given to the constructor.
:param key_value_pairs: Optional. Several search fields and values can
be specified as key-value-pairs,
e.g. CHECKSUM=123456, URL=www.foo.com
:raise: :exc:`~b2handle.handleexceptions.ReverseLookupException`: If a search field is specified that
cannot be used, or if something else goes wrong.
:return: A list of all Handles (strings) that bear the given key with
given value of given prefix or server. The list may be empty and
may also contain more than one element.
'''
LOGGER.debug('search_handle...')
list_of_handles = self.__searcher.search_handle(URL=URL, prefix=prefix, **key_value_pairs)
return list_of_handles
|
python
|
def search_handle(self, URL=None, prefix=None, **key_value_pairs):
'''
Search for handles containing the specified key with the specified
value. The search terms are passed on to the reverse lookup servlet
as-is. The servlet is supposed to be case-insensitive, but if it
isn't, the wrong case will cause a :exc:`~b2handle.handleexceptions.ReverseLookupException`.
*Note:* If allowed search keys are configured, only these are used. If
no allowed search keys are specified, all key-value pairs are
passed on to the reverse lookup servlet, possibly causing a
:exc:`~b2handle.handleexceptions.ReverseLookupException`.
Example calls:
.. code:: python
list_of_handles = search_handle('http://www.foo.com')
list_of_handles = search_handle('http://www.foo.com', CHECKSUM=99999)
list_of_handles = search_handle(URL='http://www.foo.com', CHECKSUM=99999)
:param URL: Optional. The URL to search for (reverse lookup). [This is
NOT the URL of the search servlet!]
:param prefix: Optional. The Handle prefix to which the search should
be limited to. If unspecified, the method will search across all
prefixes present at the server given to the constructor.
:param key_value_pairs: Optional. Several search fields and values can
be specified as key-value-pairs,
e.g. CHECKSUM=123456, URL=www.foo.com
:raise: :exc:`~b2handle.handleexceptions.ReverseLookupException`: If a search field is specified that
cannot be used, or if something else goes wrong.
:return: A list of all Handles (strings) that bear the given key with
given value of given prefix or server. The list may be empty and
may also contain more than one element.
'''
LOGGER.debug('search_handle...')
list_of_handles = self.__searcher.search_handle(URL=URL, prefix=prefix, **key_value_pairs)
return list_of_handles
|
[
"def",
"search_handle",
"(",
"self",
",",
"URL",
"=",
"None",
",",
"prefix",
"=",
"None",
",",
"*",
"*",
"key_value_pairs",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'search_handle...'",
")",
"list_of_handles",
"=",
"self",
".",
"__searcher",
".",
"search_handle",
"(",
"URL",
"=",
"URL",
",",
"prefix",
"=",
"prefix",
",",
"*",
"*",
"key_value_pairs",
")",
"return",
"list_of_handles"
] |
Search for handles containing the specified key with the specified
value. The search terms are passed on to the reverse lookup servlet
as-is. The servlet is supposed to be case-insensitive, but if it
isn't, the wrong case will cause a :exc:`~b2handle.handleexceptions.ReverseLookupException`.
*Note:* If allowed search keys are configured, only these are used. If
no allowed search keys are specified, all key-value pairs are
passed on to the reverse lookup servlet, possibly causing a
:exc:`~b2handle.handleexceptions.ReverseLookupException`.
Example calls:
.. code:: python
list_of_handles = search_handle('http://www.foo.com')
list_of_handles = search_handle('http://www.foo.com', CHECKSUM=99999)
list_of_handles = search_handle(URL='http://www.foo.com', CHECKSUM=99999)
:param URL: Optional. The URL to search for (reverse lookup). [This is
NOT the URL of the search servlet!]
:param prefix: Optional. The Handle prefix to which the search should
be limited to. If unspecified, the method will search across all
prefixes present at the server given to the constructor.
:param key_value_pairs: Optional. Several search fields and values can
be specified as key-value-pairs,
e.g. CHECKSUM=123456, URL=www.foo.com
:raise: :exc:`~b2handle.handleexceptions.ReverseLookupException`: If a search field is specified that
cannot be used, or if something else goes wrong.
:return: A list of all Handles (strings) that bear the given key with
given value of given prefix or server. The list may be empty and
may also contain more than one element.
|
[
"Search",
"for",
"handles",
"containing",
"the",
"specified",
"key",
"with",
"the",
"specified",
"value",
".",
"The",
"search",
"terms",
"are",
"passed",
"on",
"to",
"the",
"reverse",
"lookup",
"servlet",
"as",
"-",
"is",
".",
"The",
"servlet",
"is",
"supposed",
"to",
"be",
"case",
"-",
"insensitive",
"but",
"if",
"it",
"isn",
"t",
"the",
"wrong",
"case",
"will",
"cause",
"a",
":",
"exc",
":",
"~b2handle",
".",
"handleexceptions",
".",
"ReverseLookupException",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handleclient.py#L934-L973
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/handleclient.py
|
EUDATHandleClient.generate_PID_name
|
def generate_PID_name(self, prefix=None):
'''
Generate a unique random Handle name (random UUID). The Handle is not
registered. If a prefix is specified, the PID name has the syntax
<prefix>/<generatedname>, otherwise it just returns the generated
random name (suffix for the Handle).
:param prefix: Optional. The prefix to be used for the Handle name.
:return: The handle name in the form <prefix>/<generatedsuffix> or
<generatedsuffix>.
'''
LOGGER.debug('generate_PID_name...')
randomuuid = uuid.uuid4()
if prefix is not None:
return prefix + '/' + str(randomuuid)
else:
return str(randomuuid)
|
python
|
def generate_PID_name(self, prefix=None):
'''
Generate a unique random Handle name (random UUID). The Handle is not
registered. If a prefix is specified, the PID name has the syntax
<prefix>/<generatedname>, otherwise it just returns the generated
random name (suffix for the Handle).
:param prefix: Optional. The prefix to be used for the Handle name.
:return: The handle name in the form <prefix>/<generatedsuffix> or
<generatedsuffix>.
'''
LOGGER.debug('generate_PID_name...')
randomuuid = uuid.uuid4()
if prefix is not None:
return prefix + '/' + str(randomuuid)
else:
return str(randomuuid)
|
[
"def",
"generate_PID_name",
"(",
"self",
",",
"prefix",
"=",
"None",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'generate_PID_name...'",
")",
"randomuuid",
"=",
"uuid",
".",
"uuid4",
"(",
")",
"if",
"prefix",
"is",
"not",
"None",
":",
"return",
"prefix",
"+",
"'/'",
"+",
"str",
"(",
"randomuuid",
")",
"else",
":",
"return",
"str",
"(",
"randomuuid",
")"
] |
Generate a unique random Handle name (random UUID). The Handle is not
registered. If a prefix is specified, the PID name has the syntax
<prefix>/<generatedname>, otherwise it just returns the generated
random name (suffix for the Handle).
:param prefix: Optional. The prefix to be used for the Handle name.
:return: The handle name in the form <prefix>/<generatedsuffix> or
<generatedsuffix>.
|
[
"Generate",
"a",
"unique",
"random",
"Handle",
"name",
"(",
"random",
"UUID",
")",
".",
"The",
"Handle",
"is",
"not",
"registered",
".",
"If",
"a",
"prefix",
"is",
"specified",
"the",
"PID",
"name",
"has",
"the",
"syntax",
"<prefix",
">",
"/",
"<generatedname",
">",
"otherwise",
"it",
"just",
"returns",
"the",
"generated",
"random",
"name",
"(",
"suffix",
"for",
"the",
"Handle",
")",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handleclient.py#L975-L993
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/handleclient.py
|
EUDATHandleClient.get_handlerecord_indices_for_key
|
def get_handlerecord_indices_for_key(self, key, list_of_entries):
'''
Finds the Handle entry indices of all entries that have a specific
type.
*Important:* It finds the Handle System indices! These are not
the python indices of the list, so they can not be used for
iteration.
:param key: The key (Handle Record type)
:param list_of_entries: A list of the existing entries in which to find
the indices.
:return: A list of strings, the indices of the entries of type "key" in
the given handle record.
'''
LOGGER.debug('get_handlerecord_indices_for_key...')
indices = []
for entry in list_of_entries:
if entry['type'] == key:
indices.append(entry['index'])
return indices
|
python
|
def get_handlerecord_indices_for_key(self, key, list_of_entries):
'''
Finds the Handle entry indices of all entries that have a specific
type.
*Important:* It finds the Handle System indices! These are not
the python indices of the list, so they can not be used for
iteration.
:param key: The key (Handle Record type)
:param list_of_entries: A list of the existing entries in which to find
the indices.
:return: A list of strings, the indices of the entries of type "key" in
the given handle record.
'''
LOGGER.debug('get_handlerecord_indices_for_key...')
indices = []
for entry in list_of_entries:
if entry['type'] == key:
indices.append(entry['index'])
return indices
|
[
"def",
"get_handlerecord_indices_for_key",
"(",
"self",
",",
"key",
",",
"list_of_entries",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'get_handlerecord_indices_for_key...'",
")",
"indices",
"=",
"[",
"]",
"for",
"entry",
"in",
"list_of_entries",
":",
"if",
"entry",
"[",
"'type'",
"]",
"==",
"key",
":",
"indices",
".",
"append",
"(",
"entry",
"[",
"'index'",
"]",
")",
"return",
"indices"
] |
Finds the Handle entry indices of all entries that have a specific
type.
*Important:* It finds the Handle System indices! These are not
the python indices of the list, so they can not be used for
iteration.
:param key: The key (Handle Record type)
:param list_of_entries: A list of the existing entries in which to find
the indices.
:return: A list of strings, the indices of the entries of type "key" in
the given handle record.
|
[
"Finds",
"the",
"Handle",
"entry",
"indices",
"of",
"all",
"entries",
"that",
"have",
"a",
"specific",
"type",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handleclient.py#L997-L1019
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/handleclient.py
|
EUDATHandleClient.__send_handle_delete_request
|
def __send_handle_delete_request(self, handle, indices=None, op=None):
'''
Send a HTTP DELETE request to the handle server to delete either an
entire handle or to some specified values from a handle record,
using the requests module.
:param handle: The handle.
:param indices: Optional. A list of indices to delete. Defaults to
None (i.e. the entire handle is deleted.). The list can contain
integers or strings.
:return: The server's response.
'''
resp = self.__handlesystemconnector.send_handle_delete_request(
handle=handle,
indices=indices,
op=op)
return resp
|
python
|
def __send_handle_delete_request(self, handle, indices=None, op=None):
'''
Send a HTTP DELETE request to the handle server to delete either an
entire handle or to some specified values from a handle record,
using the requests module.
:param handle: The handle.
:param indices: Optional. A list of indices to delete. Defaults to
None (i.e. the entire handle is deleted.). The list can contain
integers or strings.
:return: The server's response.
'''
resp = self.__handlesystemconnector.send_handle_delete_request(
handle=handle,
indices=indices,
op=op)
return resp
|
[
"def",
"__send_handle_delete_request",
"(",
"self",
",",
"handle",
",",
"indices",
"=",
"None",
",",
"op",
"=",
"None",
")",
":",
"resp",
"=",
"self",
".",
"__handlesystemconnector",
".",
"send_handle_delete_request",
"(",
"handle",
"=",
"handle",
",",
"indices",
"=",
"indices",
",",
"op",
"=",
"op",
")",
"return",
"resp"
] |
Send a HTTP DELETE request to the handle server to delete either an
entire handle or to some specified values from a handle record,
using the requests module.
:param handle: The handle.
:param indices: Optional. A list of indices to delete. Defaults to
None (i.e. the entire handle is deleted.). The list can contain
integers or strings.
:return: The server's response.
|
[
"Send",
"a",
"HTTP",
"DELETE",
"request",
"to",
"the",
"handle",
"server",
"to",
"delete",
"either",
"an",
"entire",
"handle",
"or",
"to",
"some",
"specified",
"values",
"from",
"a",
"handle",
"record",
"using",
"the",
"requests",
"module",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handleclient.py#L1023-L1040
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/handleclient.py
|
EUDATHandleClient.__send_handle_put_request
|
def __send_handle_put_request(self, handle, list_of_entries, indices=None, overwrite=False, op=None):
'''
Send a HTTP PUT request to the handle server to write either an entire
handle or to some specified values to an handle record, using the
requests module.
:param handle: The handle.
:param list_of_entries: A list of handle record entries to be written,
in the format [{"index":xyz, "type":"xyz", "data":"xyz"}] or similar.
:param indices: Optional. A list of indices to modify. Defaults
to None (i.e. the entire handle is updated.). The list can
contain integers or strings.
:param overwrite: Optional. Whether the handle should be overwritten
if it exists already.
:return: The server's response.
'''
resp, payload = self.__handlesystemconnector.send_handle_put_request(
handle=handle,
list_of_entries=list_of_entries,
indices=indices,
overwrite=overwrite,
op=op
)
return resp, payload
|
python
|
def __send_handle_put_request(self, handle, list_of_entries, indices=None, overwrite=False, op=None):
'''
Send a HTTP PUT request to the handle server to write either an entire
handle or to some specified values to an handle record, using the
requests module.
:param handle: The handle.
:param list_of_entries: A list of handle record entries to be written,
in the format [{"index":xyz, "type":"xyz", "data":"xyz"}] or similar.
:param indices: Optional. A list of indices to modify. Defaults
to None (i.e. the entire handle is updated.). The list can
contain integers or strings.
:param overwrite: Optional. Whether the handle should be overwritten
if it exists already.
:return: The server's response.
'''
resp, payload = self.__handlesystemconnector.send_handle_put_request(
handle=handle,
list_of_entries=list_of_entries,
indices=indices,
overwrite=overwrite,
op=op
)
return resp, payload
|
[
"def",
"__send_handle_put_request",
"(",
"self",
",",
"handle",
",",
"list_of_entries",
",",
"indices",
"=",
"None",
",",
"overwrite",
"=",
"False",
",",
"op",
"=",
"None",
")",
":",
"resp",
",",
"payload",
"=",
"self",
".",
"__handlesystemconnector",
".",
"send_handle_put_request",
"(",
"handle",
"=",
"handle",
",",
"list_of_entries",
"=",
"list_of_entries",
",",
"indices",
"=",
"indices",
",",
"overwrite",
"=",
"overwrite",
",",
"op",
"=",
"op",
")",
"return",
"resp",
",",
"payload"
] |
Send a HTTP PUT request to the handle server to write either an entire
handle or to some specified values to an handle record, using the
requests module.
:param handle: The handle.
:param list_of_entries: A list of handle record entries to be written,
in the format [{"index":xyz, "type":"xyz", "data":"xyz"}] or similar.
:param indices: Optional. A list of indices to modify. Defaults
to None (i.e. the entire handle is updated.). The list can
contain integers or strings.
:param overwrite: Optional. Whether the handle should be overwritten
if it exists already.
:return: The server's response.
|
[
"Send",
"a",
"HTTP",
"PUT",
"request",
"to",
"the",
"handle",
"server",
"to",
"write",
"either",
"an",
"entire",
"handle",
"or",
"to",
"some",
"specified",
"values",
"to",
"an",
"handle",
"record",
"using",
"the",
"requests",
"module",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handleclient.py#L1042-L1066
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/handleclient.py
|
EUDATHandleClient.__send_handle_get_request
|
def __send_handle_get_request(self, handle, indices=None):
'''
Send a HTTP GET request to the handle server to read either an entire
handle or to some specified values from a handle record, using the
requests module.
:param handle: The handle.
:param indices: Optional. A list of indices to delete. Defaults to
None (i.e. the entire handle is deleted.). The list can contain
integers or strings.
:return: The server's response.
'''
resp = self.__handlesystemconnector.send_handle_get_request(handle, indices)
return resp
|
python
|
def __send_handle_get_request(self, handle, indices=None):
'''
Send a HTTP GET request to the handle server to read either an entire
handle or to some specified values from a handle record, using the
requests module.
:param handle: The handle.
:param indices: Optional. A list of indices to delete. Defaults to
None (i.e. the entire handle is deleted.). The list can contain
integers or strings.
:return: The server's response.
'''
resp = self.__handlesystemconnector.send_handle_get_request(handle, indices)
return resp
|
[
"def",
"__send_handle_get_request",
"(",
"self",
",",
"handle",
",",
"indices",
"=",
"None",
")",
":",
"resp",
"=",
"self",
".",
"__handlesystemconnector",
".",
"send_handle_get_request",
"(",
"handle",
",",
"indices",
")",
"return",
"resp"
] |
Send a HTTP GET request to the handle server to read either an entire
handle or to some specified values from a handle record, using the
requests module.
:param handle: The handle.
:param indices: Optional. A list of indices to delete. Defaults to
None (i.e. the entire handle is deleted.). The list can contain
integers or strings.
:return: The server's response.
|
[
"Send",
"a",
"HTTP",
"GET",
"request",
"to",
"the",
"handle",
"server",
"to",
"read",
"either",
"an",
"entire",
"handle",
"or",
"to",
"some",
"specified",
"values",
"from",
"a",
"handle",
"record",
"using",
"the",
"requests",
"module",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handleclient.py#L1068-L1082
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/handleclient.py
|
EUDATHandleClient.__get_handle_record_if_necessary
|
def __get_handle_record_if_necessary(self, handle, handlerecord_json):
'''
Returns the handle record if it is None or if its handle is not the
same as the specified handle.
'''
if handlerecord_json is None:
handlerecord_json = self.retrieve_handle_record_json(handle)
else:
if handle != handlerecord_json['handle']:
handlerecord_json = self.retrieve_handle_record_json(handle)
return handlerecord_json
|
python
|
def __get_handle_record_if_necessary(self, handle, handlerecord_json):
'''
Returns the handle record if it is None or if its handle is not the
same as the specified handle.
'''
if handlerecord_json is None:
handlerecord_json = self.retrieve_handle_record_json(handle)
else:
if handle != handlerecord_json['handle']:
handlerecord_json = self.retrieve_handle_record_json(handle)
return handlerecord_json
|
[
"def",
"__get_handle_record_if_necessary",
"(",
"self",
",",
"handle",
",",
"handlerecord_json",
")",
":",
"if",
"handlerecord_json",
"is",
"None",
":",
"handlerecord_json",
"=",
"self",
".",
"retrieve_handle_record_json",
"(",
"handle",
")",
"else",
":",
"if",
"handle",
"!=",
"handlerecord_json",
"[",
"'handle'",
"]",
":",
"handlerecord_json",
"=",
"self",
".",
"retrieve_handle_record_json",
"(",
"handle",
")",
"return",
"handlerecord_json"
] |
Returns the handle record if it is None or if its handle is not the
same as the specified handle.
|
[
"Returns",
"the",
"handle",
"record",
"if",
"it",
"is",
"None",
"or",
"if",
"its",
"handle",
"is",
"not",
"the",
"same",
"as",
"the",
"specified",
"handle",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handleclient.py#L1084-L1095
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/handleclient.py
|
EUDATHandleClient.__make_another_index
|
def __make_another_index(self, list_of_entries, url=False, hs_admin=False):
'''
Find an index not yet used in the handle record and not reserved for
any (other) special type.
:param: list_of_entries: List of all entries to find which indices are
used already.
:param url: If True, an index for an URL entry is returned (1, unless
it is already in use).
:param hs_admin: If True, an index for HS_ADMIN is returned (100 or one
of the following).
:return: An integer.
'''
start = 2
# reserved indices:
reserved_for_url = set([1])
reserved_for_admin = set(range(100, 200))
prohibited_indices = reserved_for_url | reserved_for_admin
if url:
prohibited_indices = prohibited_indices - reserved_for_url
start = 1
elif hs_admin:
prohibited_indices = prohibited_indices - reserved_for_admin
start = 100
# existing indices
existing_indices = set()
if list_of_entries is not None:
for entry in list_of_entries:
existing_indices.add(int(entry['index']))
# find new index:
all_prohibited_indices = existing_indices | prohibited_indices
searchmax = max(start, max(all_prohibited_indices)) + 2
for index in xrange(start, searchmax):
if index not in all_prohibited_indices:
return index
|
python
|
def __make_another_index(self, list_of_entries, url=False, hs_admin=False):
'''
Find an index not yet used in the handle record and not reserved for
any (other) special type.
:param: list_of_entries: List of all entries to find which indices are
used already.
:param url: If True, an index for an URL entry is returned (1, unless
it is already in use).
:param hs_admin: If True, an index for HS_ADMIN is returned (100 or one
of the following).
:return: An integer.
'''
start = 2
# reserved indices:
reserved_for_url = set([1])
reserved_for_admin = set(range(100, 200))
prohibited_indices = reserved_for_url | reserved_for_admin
if url:
prohibited_indices = prohibited_indices - reserved_for_url
start = 1
elif hs_admin:
prohibited_indices = prohibited_indices - reserved_for_admin
start = 100
# existing indices
existing_indices = set()
if list_of_entries is not None:
for entry in list_of_entries:
existing_indices.add(int(entry['index']))
# find new index:
all_prohibited_indices = existing_indices | prohibited_indices
searchmax = max(start, max(all_prohibited_indices)) + 2
for index in xrange(start, searchmax):
if index not in all_prohibited_indices:
return index
|
[
"def",
"__make_another_index",
"(",
"self",
",",
"list_of_entries",
",",
"url",
"=",
"False",
",",
"hs_admin",
"=",
"False",
")",
":",
"start",
"=",
"2",
"# reserved indices:",
"reserved_for_url",
"=",
"set",
"(",
"[",
"1",
"]",
")",
"reserved_for_admin",
"=",
"set",
"(",
"range",
"(",
"100",
",",
"200",
")",
")",
"prohibited_indices",
"=",
"reserved_for_url",
"|",
"reserved_for_admin",
"if",
"url",
":",
"prohibited_indices",
"=",
"prohibited_indices",
"-",
"reserved_for_url",
"start",
"=",
"1",
"elif",
"hs_admin",
":",
"prohibited_indices",
"=",
"prohibited_indices",
"-",
"reserved_for_admin",
"start",
"=",
"100",
"# existing indices",
"existing_indices",
"=",
"set",
"(",
")",
"if",
"list_of_entries",
"is",
"not",
"None",
":",
"for",
"entry",
"in",
"list_of_entries",
":",
"existing_indices",
".",
"add",
"(",
"int",
"(",
"entry",
"[",
"'index'",
"]",
")",
")",
"# find new index:",
"all_prohibited_indices",
"=",
"existing_indices",
"|",
"prohibited_indices",
"searchmax",
"=",
"max",
"(",
"start",
",",
"max",
"(",
"all_prohibited_indices",
")",
")",
"+",
"2",
"for",
"index",
"in",
"xrange",
"(",
"start",
",",
"searchmax",
")",
":",
"if",
"index",
"not",
"in",
"all_prohibited_indices",
":",
"return",
"index"
] |
Find an index not yet used in the handle record and not reserved for
any (other) special type.
:param: list_of_entries: List of all entries to find which indices are
used already.
:param url: If True, an index for an URL entry is returned (1, unless
it is already in use).
:param hs_admin: If True, an index for HS_ADMIN is returned (100 or one
of the following).
:return: An integer.
|
[
"Find",
"an",
"index",
"not",
"yet",
"used",
"in",
"the",
"handle",
"record",
"and",
"not",
"reserved",
"for",
"any",
"(",
"other",
")",
"special",
"type",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handleclient.py#L1097-L1136
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/handleclient.py
|
EUDATHandleClient.__create_entry
|
def __create_entry(self, entrytype, data, index, ttl=None):
'''
Create an entry of any type except HS_ADMIN.
:param entrytype: THe type of entry to create, e.g. 'URL' or
'checksum' or ... Note: For entries of type 'HS_ADMIN', please
use __create_admin_entry(). For type '10320/LOC', please use
'add_additional_URL()'
:param data: The actual value for the entry. Can be a simple string,
e.g. "example", or a dict {"format":"string", "value":"example"}.
:param index: The integer to be used as index.
:param ttl: Optional. If not set, the library's default is set. If
there is no default, it is not set by this library, so Handle
System sets it.
:return: The entry as a dict.
'''
if entrytype == 'HS_ADMIN':
op = 'creating HS_ADMIN entry'
msg = 'This method can not create HS_ADMIN entries.'
raise IllegalOperationException(operation=op, msg=msg)
entry = {'index':index, 'type':entrytype, 'data':data}
if ttl is not None:
entry['ttl'] = ttl
return entry
|
python
|
def __create_entry(self, entrytype, data, index, ttl=None):
'''
Create an entry of any type except HS_ADMIN.
:param entrytype: THe type of entry to create, e.g. 'URL' or
'checksum' or ... Note: For entries of type 'HS_ADMIN', please
use __create_admin_entry(). For type '10320/LOC', please use
'add_additional_URL()'
:param data: The actual value for the entry. Can be a simple string,
e.g. "example", or a dict {"format":"string", "value":"example"}.
:param index: The integer to be used as index.
:param ttl: Optional. If not set, the library's default is set. If
there is no default, it is not set by this library, so Handle
System sets it.
:return: The entry as a dict.
'''
if entrytype == 'HS_ADMIN':
op = 'creating HS_ADMIN entry'
msg = 'This method can not create HS_ADMIN entries.'
raise IllegalOperationException(operation=op, msg=msg)
entry = {'index':index, 'type':entrytype, 'data':data}
if ttl is not None:
entry['ttl'] = ttl
return entry
|
[
"def",
"__create_entry",
"(",
"self",
",",
"entrytype",
",",
"data",
",",
"index",
",",
"ttl",
"=",
"None",
")",
":",
"if",
"entrytype",
"==",
"'HS_ADMIN'",
":",
"op",
"=",
"'creating HS_ADMIN entry'",
"msg",
"=",
"'This method can not create HS_ADMIN entries.'",
"raise",
"IllegalOperationException",
"(",
"operation",
"=",
"op",
",",
"msg",
"=",
"msg",
")",
"entry",
"=",
"{",
"'index'",
":",
"index",
",",
"'type'",
":",
"entrytype",
",",
"'data'",
":",
"data",
"}",
"if",
"ttl",
"is",
"not",
"None",
":",
"entry",
"[",
"'ttl'",
"]",
"=",
"ttl",
"return",
"entry"
] |
Create an entry of any type except HS_ADMIN.
:param entrytype: THe type of entry to create, e.g. 'URL' or
'checksum' or ... Note: For entries of type 'HS_ADMIN', please
use __create_admin_entry(). For type '10320/LOC', please use
'add_additional_URL()'
:param data: The actual value for the entry. Can be a simple string,
e.g. "example", or a dict {"format":"string", "value":"example"}.
:param index: The integer to be used as index.
:param ttl: Optional. If not set, the library's default is set. If
there is no default, it is not set by this library, so Handle
System sets it.
:return: The entry as a dict.
|
[
"Create",
"an",
"entry",
"of",
"any",
"type",
"except",
"HS_ADMIN",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handleclient.py#L1138-L1165
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/handleclient.py
|
EUDATHandleClient.__create_admin_entry
|
def __create_admin_entry(self, handleowner, permissions, index, handle, ttl=None):
'''
Create an entry of type "HS_ADMIN".
:param username: The username, i.e. a handle with an index
(index:prefix/suffix). The value referenced by the index contains
authentcation information, e.g. a hidden entry containing a key.
:param permissions: The permissions as a string of zeros and ones,
e.g. '0111011101011'. If not all twelve bits are set, the remaining
ones are set to zero.
:param index: The integer to be used as index of this admin entry (not
of the username!). Should be 1xx.
:param ttl: Optional. If not set, the library's default is set. If
there is no default, it is not set by this library, so Handle
System sets it.
:return: The entry as a dict.
'''
# If the handle owner is specified, use it. Otherwise, use 200:0.NA/prefix
# With the prefix taken from the handle that is being created, not from anywhere else.
if handleowner is None:
adminindex = '200'
prefix = handle.split('/')[0]
adminhandle = '0.NA/' + prefix
else:
adminindex, adminhandle = utilhandle.remove_index_from_handle(handleowner)
data = {
'value':{
'index':adminindex,
'handle':adminhandle,
'permissions':permissions
},
'format':'admin'
}
entry = {'index':index, 'type':'HS_ADMIN', 'data':data}
if ttl is not None:
entry['ttl'] = ttl
return entry
|
python
|
def __create_admin_entry(self, handleowner, permissions, index, handle, ttl=None):
'''
Create an entry of type "HS_ADMIN".
:param username: The username, i.e. a handle with an index
(index:prefix/suffix). The value referenced by the index contains
authentcation information, e.g. a hidden entry containing a key.
:param permissions: The permissions as a string of zeros and ones,
e.g. '0111011101011'. If not all twelve bits are set, the remaining
ones are set to zero.
:param index: The integer to be used as index of this admin entry (not
of the username!). Should be 1xx.
:param ttl: Optional. If not set, the library's default is set. If
there is no default, it is not set by this library, so Handle
System sets it.
:return: The entry as a dict.
'''
# If the handle owner is specified, use it. Otherwise, use 200:0.NA/prefix
# With the prefix taken from the handle that is being created, not from anywhere else.
if handleowner is None:
adminindex = '200'
prefix = handle.split('/')[0]
adminhandle = '0.NA/' + prefix
else:
adminindex, adminhandle = utilhandle.remove_index_from_handle(handleowner)
data = {
'value':{
'index':adminindex,
'handle':adminhandle,
'permissions':permissions
},
'format':'admin'
}
entry = {'index':index, 'type':'HS_ADMIN', 'data':data}
if ttl is not None:
entry['ttl'] = ttl
return entry
|
[
"def",
"__create_admin_entry",
"(",
"self",
",",
"handleowner",
",",
"permissions",
",",
"index",
",",
"handle",
",",
"ttl",
"=",
"None",
")",
":",
"# If the handle owner is specified, use it. Otherwise, use 200:0.NA/prefix",
"# With the prefix taken from the handle that is being created, not from anywhere else.",
"if",
"handleowner",
"is",
"None",
":",
"adminindex",
"=",
"'200'",
"prefix",
"=",
"handle",
".",
"split",
"(",
"'/'",
")",
"[",
"0",
"]",
"adminhandle",
"=",
"'0.NA/'",
"+",
"prefix",
"else",
":",
"adminindex",
",",
"adminhandle",
"=",
"utilhandle",
".",
"remove_index_from_handle",
"(",
"handleowner",
")",
"data",
"=",
"{",
"'value'",
":",
"{",
"'index'",
":",
"adminindex",
",",
"'handle'",
":",
"adminhandle",
",",
"'permissions'",
":",
"permissions",
"}",
",",
"'format'",
":",
"'admin'",
"}",
"entry",
"=",
"{",
"'index'",
":",
"index",
",",
"'type'",
":",
"'HS_ADMIN'",
",",
"'data'",
":",
"data",
"}",
"if",
"ttl",
"is",
"not",
"None",
":",
"entry",
"[",
"'ttl'",
"]",
"=",
"ttl",
"return",
"entry"
] |
Create an entry of type "HS_ADMIN".
:param username: The username, i.e. a handle with an index
(index:prefix/suffix). The value referenced by the index contains
authentcation information, e.g. a hidden entry containing a key.
:param permissions: The permissions as a string of zeros and ones,
e.g. '0111011101011'. If not all twelve bits are set, the remaining
ones are set to zero.
:param index: The integer to be used as index of this admin entry (not
of the username!). Should be 1xx.
:param ttl: Optional. If not set, the library's default is set. If
there is no default, it is not set by this library, so Handle
System sets it.
:return: The entry as a dict.
|
[
"Create",
"an",
"entry",
"of",
"type",
"HS_ADMIN",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handleclient.py#L1167-L1206
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/handleclient.py
|
EUDATHandleClient.__get_python_indices_for_key
|
def __get_python_indices_for_key(self, key, list_of_entries):
'''
Finds the indices of all entries that have a specific type. Important:
This method finds the python indices of the list of entries! These
are not the Handle System index values!
:param key: The key (Handle Record type)
:param list_of_entries: A list of the existing entries in which to find
the indices.
:return: A list of integers, the indices of the entries of type "key"
in the given list.
'''
indices = []
for i in xrange(len(list_of_entries)):
if list_of_entries[i]['type'] == key:
indices.append(i)
return indices
|
python
|
def __get_python_indices_for_key(self, key, list_of_entries):
'''
Finds the indices of all entries that have a specific type. Important:
This method finds the python indices of the list of entries! These
are not the Handle System index values!
:param key: The key (Handle Record type)
:param list_of_entries: A list of the existing entries in which to find
the indices.
:return: A list of integers, the indices of the entries of type "key"
in the given list.
'''
indices = []
for i in xrange(len(list_of_entries)):
if list_of_entries[i]['type'] == key:
indices.append(i)
return indices
|
[
"def",
"__get_python_indices_for_key",
"(",
"self",
",",
"key",
",",
"list_of_entries",
")",
":",
"indices",
"=",
"[",
"]",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"list_of_entries",
")",
")",
":",
"if",
"list_of_entries",
"[",
"i",
"]",
"[",
"'type'",
"]",
"==",
"key",
":",
"indices",
".",
"append",
"(",
"i",
")",
"return",
"indices"
] |
Finds the indices of all entries that have a specific type. Important:
This method finds the python indices of the list of entries! These
are not the Handle System index values!
:param key: The key (Handle Record type)
:param list_of_entries: A list of the existing entries in which to find
the indices.
:return: A list of integers, the indices of the entries of type "key"
in the given list.
|
[
"Finds",
"the",
"indices",
"of",
"all",
"entries",
"that",
"have",
"a",
"specific",
"type",
".",
"Important",
":",
"This",
"method",
"finds",
"the",
"python",
"indices",
"of",
"the",
"list",
"of",
"entries!",
"These",
"are",
"not",
"the",
"Handle",
"System",
"index",
"values!"
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handleclient.py#L1208-L1224
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/handleclient.py
|
EUDATHandleClient.__exchange_URL_in_13020loc
|
def __exchange_URL_in_13020loc(self, oldurl, newurl, list_of_entries, handle):
'''
Exchange every occurrence of oldurl against newurl in a 10320/LOC entry.
This does not change the ids or other xml attributes of the
<location> element.
:param oldurl: The URL that will be overwritten.
:param newurl: The URL to write into the entry.
:param list_of_entries: A list of the existing entries (to find and
remove the correct one).
:param handle: Only for the exception message.
:raise: GenericHandleError: If several 10320/LOC exist (unlikely).
'''
# Find existing 10320/LOC entries
python_indices = self.__get_python_indices_for_key(
'10320/LOC',
list_of_entries
)
num_exchanged = 0
if len(python_indices) > 0:
if len(python_indices) > 1:
msg = str(len(python_indices)) + ' entries of type "10320/LOC".'
raise BrokenHandleRecordException(handle=handle, msg=msg)
for index in python_indices:
entry = list_of_entries.pop(index)
xmlroot = ET.fromstring(entry['data']['value'])
all_URL_elements = xmlroot.findall('location')
for element in all_URL_elements:
if element.get('href') == oldurl:
LOGGER.debug('__exchange_URL_in_13020loc: Exchanging URL ' + oldurl + ' from 10320/LOC.')
num_exchanged += 1
element.set('href', newurl)
entry['data']['value'] = ET.tostring(xmlroot, encoding=encoding_value)
list_of_entries.append(entry)
if num_exchanged == 0:
LOGGER.debug('__exchange_URL_in_13020loc: No URLs exchanged.')
else:
message = '__exchange_URL_in_13020loc: The URL "' + oldurl + '" was exchanged ' + str(num_exchanged) + \
' times against the new url "' + newurl + '" in 10320/LOC.'
message = message.replace('1 times', 'once')
LOGGER.debug(message)
|
python
|
def __exchange_URL_in_13020loc(self, oldurl, newurl, list_of_entries, handle):
'''
Exchange every occurrence of oldurl against newurl in a 10320/LOC entry.
This does not change the ids or other xml attributes of the
<location> element.
:param oldurl: The URL that will be overwritten.
:param newurl: The URL to write into the entry.
:param list_of_entries: A list of the existing entries (to find and
remove the correct one).
:param handle: Only for the exception message.
:raise: GenericHandleError: If several 10320/LOC exist (unlikely).
'''
# Find existing 10320/LOC entries
python_indices = self.__get_python_indices_for_key(
'10320/LOC',
list_of_entries
)
num_exchanged = 0
if len(python_indices) > 0:
if len(python_indices) > 1:
msg = str(len(python_indices)) + ' entries of type "10320/LOC".'
raise BrokenHandleRecordException(handle=handle, msg=msg)
for index in python_indices:
entry = list_of_entries.pop(index)
xmlroot = ET.fromstring(entry['data']['value'])
all_URL_elements = xmlroot.findall('location')
for element in all_URL_elements:
if element.get('href') == oldurl:
LOGGER.debug('__exchange_URL_in_13020loc: Exchanging URL ' + oldurl + ' from 10320/LOC.')
num_exchanged += 1
element.set('href', newurl)
entry['data']['value'] = ET.tostring(xmlroot, encoding=encoding_value)
list_of_entries.append(entry)
if num_exchanged == 0:
LOGGER.debug('__exchange_URL_in_13020loc: No URLs exchanged.')
else:
message = '__exchange_URL_in_13020loc: The URL "' + oldurl + '" was exchanged ' + str(num_exchanged) + \
' times against the new url "' + newurl + '" in 10320/LOC.'
message = message.replace('1 times', 'once')
LOGGER.debug(message)
|
[
"def",
"__exchange_URL_in_13020loc",
"(",
"self",
",",
"oldurl",
",",
"newurl",
",",
"list_of_entries",
",",
"handle",
")",
":",
"# Find existing 10320/LOC entries",
"python_indices",
"=",
"self",
".",
"__get_python_indices_for_key",
"(",
"'10320/LOC'",
",",
"list_of_entries",
")",
"num_exchanged",
"=",
"0",
"if",
"len",
"(",
"python_indices",
")",
">",
"0",
":",
"if",
"len",
"(",
"python_indices",
")",
">",
"1",
":",
"msg",
"=",
"str",
"(",
"len",
"(",
"python_indices",
")",
")",
"+",
"' entries of type \"10320/LOC\".'",
"raise",
"BrokenHandleRecordException",
"(",
"handle",
"=",
"handle",
",",
"msg",
"=",
"msg",
")",
"for",
"index",
"in",
"python_indices",
":",
"entry",
"=",
"list_of_entries",
".",
"pop",
"(",
"index",
")",
"xmlroot",
"=",
"ET",
".",
"fromstring",
"(",
"entry",
"[",
"'data'",
"]",
"[",
"'value'",
"]",
")",
"all_URL_elements",
"=",
"xmlroot",
".",
"findall",
"(",
"'location'",
")",
"for",
"element",
"in",
"all_URL_elements",
":",
"if",
"element",
".",
"get",
"(",
"'href'",
")",
"==",
"oldurl",
":",
"LOGGER",
".",
"debug",
"(",
"'__exchange_URL_in_13020loc: Exchanging URL '",
"+",
"oldurl",
"+",
"' from 10320/LOC.'",
")",
"num_exchanged",
"+=",
"1",
"element",
".",
"set",
"(",
"'href'",
",",
"newurl",
")",
"entry",
"[",
"'data'",
"]",
"[",
"'value'",
"]",
"=",
"ET",
".",
"tostring",
"(",
"xmlroot",
",",
"encoding",
"=",
"encoding_value",
")",
"list_of_entries",
".",
"append",
"(",
"entry",
")",
"if",
"num_exchanged",
"==",
"0",
":",
"LOGGER",
".",
"debug",
"(",
"'__exchange_URL_in_13020loc: No URLs exchanged.'",
")",
"else",
":",
"message",
"=",
"'__exchange_URL_in_13020loc: The URL \"'",
"+",
"oldurl",
"+",
"'\" was exchanged '",
"+",
"str",
"(",
"num_exchanged",
")",
"+",
"' times against the new url \"'",
"+",
"newurl",
"+",
"'\" in 10320/LOC.'",
"message",
"=",
"message",
".",
"replace",
"(",
"'1 times'",
",",
"'once'",
")",
"LOGGER",
".",
"debug",
"(",
"message",
")"
] |
Exchange every occurrence of oldurl against newurl in a 10320/LOC entry.
This does not change the ids or other xml attributes of the
<location> element.
:param oldurl: The URL that will be overwritten.
:param newurl: The URL to write into the entry.
:param list_of_entries: A list of the existing entries (to find and
remove the correct one).
:param handle: Only for the exception message.
:raise: GenericHandleError: If several 10320/LOC exist (unlikely).
|
[
"Exchange",
"every",
"occurrence",
"of",
"oldurl",
"against",
"newurl",
"in",
"a",
"10320",
"/",
"LOC",
"entry",
".",
"This",
"does",
"not",
"change",
"the",
"ids",
"or",
"other",
"xml",
"attributes",
"of",
"the",
"<location",
">",
"element",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handleclient.py#L1226-L1271
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/handleclient.py
|
EUDATHandleClient.__remove_URL_from_10320LOC
|
def __remove_URL_from_10320LOC(self, url, list_of_entries, handle):
'''
Remove an URL from the handle record's "10320/LOC" entry.
If it exists several times in the entry, all occurences are removed.
If the URL is not present, nothing happens.
If after removing, there is no more URLs in the entry, the entry is
removed.
:param url: The URL to be removed.
:param list_of_entries: A list of the existing entries (to find and
remove the correct one).
:param handle: Only for the exception message.
:raise: GenericHandleError: If several 10320/LOC exist (unlikely).
'''
# Find existing 10320/LOC entries
python_indices = self.__get_python_indices_for_key(
'10320/LOC',
list_of_entries
)
num_removed = 0
if len(python_indices) > 0:
if len(python_indices) > 1:
msg = str(len(python_indices)) + ' entries of type "10320/LOC".'
raise BrokenHandleRecordException(handle=handle, msg=msg)
for index in python_indices:
entry = list_of_entries.pop(index)
xmlroot = ET.fromstring(entry['data']['value'])
all_URL_elements = xmlroot.findall('location')
for element in all_URL_elements:
if element.get('href') == url:
LOGGER.debug('__remove_URL_from_10320LOC: Removing URL ' + url + '.')
num_removed += 1
xmlroot.remove(element)
remaining_URL_elements = xmlroot.findall('location')
if len(remaining_URL_elements) == 0:
LOGGER.debug("__remove_URL_from_10320LOC: All URLs removed.")
# TODO FIXME: If we start adapting the Handle Record by
# index (instead of overwriting the entire one), be careful
# to delete the ones that became empty!
else:
entry['data']['value'] = ET.tostring(xmlroot, encoding=encoding_value)
LOGGER.debug('__remove_URL_from_10320LOC: ' + str(len(remaining_URL_elements)) + ' URLs' + \
' left after removal operation.')
list_of_entries.append(entry)
if num_removed == 0:
LOGGER.debug('__remove_URL_from_10320LOC: No URLs removed.')
else:
message = '__remove_URL_from_10320LOC: The URL "' + url + '" was removed '\
+ str(num_removed) + ' times.'
message = message.replace('1 times', 'once')
LOGGER.debug(message)
|
python
|
def __remove_URL_from_10320LOC(self, url, list_of_entries, handle):
'''
Remove an URL from the handle record's "10320/LOC" entry.
If it exists several times in the entry, all occurences are removed.
If the URL is not present, nothing happens.
If after removing, there is no more URLs in the entry, the entry is
removed.
:param url: The URL to be removed.
:param list_of_entries: A list of the existing entries (to find and
remove the correct one).
:param handle: Only for the exception message.
:raise: GenericHandleError: If several 10320/LOC exist (unlikely).
'''
# Find existing 10320/LOC entries
python_indices = self.__get_python_indices_for_key(
'10320/LOC',
list_of_entries
)
num_removed = 0
if len(python_indices) > 0:
if len(python_indices) > 1:
msg = str(len(python_indices)) + ' entries of type "10320/LOC".'
raise BrokenHandleRecordException(handle=handle, msg=msg)
for index in python_indices:
entry = list_of_entries.pop(index)
xmlroot = ET.fromstring(entry['data']['value'])
all_URL_elements = xmlroot.findall('location')
for element in all_URL_elements:
if element.get('href') == url:
LOGGER.debug('__remove_URL_from_10320LOC: Removing URL ' + url + '.')
num_removed += 1
xmlroot.remove(element)
remaining_URL_elements = xmlroot.findall('location')
if len(remaining_URL_elements) == 0:
LOGGER.debug("__remove_URL_from_10320LOC: All URLs removed.")
# TODO FIXME: If we start adapting the Handle Record by
# index (instead of overwriting the entire one), be careful
# to delete the ones that became empty!
else:
entry['data']['value'] = ET.tostring(xmlroot, encoding=encoding_value)
LOGGER.debug('__remove_URL_from_10320LOC: ' + str(len(remaining_URL_elements)) + ' URLs' + \
' left after removal operation.')
list_of_entries.append(entry)
if num_removed == 0:
LOGGER.debug('__remove_URL_from_10320LOC: No URLs removed.')
else:
message = '__remove_URL_from_10320LOC: The URL "' + url + '" was removed '\
+ str(num_removed) + ' times.'
message = message.replace('1 times', 'once')
LOGGER.debug(message)
|
[
"def",
"__remove_URL_from_10320LOC",
"(",
"self",
",",
"url",
",",
"list_of_entries",
",",
"handle",
")",
":",
"# Find existing 10320/LOC entries",
"python_indices",
"=",
"self",
".",
"__get_python_indices_for_key",
"(",
"'10320/LOC'",
",",
"list_of_entries",
")",
"num_removed",
"=",
"0",
"if",
"len",
"(",
"python_indices",
")",
">",
"0",
":",
"if",
"len",
"(",
"python_indices",
")",
">",
"1",
":",
"msg",
"=",
"str",
"(",
"len",
"(",
"python_indices",
")",
")",
"+",
"' entries of type \"10320/LOC\".'",
"raise",
"BrokenHandleRecordException",
"(",
"handle",
"=",
"handle",
",",
"msg",
"=",
"msg",
")",
"for",
"index",
"in",
"python_indices",
":",
"entry",
"=",
"list_of_entries",
".",
"pop",
"(",
"index",
")",
"xmlroot",
"=",
"ET",
".",
"fromstring",
"(",
"entry",
"[",
"'data'",
"]",
"[",
"'value'",
"]",
")",
"all_URL_elements",
"=",
"xmlroot",
".",
"findall",
"(",
"'location'",
")",
"for",
"element",
"in",
"all_URL_elements",
":",
"if",
"element",
".",
"get",
"(",
"'href'",
")",
"==",
"url",
":",
"LOGGER",
".",
"debug",
"(",
"'__remove_URL_from_10320LOC: Removing URL '",
"+",
"url",
"+",
"'.'",
")",
"num_removed",
"+=",
"1",
"xmlroot",
".",
"remove",
"(",
"element",
")",
"remaining_URL_elements",
"=",
"xmlroot",
".",
"findall",
"(",
"'location'",
")",
"if",
"len",
"(",
"remaining_URL_elements",
")",
"==",
"0",
":",
"LOGGER",
".",
"debug",
"(",
"\"__remove_URL_from_10320LOC: All URLs removed.\"",
")",
"# TODO FIXME: If we start adapting the Handle Record by",
"# index (instead of overwriting the entire one), be careful",
"# to delete the ones that became empty!",
"else",
":",
"entry",
"[",
"'data'",
"]",
"[",
"'value'",
"]",
"=",
"ET",
".",
"tostring",
"(",
"xmlroot",
",",
"encoding",
"=",
"encoding_value",
")",
"LOGGER",
".",
"debug",
"(",
"'__remove_URL_from_10320LOC: '",
"+",
"str",
"(",
"len",
"(",
"remaining_URL_elements",
")",
")",
"+",
"' URLs'",
"+",
"' left after removal operation.'",
")",
"list_of_entries",
".",
"append",
"(",
"entry",
")",
"if",
"num_removed",
"==",
"0",
":",
"LOGGER",
".",
"debug",
"(",
"'__remove_URL_from_10320LOC: No URLs removed.'",
")",
"else",
":",
"message",
"=",
"'__remove_URL_from_10320LOC: The URL \"'",
"+",
"url",
"+",
"'\" was removed '",
"+",
"str",
"(",
"num_removed",
")",
"+",
"' times.'",
"message",
"=",
"message",
".",
"replace",
"(",
"'1 times'",
",",
"'once'",
")",
"LOGGER",
".",
"debug",
"(",
"message",
")"
] |
Remove an URL from the handle record's "10320/LOC" entry.
If it exists several times in the entry, all occurences are removed.
If the URL is not present, nothing happens.
If after removing, there is no more URLs in the entry, the entry is
removed.
:param url: The URL to be removed.
:param list_of_entries: A list of the existing entries (to find and
remove the correct one).
:param handle: Only for the exception message.
:raise: GenericHandleError: If several 10320/LOC exist (unlikely).
|
[
"Remove",
"an",
"URL",
"from",
"the",
"handle",
"record",
"s",
"10320",
"/",
"LOC",
"entry",
".",
"If",
"it",
"exists",
"several",
"times",
"in",
"the",
"entry",
"all",
"occurences",
"are",
"removed",
".",
"If",
"the",
"URL",
"is",
"not",
"present",
"nothing",
"happens",
".",
"If",
"after",
"removing",
"there",
"is",
"no",
"more",
"URLs",
"in",
"the",
"entry",
"the",
"entry",
"is",
"removed",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handleclient.py#L1273-L1327
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/handleclient.py
|
EUDATHandleClient.__add_URL_to_10320LOC
|
def __add_URL_to_10320LOC(self, url, list_of_entries, handle=None, weight=None, http_role=None, **kvpairs):
'''
Add a url to the handle record's "10320/LOC" entry.
If no 10320/LOC entry exists, a new one is created (using the
default "chooseby" attribute, if configured).
If the URL is already present, it is not added again, but
the attributes (e.g. weight) are updated/added.
If the existing 10320/LOC entry is mal-formed, an exception will be
thrown (xml.etree.ElementTree.ParseError)
Note: In the unlikely case that several "10320/LOC" entries exist,
an exception is raised.
:param url: The URL to be added.
:param list_of_entries: A list of the existing entries (to find and
adapt the correct one).
:param weight: Optional. The weight to be set (integer between 0 and
1). If None, no weight attribute is set. If the value is outside
the accepted range, it is set to 1.
:param http_role: Optional. The http_role to be set. This accepts any
string. Currently, Handle System can process 'conneg'. In future,
it may be able to process 'no_conneg' and 'browser'.
:param handle: Optional. Only for the exception message.
:param all others: Optional. All other key-value pairs will be set to
the element. Any value is accepted and transformed to string.
:raise: GenericHandleError: If several 10320/LOC exist (unlikely).
'''
# Find existing 10320/LOC entry or create new
indices = self.__get_python_indices_for_key('10320/LOC', list_of_entries)
makenew = False
entry = None
if len(indices) == 0:
index = self.__make_another_index(list_of_entries)
entry = self.__create_entry('10320/LOC', 'add_later', index)
makenew = True
else:
if len(indices) > 1:
msg = 'There is ' + str(len(indices)) + ' 10320/LOC entries.'
raise BrokenHandleRecordException(handle=handle, msg=msg)
ind = indices[0]
entry = list_of_entries.pop(ind)
# Get xml data or make new:
xmlroot = None
if makenew:
xmlroot = ET.Element('locations')
if self.__10320LOC_chooseby is not None:
xmlroot.set('chooseby', self.__10320LOC_chooseby)
else:
try:
xmlroot = ET.fromstring(entry['data']['value'])
except TypeError:
xmlroot = ET.fromstring(entry['data'])
LOGGER.debug("__add_URL_to_10320LOC: xmlroot is (1) " + ET.tostring(xmlroot, encoding=encoding_value))
# Check if URL already there...
location_element = None
existing_location_ids = []
if not makenew:
list_of_locations = xmlroot.findall('location')
for item in list_of_locations:
try:
existing_location_ids.append(int(item.get('id')))
except TypeError:
pass
if item.get('href') == url:
location_element = item
existing_location_ids.sort()
# ... if not, add it!
if location_element is None:
location_id = 0
for existing_id in existing_location_ids:
if location_id == existing_id:
location_id += 1
location_element = ET.SubElement(xmlroot, 'location')
LOGGER.debug("__add_URL_to_10320LOC: location_element is (1) " + ET.tostring(location_element, encoding=encoding_value) + ', now add id ' + str(location_id))
location_element.set('id', str(location_id))
LOGGER.debug("__add_URL_to_10320LOC: location_element is (2) " + ET.tostring(location_element, encoding=encoding_value) + ', now add url ' + str(url))
location_element.set('href', url)
LOGGER.debug("__add_URL_to_10320LOC: location_element is (3) " + ET.tostring(location_element, encoding=encoding_value))
self.__set_or_adapt_10320LOC_attributes(location_element, weight, http_role, **kvpairs)
# FIXME: If we start adapting the Handle Record by index (instead of
# overwriting the entire one), be careful to add and/or overwrite!
# (Re-)Add entire 10320 to entry, add entry to list of entries:
LOGGER.debug("__add_URL_to_10320LOC: xmlroot is (2) " + ET.tostring(xmlroot, encoding=encoding_value))
entry['data'] = ET.tostring(xmlroot, encoding=encoding_value)
list_of_entries.append(entry)
|
python
|
def __add_URL_to_10320LOC(self, url, list_of_entries, handle=None, weight=None, http_role=None, **kvpairs):
'''
Add a url to the handle record's "10320/LOC" entry.
If no 10320/LOC entry exists, a new one is created (using the
default "chooseby" attribute, if configured).
If the URL is already present, it is not added again, but
the attributes (e.g. weight) are updated/added.
If the existing 10320/LOC entry is mal-formed, an exception will be
thrown (xml.etree.ElementTree.ParseError)
Note: In the unlikely case that several "10320/LOC" entries exist,
an exception is raised.
:param url: The URL to be added.
:param list_of_entries: A list of the existing entries (to find and
adapt the correct one).
:param weight: Optional. The weight to be set (integer between 0 and
1). If None, no weight attribute is set. If the value is outside
the accepted range, it is set to 1.
:param http_role: Optional. The http_role to be set. This accepts any
string. Currently, Handle System can process 'conneg'. In future,
it may be able to process 'no_conneg' and 'browser'.
:param handle: Optional. Only for the exception message.
:param all others: Optional. All other key-value pairs will be set to
the element. Any value is accepted and transformed to string.
:raise: GenericHandleError: If several 10320/LOC exist (unlikely).
'''
# Find existing 10320/LOC entry or create new
indices = self.__get_python_indices_for_key('10320/LOC', list_of_entries)
makenew = False
entry = None
if len(indices) == 0:
index = self.__make_another_index(list_of_entries)
entry = self.__create_entry('10320/LOC', 'add_later', index)
makenew = True
else:
if len(indices) > 1:
msg = 'There is ' + str(len(indices)) + ' 10320/LOC entries.'
raise BrokenHandleRecordException(handle=handle, msg=msg)
ind = indices[0]
entry = list_of_entries.pop(ind)
# Get xml data or make new:
xmlroot = None
if makenew:
xmlroot = ET.Element('locations')
if self.__10320LOC_chooseby is not None:
xmlroot.set('chooseby', self.__10320LOC_chooseby)
else:
try:
xmlroot = ET.fromstring(entry['data']['value'])
except TypeError:
xmlroot = ET.fromstring(entry['data'])
LOGGER.debug("__add_URL_to_10320LOC: xmlroot is (1) " + ET.tostring(xmlroot, encoding=encoding_value))
# Check if URL already there...
location_element = None
existing_location_ids = []
if not makenew:
list_of_locations = xmlroot.findall('location')
for item in list_of_locations:
try:
existing_location_ids.append(int(item.get('id')))
except TypeError:
pass
if item.get('href') == url:
location_element = item
existing_location_ids.sort()
# ... if not, add it!
if location_element is None:
location_id = 0
for existing_id in existing_location_ids:
if location_id == existing_id:
location_id += 1
location_element = ET.SubElement(xmlroot, 'location')
LOGGER.debug("__add_URL_to_10320LOC: location_element is (1) " + ET.tostring(location_element, encoding=encoding_value) + ', now add id ' + str(location_id))
location_element.set('id', str(location_id))
LOGGER.debug("__add_URL_to_10320LOC: location_element is (2) " + ET.tostring(location_element, encoding=encoding_value) + ', now add url ' + str(url))
location_element.set('href', url)
LOGGER.debug("__add_URL_to_10320LOC: location_element is (3) " + ET.tostring(location_element, encoding=encoding_value))
self.__set_or_adapt_10320LOC_attributes(location_element, weight, http_role, **kvpairs)
# FIXME: If we start adapting the Handle Record by index (instead of
# overwriting the entire one), be careful to add and/or overwrite!
# (Re-)Add entire 10320 to entry, add entry to list of entries:
LOGGER.debug("__add_URL_to_10320LOC: xmlroot is (2) " + ET.tostring(xmlroot, encoding=encoding_value))
entry['data'] = ET.tostring(xmlroot, encoding=encoding_value)
list_of_entries.append(entry)
|
[
"def",
"__add_URL_to_10320LOC",
"(",
"self",
",",
"url",
",",
"list_of_entries",
",",
"handle",
"=",
"None",
",",
"weight",
"=",
"None",
",",
"http_role",
"=",
"None",
",",
"*",
"*",
"kvpairs",
")",
":",
"# Find existing 10320/LOC entry or create new",
"indices",
"=",
"self",
".",
"__get_python_indices_for_key",
"(",
"'10320/LOC'",
",",
"list_of_entries",
")",
"makenew",
"=",
"False",
"entry",
"=",
"None",
"if",
"len",
"(",
"indices",
")",
"==",
"0",
":",
"index",
"=",
"self",
".",
"__make_another_index",
"(",
"list_of_entries",
")",
"entry",
"=",
"self",
".",
"__create_entry",
"(",
"'10320/LOC'",
",",
"'add_later'",
",",
"index",
")",
"makenew",
"=",
"True",
"else",
":",
"if",
"len",
"(",
"indices",
")",
">",
"1",
":",
"msg",
"=",
"'There is '",
"+",
"str",
"(",
"len",
"(",
"indices",
")",
")",
"+",
"' 10320/LOC entries.'",
"raise",
"BrokenHandleRecordException",
"(",
"handle",
"=",
"handle",
",",
"msg",
"=",
"msg",
")",
"ind",
"=",
"indices",
"[",
"0",
"]",
"entry",
"=",
"list_of_entries",
".",
"pop",
"(",
"ind",
")",
"# Get xml data or make new:",
"xmlroot",
"=",
"None",
"if",
"makenew",
":",
"xmlroot",
"=",
"ET",
".",
"Element",
"(",
"'locations'",
")",
"if",
"self",
".",
"__10320LOC_chooseby",
"is",
"not",
"None",
":",
"xmlroot",
".",
"set",
"(",
"'chooseby'",
",",
"self",
".",
"__10320LOC_chooseby",
")",
"else",
":",
"try",
":",
"xmlroot",
"=",
"ET",
".",
"fromstring",
"(",
"entry",
"[",
"'data'",
"]",
"[",
"'value'",
"]",
")",
"except",
"TypeError",
":",
"xmlroot",
"=",
"ET",
".",
"fromstring",
"(",
"entry",
"[",
"'data'",
"]",
")",
"LOGGER",
".",
"debug",
"(",
"\"__add_URL_to_10320LOC: xmlroot is (1) \"",
"+",
"ET",
".",
"tostring",
"(",
"xmlroot",
",",
"encoding",
"=",
"encoding_value",
")",
")",
"# Check if URL already there...",
"location_element",
"=",
"None",
"existing_location_ids",
"=",
"[",
"]",
"if",
"not",
"makenew",
":",
"list_of_locations",
"=",
"xmlroot",
".",
"findall",
"(",
"'location'",
")",
"for",
"item",
"in",
"list_of_locations",
":",
"try",
":",
"existing_location_ids",
".",
"append",
"(",
"int",
"(",
"item",
".",
"get",
"(",
"'id'",
")",
")",
")",
"except",
"TypeError",
":",
"pass",
"if",
"item",
".",
"get",
"(",
"'href'",
")",
"==",
"url",
":",
"location_element",
"=",
"item",
"existing_location_ids",
".",
"sort",
"(",
")",
"# ... if not, add it!",
"if",
"location_element",
"is",
"None",
":",
"location_id",
"=",
"0",
"for",
"existing_id",
"in",
"existing_location_ids",
":",
"if",
"location_id",
"==",
"existing_id",
":",
"location_id",
"+=",
"1",
"location_element",
"=",
"ET",
".",
"SubElement",
"(",
"xmlroot",
",",
"'location'",
")",
"LOGGER",
".",
"debug",
"(",
"\"__add_URL_to_10320LOC: location_element is (1) \"",
"+",
"ET",
".",
"tostring",
"(",
"location_element",
",",
"encoding",
"=",
"encoding_value",
")",
"+",
"', now add id '",
"+",
"str",
"(",
"location_id",
")",
")",
"location_element",
".",
"set",
"(",
"'id'",
",",
"str",
"(",
"location_id",
")",
")",
"LOGGER",
".",
"debug",
"(",
"\"__add_URL_to_10320LOC: location_element is (2) \"",
"+",
"ET",
".",
"tostring",
"(",
"location_element",
",",
"encoding",
"=",
"encoding_value",
")",
"+",
"', now add url '",
"+",
"str",
"(",
"url",
")",
")",
"location_element",
".",
"set",
"(",
"'href'",
",",
"url",
")",
"LOGGER",
".",
"debug",
"(",
"\"__add_URL_to_10320LOC: location_element is (3) \"",
"+",
"ET",
".",
"tostring",
"(",
"location_element",
",",
"encoding",
"=",
"encoding_value",
")",
")",
"self",
".",
"__set_or_adapt_10320LOC_attributes",
"(",
"location_element",
",",
"weight",
",",
"http_role",
",",
"*",
"*",
"kvpairs",
")",
"# FIXME: If we start adapting the Handle Record by index (instead of",
"# overwriting the entire one), be careful to add and/or overwrite!",
"# (Re-)Add entire 10320 to entry, add entry to list of entries:",
"LOGGER",
".",
"debug",
"(",
"\"__add_URL_to_10320LOC: xmlroot is (2) \"",
"+",
"ET",
".",
"tostring",
"(",
"xmlroot",
",",
"encoding",
"=",
"encoding_value",
")",
")",
"entry",
"[",
"'data'",
"]",
"=",
"ET",
".",
"tostring",
"(",
"xmlroot",
",",
"encoding",
"=",
"encoding_value",
")",
"list_of_entries",
".",
"append",
"(",
"entry",
")"
] |
Add a url to the handle record's "10320/LOC" entry.
If no 10320/LOC entry exists, a new one is created (using the
default "chooseby" attribute, if configured).
If the URL is already present, it is not added again, but
the attributes (e.g. weight) are updated/added.
If the existing 10320/LOC entry is mal-formed, an exception will be
thrown (xml.etree.ElementTree.ParseError)
Note: In the unlikely case that several "10320/LOC" entries exist,
an exception is raised.
:param url: The URL to be added.
:param list_of_entries: A list of the existing entries (to find and
adapt the correct one).
:param weight: Optional. The weight to be set (integer between 0 and
1). If None, no weight attribute is set. If the value is outside
the accepted range, it is set to 1.
:param http_role: Optional. The http_role to be set. This accepts any
string. Currently, Handle System can process 'conneg'. In future,
it may be able to process 'no_conneg' and 'browser'.
:param handle: Optional. Only for the exception message.
:param all others: Optional. All other key-value pairs will be set to
the element. Any value is accepted and transformed to string.
:raise: GenericHandleError: If several 10320/LOC exist (unlikely).
|
[
"Add",
"a",
"url",
"to",
"the",
"handle",
"record",
"s",
"10320",
"/",
"LOC",
"entry",
".",
"If",
"no",
"10320",
"/",
"LOC",
"entry",
"exists",
"a",
"new",
"one",
"is",
"created",
"(",
"using",
"the",
"default",
"chooseby",
"attribute",
"if",
"configured",
")",
".",
"If",
"the",
"URL",
"is",
"already",
"present",
"it",
"is",
"not",
"added",
"again",
"but",
"the",
"attributes",
"(",
"e",
".",
"g",
".",
"weight",
")",
"are",
"updated",
"/",
"added",
".",
"If",
"the",
"existing",
"10320",
"/",
"LOC",
"entry",
"is",
"mal",
"-",
"formed",
"an",
"exception",
"will",
"be",
"thrown",
"(",
"xml",
".",
"etree",
".",
"ElementTree",
".",
"ParseError",
")",
"Note",
":",
"In",
"the",
"unlikely",
"case",
"that",
"several",
"10320",
"/",
"LOC",
"entries",
"exist",
"an",
"exception",
"is",
"raised",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handleclient.py#L1329-L1417
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/handleclient.py
|
EUDATHandleClient.__set_or_adapt_10320LOC_attributes
|
def __set_or_adapt_10320LOC_attributes(self, locelement, weight=None, http_role=None, **kvpairs):
'''
Adds or updates attributes of a <location> element. Existing attributes
are not removed!
:param locelement: A location element as xml snippet
(xml.etree.ElementTree.Element).
:param weight: Optional. The weight to be set (integer between 0 and
1). If None, no weight attribute is set. If the value is outside
the accepted range, it is set to 1.
:param http_role: Optional. The http_role to be set. This accepts any
string. Currently, Handle System can process 'conneg'. In future,
it may be able to process 'no_conneg' and 'browser'.
:param all others: Optional. All other key-value pairs will be set to
the element. Any value is accepted and transformed to string.
'''
if weight is not None:
LOGGER.debug('__set_or_adapt_10320LOC_attributes: weight (' + str(type(weight)) + '): ' + str(weight))
weight = float(weight)
if weight < 0 or weight > 1:
default = 1
LOGGER.debug('__set_or_adapt_10320LOC_attributes: Invalid weight (' + str(weight) + \
'), using default value (' + str(default) + ') instead.')
weight = default
weight = str(weight)
locelement.set('weight', weight)
if http_role is not None:
locelement.set('http_role', http_role)
for key, value in kvpairs.items():
locelement.set(key, str(value))
|
python
|
def __set_or_adapt_10320LOC_attributes(self, locelement, weight=None, http_role=None, **kvpairs):
'''
Adds or updates attributes of a <location> element. Existing attributes
are not removed!
:param locelement: A location element as xml snippet
(xml.etree.ElementTree.Element).
:param weight: Optional. The weight to be set (integer between 0 and
1). If None, no weight attribute is set. If the value is outside
the accepted range, it is set to 1.
:param http_role: Optional. The http_role to be set. This accepts any
string. Currently, Handle System can process 'conneg'. In future,
it may be able to process 'no_conneg' and 'browser'.
:param all others: Optional. All other key-value pairs will be set to
the element. Any value is accepted and transformed to string.
'''
if weight is not None:
LOGGER.debug('__set_or_adapt_10320LOC_attributes: weight (' + str(type(weight)) + '): ' + str(weight))
weight = float(weight)
if weight < 0 or weight > 1:
default = 1
LOGGER.debug('__set_or_adapt_10320LOC_attributes: Invalid weight (' + str(weight) + \
'), using default value (' + str(default) + ') instead.')
weight = default
weight = str(weight)
locelement.set('weight', weight)
if http_role is not None:
locelement.set('http_role', http_role)
for key, value in kvpairs.items():
locelement.set(key, str(value))
|
[
"def",
"__set_or_adapt_10320LOC_attributes",
"(",
"self",
",",
"locelement",
",",
"weight",
"=",
"None",
",",
"http_role",
"=",
"None",
",",
"*",
"*",
"kvpairs",
")",
":",
"if",
"weight",
"is",
"not",
"None",
":",
"LOGGER",
".",
"debug",
"(",
"'__set_or_adapt_10320LOC_attributes: weight ('",
"+",
"str",
"(",
"type",
"(",
"weight",
")",
")",
"+",
"'): '",
"+",
"str",
"(",
"weight",
")",
")",
"weight",
"=",
"float",
"(",
"weight",
")",
"if",
"weight",
"<",
"0",
"or",
"weight",
">",
"1",
":",
"default",
"=",
"1",
"LOGGER",
".",
"debug",
"(",
"'__set_or_adapt_10320LOC_attributes: Invalid weight ('",
"+",
"str",
"(",
"weight",
")",
"+",
"'), using default value ('",
"+",
"str",
"(",
"default",
")",
"+",
"') instead.'",
")",
"weight",
"=",
"default",
"weight",
"=",
"str",
"(",
"weight",
")",
"locelement",
".",
"set",
"(",
"'weight'",
",",
"weight",
")",
"if",
"http_role",
"is",
"not",
"None",
":",
"locelement",
".",
"set",
"(",
"'http_role'",
",",
"http_role",
")",
"for",
"key",
",",
"value",
"in",
"kvpairs",
".",
"items",
"(",
")",
":",
"locelement",
".",
"set",
"(",
"key",
",",
"str",
"(",
"value",
")",
")"
] |
Adds or updates attributes of a <location> element. Existing attributes
are not removed!
:param locelement: A location element as xml snippet
(xml.etree.ElementTree.Element).
:param weight: Optional. The weight to be set (integer between 0 and
1). If None, no weight attribute is set. If the value is outside
the accepted range, it is set to 1.
:param http_role: Optional. The http_role to be set. This accepts any
string. Currently, Handle System can process 'conneg'. In future,
it may be able to process 'no_conneg' and 'browser'.
:param all others: Optional. All other key-value pairs will be set to
the element. Any value is accepted and transformed to string.
|
[
"Adds",
"or",
"updates",
"attributes",
"of",
"a",
"<location",
">",
"element",
".",
"Existing",
"attributes",
"are",
"not",
"removed!"
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handleclient.py#L1419-L1451
|
train
|
nooperpudd/weibopy
|
weibopy/auth.py
|
WeiboOauth2.authorize_url
|
def authorize_url(self):
"""
authorization url
request weibo authorization url
:return:
code string 用于第二步调用oauth2/access_token接口,获取授权后的access token。
state string 如果传递参数,会回传该参数
"""
if self.oauth2_params and self.oauth2_params.get("display") == "mobile":
auth_url = self.mobile_url + "authorize"
else:
auth_url = self.site_url + "authorize"
params = {
'client_id': self.client_id,
'redirect_uri': self.redirect_url,
}
params.update(self.oauth2_params)
params = filter_params(params)
return "{auth_url}?{params}".format(auth_url=auth_url, params=urlencode(params))
|
python
|
def authorize_url(self):
"""
authorization url
request weibo authorization url
:return:
code string 用于第二步调用oauth2/access_token接口,获取授权后的access token。
state string 如果传递参数,会回传该参数
"""
if self.oauth2_params and self.oauth2_params.get("display") == "mobile":
auth_url = self.mobile_url + "authorize"
else:
auth_url = self.site_url + "authorize"
params = {
'client_id': self.client_id,
'redirect_uri': self.redirect_url,
}
params.update(self.oauth2_params)
params = filter_params(params)
return "{auth_url}?{params}".format(auth_url=auth_url, params=urlencode(params))
|
[
"def",
"authorize_url",
"(",
"self",
")",
":",
"if",
"self",
".",
"oauth2_params",
"and",
"self",
".",
"oauth2_params",
".",
"get",
"(",
"\"display\"",
")",
"==",
"\"mobile\"",
":",
"auth_url",
"=",
"self",
".",
"mobile_url",
"+",
"\"authorize\"",
"else",
":",
"auth_url",
"=",
"self",
".",
"site_url",
"+",
"\"authorize\"",
"params",
"=",
"{",
"'client_id'",
":",
"self",
".",
"client_id",
",",
"'redirect_uri'",
":",
"self",
".",
"redirect_url",
",",
"}",
"params",
".",
"update",
"(",
"self",
".",
"oauth2_params",
")",
"params",
"=",
"filter_params",
"(",
"params",
")",
"return",
"\"{auth_url}?{params}\"",
".",
"format",
"(",
"auth_url",
"=",
"auth_url",
",",
"params",
"=",
"urlencode",
"(",
"params",
")",
")"
] |
authorization url
request weibo authorization url
:return:
code string 用于第二步调用oauth2/access_token接口,获取授权后的access token。
state string 如果传递参数,会回传该参数
|
[
"authorization",
"url",
"request",
"weibo",
"authorization",
"url",
":",
"return",
":",
"code",
"string",
"用于第二步调用oauth2",
"/",
"access_token接口,获取授权后的access",
"token。",
"state",
"string",
"如果传递参数,会回传该参数"
] |
61f3fb0502c1f07a591388aaa7526e74c63eaeb1
|
https://github.com/nooperpudd/weibopy/blob/61f3fb0502c1f07a591388aaa7526e74c63eaeb1/weibopy/auth.py#L68-L90
|
train
|
nooperpudd/weibopy
|
weibopy/auth.py
|
WeiboOauth2.request
|
def request(self, method, suffix, data):
"""
:param method: str, http method ["GET","POST","PUT"]
:param suffix: the url suffix
:param data:
:return:
"""
url = self.site_url + suffix
response = self.session.request(method, url, data=data)
if response.status_code == 200:
json_obj = response.json()
if isinstance(json_obj, dict) and json_obj.get("error_code"):
raise WeiboOauth2Error(
json_obj.get("error_code"),
json_obj.get("error"),
json_obj.get('error_description')
)
else:
return json_obj
else:
raise WeiboRequestError(
"Weibo API request error: status code: {code} url:{url} ->"
" method:{method}: data={data}".format(
code=response.status_code,
url=response.url,
method=method,
data=data
)
)
|
python
|
def request(self, method, suffix, data):
"""
:param method: str, http method ["GET","POST","PUT"]
:param suffix: the url suffix
:param data:
:return:
"""
url = self.site_url + suffix
response = self.session.request(method, url, data=data)
if response.status_code == 200:
json_obj = response.json()
if isinstance(json_obj, dict) and json_obj.get("error_code"):
raise WeiboOauth2Error(
json_obj.get("error_code"),
json_obj.get("error"),
json_obj.get('error_description')
)
else:
return json_obj
else:
raise WeiboRequestError(
"Weibo API request error: status code: {code} url:{url} ->"
" method:{method}: data={data}".format(
code=response.status_code,
url=response.url,
method=method,
data=data
)
)
|
[
"def",
"request",
"(",
"self",
",",
"method",
",",
"suffix",
",",
"data",
")",
":",
"url",
"=",
"self",
".",
"site_url",
"+",
"suffix",
"response",
"=",
"self",
".",
"session",
".",
"request",
"(",
"method",
",",
"url",
",",
"data",
"=",
"data",
")",
"if",
"response",
".",
"status_code",
"==",
"200",
":",
"json_obj",
"=",
"response",
".",
"json",
"(",
")",
"if",
"isinstance",
"(",
"json_obj",
",",
"dict",
")",
"and",
"json_obj",
".",
"get",
"(",
"\"error_code\"",
")",
":",
"raise",
"WeiboOauth2Error",
"(",
"json_obj",
".",
"get",
"(",
"\"error_code\"",
")",
",",
"json_obj",
".",
"get",
"(",
"\"error\"",
")",
",",
"json_obj",
".",
"get",
"(",
"'error_description'",
")",
")",
"else",
":",
"return",
"json_obj",
"else",
":",
"raise",
"WeiboRequestError",
"(",
"\"Weibo API request error: status code: {code} url:{url} ->\"",
"\" method:{method}: data={data}\"",
".",
"format",
"(",
"code",
"=",
"response",
".",
"status_code",
",",
"url",
"=",
"response",
".",
"url",
",",
"method",
"=",
"method",
",",
"data",
"=",
"data",
")",
")"
] |
:param method: str, http method ["GET","POST","PUT"]
:param suffix: the url suffix
:param data:
:return:
|
[
":",
"param",
"method",
":",
"str",
"http",
"method",
"[",
"GET",
"POST",
"PUT",
"]",
":",
"param",
"suffix",
":",
"the",
"url",
"suffix",
":",
"param",
"data",
":",
":",
"return",
":"
] |
61f3fb0502c1f07a591388aaa7526e74c63eaeb1
|
https://github.com/nooperpudd/weibopy/blob/61f3fb0502c1f07a591388aaa7526e74c63eaeb1/weibopy/auth.py#L92-L123
|
train
|
nooperpudd/weibopy
|
weibopy/auth.py
|
WeiboOauth2.auth_access
|
def auth_access(self, auth_code):
"""
verify the fist authorization response url code
response data
返回值字段 字段类型 字段说明
access_token string 用户授权的唯一票据,用于调用微博的开放接口,同时也是第三方应用验证微博用户登录的唯一票据,
第三方应用应该用该票据和自己应用内的用户建立唯一影射关系,来识别登录状态,不能使用本返回值里的UID
字段来做登录识别。
expires_in string access_token的生命周期,单位是秒数。
remind_in string access_token的生命周期(该参数即将废弃,开发者请使用expires_in)。
uid string 授权用户的UID,本字段只是为了方便开发者,减少一次user/show接口调用而返回的,第三方应用不能用此字段作为用户
登录状态的识别,只有access_token才是用户授权的唯一票据。
:param auth_code: authorize_url response code
:return:
normal:
{
"access_token": "ACCESS_TOKEN",
"expires_in": 1234,
"remind_in":"798114",
"uid":"12341234"
}
mobile:
{
"access_token": "SlAV32hkKG",
"remind_in": 3600,
"expires_in": 3600
"refresh_token": "QXBK19xm62"
}
"""
data = {
'client_id': self.client_id,
'client_secret': self.client_secret,
'grant_type': 'authorization_code',
'code': auth_code,
'redirect_uri': self.redirect_url
}
return self.request("post", "access_token", data=data)
|
python
|
def auth_access(self, auth_code):
"""
verify the fist authorization response url code
response data
返回值字段 字段类型 字段说明
access_token string 用户授权的唯一票据,用于调用微博的开放接口,同时也是第三方应用验证微博用户登录的唯一票据,
第三方应用应该用该票据和自己应用内的用户建立唯一影射关系,来识别登录状态,不能使用本返回值里的UID
字段来做登录识别。
expires_in string access_token的生命周期,单位是秒数。
remind_in string access_token的生命周期(该参数即将废弃,开发者请使用expires_in)。
uid string 授权用户的UID,本字段只是为了方便开发者,减少一次user/show接口调用而返回的,第三方应用不能用此字段作为用户
登录状态的识别,只有access_token才是用户授权的唯一票据。
:param auth_code: authorize_url response code
:return:
normal:
{
"access_token": "ACCESS_TOKEN",
"expires_in": 1234,
"remind_in":"798114",
"uid":"12341234"
}
mobile:
{
"access_token": "SlAV32hkKG",
"remind_in": 3600,
"expires_in": 3600
"refresh_token": "QXBK19xm62"
}
"""
data = {
'client_id': self.client_id,
'client_secret': self.client_secret,
'grant_type': 'authorization_code',
'code': auth_code,
'redirect_uri': self.redirect_url
}
return self.request("post", "access_token", data=data)
|
[
"def",
"auth_access",
"(",
"self",
",",
"auth_code",
")",
":",
"data",
"=",
"{",
"'client_id'",
":",
"self",
".",
"client_id",
",",
"'client_secret'",
":",
"self",
".",
"client_secret",
",",
"'grant_type'",
":",
"'authorization_code'",
",",
"'code'",
":",
"auth_code",
",",
"'redirect_uri'",
":",
"self",
".",
"redirect_url",
"}",
"return",
"self",
".",
"request",
"(",
"\"post\"",
",",
"\"access_token\"",
",",
"data",
"=",
"data",
")"
] |
verify the fist authorization response url code
response data
返回值字段 字段类型 字段说明
access_token string 用户授权的唯一票据,用于调用微博的开放接口,同时也是第三方应用验证微博用户登录的唯一票据,
第三方应用应该用该票据和自己应用内的用户建立唯一影射关系,来识别登录状态,不能使用本返回值里的UID
字段来做登录识别。
expires_in string access_token的生命周期,单位是秒数。
remind_in string access_token的生命周期(该参数即将废弃,开发者请使用expires_in)。
uid string 授权用户的UID,本字段只是为了方便开发者,减少一次user/show接口调用而返回的,第三方应用不能用此字段作为用户
登录状态的识别,只有access_token才是用户授权的唯一票据。
:param auth_code: authorize_url response code
:return:
normal:
{
"access_token": "ACCESS_TOKEN",
"expires_in": 1234,
"remind_in":"798114",
"uid":"12341234"
}
mobile:
{
"access_token": "SlAV32hkKG",
"remind_in": 3600,
"expires_in": 3600
"refresh_token": "QXBK19xm62"
}
|
[
"verify",
"the",
"fist",
"authorization",
"response",
"url",
"code"
] |
61f3fb0502c1f07a591388aaa7526e74c63eaeb1
|
https://github.com/nooperpudd/weibopy/blob/61f3fb0502c1f07a591388aaa7526e74c63eaeb1/weibopy/auth.py#L125-L166
|
train
|
nooperpudd/weibopy
|
weibopy/auth.py
|
WeiboOauth2.revoke_auth_access
|
def revoke_auth_access(self, access_token):
"""
授权回收接口,帮助开发者主动取消用户的授权。
应用下线时,清空所有用户的授权
应用新上线了功能,需要取得用户scope权限,可以回收后重新引导用户授权
开发者调试应用,需要反复调试授权功能
应用内实现类似登出微博帐号的功能
并传递给你以下参数,source:应用appkey,uid :取消授权的用户,auth_end :取消授权的时间
:param access_token:
:return: bool
"""
result = self.request("post", "revokeoauth2", data={"access_token": access_token})
return bool(result.get("result"))
|
python
|
def revoke_auth_access(self, access_token):
"""
授权回收接口,帮助开发者主动取消用户的授权。
应用下线时,清空所有用户的授权
应用新上线了功能,需要取得用户scope权限,可以回收后重新引导用户授权
开发者调试应用,需要反复调试授权功能
应用内实现类似登出微博帐号的功能
并传递给你以下参数,source:应用appkey,uid :取消授权的用户,auth_end :取消授权的时间
:param access_token:
:return: bool
"""
result = self.request("post", "revokeoauth2", data={"access_token": access_token})
return bool(result.get("result"))
|
[
"def",
"revoke_auth_access",
"(",
"self",
",",
"access_token",
")",
":",
"result",
"=",
"self",
".",
"request",
"(",
"\"post\"",
",",
"\"revokeoauth2\"",
",",
"data",
"=",
"{",
"\"access_token\"",
":",
"access_token",
"}",
")",
"return",
"bool",
"(",
"result",
".",
"get",
"(",
"\"result\"",
")",
")"
] |
授权回收接口,帮助开发者主动取消用户的授权。
应用下线时,清空所有用户的授权
应用新上线了功能,需要取得用户scope权限,可以回收后重新引导用户授权
开发者调试应用,需要反复调试授权功能
应用内实现类似登出微博帐号的功能
并传递给你以下参数,source:应用appkey,uid :取消授权的用户,auth_end :取消授权的时间
:param access_token:
:return: bool
|
[
"授权回收接口,帮助开发者主动取消用户的授权。"
] |
61f3fb0502c1f07a591388aaa7526e74c63eaeb1
|
https://github.com/nooperpudd/weibopy/blob/61f3fb0502c1f07a591388aaa7526e74c63eaeb1/weibopy/auth.py#L168-L183
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/handlesystemconnector.py
|
HandleSystemConnector.__set_basic_auth_string
|
def __set_basic_auth_string(self, username, password):
'''
Creates and sets the authentication string for (write-)accessing the
Handle Server. No return, the string is set as an attribute to
the client instance.
:param username: Username handle with index: index:prefix/suffix.
:param password: The password contained in the index of the username
handle.
'''
auth = b2handle.utilhandle.create_authentication_string(username, password)
self.__basic_authentication_string = auth
|
python
|
def __set_basic_auth_string(self, username, password):
'''
Creates and sets the authentication string for (write-)accessing the
Handle Server. No return, the string is set as an attribute to
the client instance.
:param username: Username handle with index: index:prefix/suffix.
:param password: The password contained in the index of the username
handle.
'''
auth = b2handle.utilhandle.create_authentication_string(username, password)
self.__basic_authentication_string = auth
|
[
"def",
"__set_basic_auth_string",
"(",
"self",
",",
"username",
",",
"password",
")",
":",
"auth",
"=",
"b2handle",
".",
"utilhandle",
".",
"create_authentication_string",
"(",
"username",
",",
"password",
")",
"self",
".",
"__basic_authentication_string",
"=",
"auth"
] |
Creates and sets the authentication string for (write-)accessing the
Handle Server. No return, the string is set as an attribute to
the client instance.
:param username: Username handle with index: index:prefix/suffix.
:param password: The password contained in the index of the username
handle.
|
[
"Creates",
"and",
"sets",
"the",
"authentication",
"string",
"for",
"(",
"write",
"-",
")",
"accessing",
"the",
"Handle",
"Server",
".",
"No",
"return",
"the",
"string",
"is",
"set",
"as",
"an",
"attribute",
"to",
"the",
"client",
"instance",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handlesystemconnector.py#L236-L247
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/handlesystemconnector.py
|
HandleSystemConnector.send_handle_get_request
|
def send_handle_get_request(self, handle, indices=None):
'''
Send a HTTP GET request to the handle server to read either an entire
handle or to some specified values from a handle record, using the
requests module.
:param handle: The handle.
:param indices: Optional. A list of indices to delete. Defaults to
None (i.e. the entire handle is deleted.). The list can contain
integers or strings.
:return: The server's response.
'''
# Assemble required info:
url = self.make_handle_URL(handle, indices)
LOGGER.debug('GET Request to '+url)
head = self.__get_headers('GET')
veri = self.__HTTPS_verify
# Send the request
if self.__cert_needed_for_get_request():
# If this is the first request and the connector uses client cert authentication, we need to send the cert along
# in the first request that builds the session.
resp = self.__session.get(url, headers=head, verify=veri, cert=self.__cert_object)
else:
# Normal case:
resp = self.__session.get(url, headers=head, verify=veri)
# Log and return
self.__log_request_response_to_file(
logger=REQUESTLOGGER,
op='GET',
handle=handle,
url=url,
headers=head,
verify=veri,
resp=resp
)
self.__first_request = False
return resp
|
python
|
def send_handle_get_request(self, handle, indices=None):
'''
Send a HTTP GET request to the handle server to read either an entire
handle or to some specified values from a handle record, using the
requests module.
:param handle: The handle.
:param indices: Optional. A list of indices to delete. Defaults to
None (i.e. the entire handle is deleted.). The list can contain
integers or strings.
:return: The server's response.
'''
# Assemble required info:
url = self.make_handle_URL(handle, indices)
LOGGER.debug('GET Request to '+url)
head = self.__get_headers('GET')
veri = self.__HTTPS_verify
# Send the request
if self.__cert_needed_for_get_request():
# If this is the first request and the connector uses client cert authentication, we need to send the cert along
# in the first request that builds the session.
resp = self.__session.get(url, headers=head, verify=veri, cert=self.__cert_object)
else:
# Normal case:
resp = self.__session.get(url, headers=head, verify=veri)
# Log and return
self.__log_request_response_to_file(
logger=REQUESTLOGGER,
op='GET',
handle=handle,
url=url,
headers=head,
verify=veri,
resp=resp
)
self.__first_request = False
return resp
|
[
"def",
"send_handle_get_request",
"(",
"self",
",",
"handle",
",",
"indices",
"=",
"None",
")",
":",
"# Assemble required info:",
"url",
"=",
"self",
".",
"make_handle_URL",
"(",
"handle",
",",
"indices",
")",
"LOGGER",
".",
"debug",
"(",
"'GET Request to '",
"+",
"url",
")",
"head",
"=",
"self",
".",
"__get_headers",
"(",
"'GET'",
")",
"veri",
"=",
"self",
".",
"__HTTPS_verify",
"# Send the request",
"if",
"self",
".",
"__cert_needed_for_get_request",
"(",
")",
":",
"# If this is the first request and the connector uses client cert authentication, we need to send the cert along",
"# in the first request that builds the session.",
"resp",
"=",
"self",
".",
"__session",
".",
"get",
"(",
"url",
",",
"headers",
"=",
"head",
",",
"verify",
"=",
"veri",
",",
"cert",
"=",
"self",
".",
"__cert_object",
")",
"else",
":",
"# Normal case:",
"resp",
"=",
"self",
".",
"__session",
".",
"get",
"(",
"url",
",",
"headers",
"=",
"head",
",",
"verify",
"=",
"veri",
")",
"# Log and return",
"self",
".",
"__log_request_response_to_file",
"(",
"logger",
"=",
"REQUESTLOGGER",
",",
"op",
"=",
"'GET'",
",",
"handle",
"=",
"handle",
",",
"url",
"=",
"url",
",",
"headers",
"=",
"head",
",",
"verify",
"=",
"veri",
",",
"resp",
"=",
"resp",
")",
"self",
".",
"__first_request",
"=",
"False",
"return",
"resp"
] |
Send a HTTP GET request to the handle server to read either an entire
handle or to some specified values from a handle record, using the
requests module.
:param handle: The handle.
:param indices: Optional. A list of indices to delete. Defaults to
None (i.e. the entire handle is deleted.). The list can contain
integers or strings.
:return: The server's response.
|
[
"Send",
"a",
"HTTP",
"GET",
"request",
"to",
"the",
"handle",
"server",
"to",
"read",
"either",
"an",
"entire",
"handle",
"or",
"to",
"some",
"specified",
"values",
"from",
"a",
"handle",
"record",
"using",
"the",
"requests",
"module",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handlesystemconnector.py#L252-L292
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/handlesystemconnector.py
|
HandleSystemConnector.send_handle_put_request
|
def send_handle_put_request(self, **args):
'''
Send a HTTP PUT request to the handle server to write either an entire
handle or to some specified values to an handle record, using the
requests module.
:param handle: The handle.
:param list_of_entries: A list of handle record entries to be written,
in the format [{"index":xyz, "type":"xyz", "data":"xyz"}] or similar.
:param indices: Optional. A list of indices to delete. Defaults
to None (i.e. the entire handle is deleted.). The list can
contain integers or strings.
:param overwrite: Optional. Whether the handle should be overwritten
if it exists already.
:return: The server's response.
'''
# Check if we have write access at all:
if not self.__has_write_access:
raise HandleAuthenticationError(msg=self.__no_auth_message)
# Check args:
mandatory_args = ['handle', 'list_of_entries']
optional_args = ['indices', 'op', 'overwrite']
b2handle.util.add_missing_optional_args_with_value_none(args, optional_args)
b2handle.util.check_presence_of_mandatory_args(args, mandatory_args)
handle = args['handle']
list_of_entries = args['list_of_entries']
indices = args['indices']
op = args['op']
overwrite = args['overwrite'] or False
# Make necessary values:
url = self.make_handle_URL(handle, indices, overwrite=overwrite)
LOGGER.debug('PUT Request to '+url)
payload = json.dumps({'values':list_of_entries})
LOGGER.debug('PUT Request payload: '+payload)
head = self.__get_headers('PUT')
LOGGER.debug('PUT Request headers: '+str(head))
veri = self.__HTTPS_verify
# Send request to server:
resp = self.__send_put_request_to_server(url, payload, head, veri, handle)
if b2handle.hsresponses.is_redirect_from_http_to_https(resp):
resp = self.__resend_put_request_on_302(payload, head, veri, handle, resp)
# Check response for authentication issues:
if b2handle.hsresponses.not_authenticated(resp):
raise HandleAuthenticationError(
operation=op,
handle=handle,
response=resp,
username=self.__username
)
self.__first_request = False
return resp, payload
|
python
|
def send_handle_put_request(self, **args):
'''
Send a HTTP PUT request to the handle server to write either an entire
handle or to some specified values to an handle record, using the
requests module.
:param handle: The handle.
:param list_of_entries: A list of handle record entries to be written,
in the format [{"index":xyz, "type":"xyz", "data":"xyz"}] or similar.
:param indices: Optional. A list of indices to delete. Defaults
to None (i.e. the entire handle is deleted.). The list can
contain integers or strings.
:param overwrite: Optional. Whether the handle should be overwritten
if it exists already.
:return: The server's response.
'''
# Check if we have write access at all:
if not self.__has_write_access:
raise HandleAuthenticationError(msg=self.__no_auth_message)
# Check args:
mandatory_args = ['handle', 'list_of_entries']
optional_args = ['indices', 'op', 'overwrite']
b2handle.util.add_missing_optional_args_with_value_none(args, optional_args)
b2handle.util.check_presence_of_mandatory_args(args, mandatory_args)
handle = args['handle']
list_of_entries = args['list_of_entries']
indices = args['indices']
op = args['op']
overwrite = args['overwrite'] or False
# Make necessary values:
url = self.make_handle_URL(handle, indices, overwrite=overwrite)
LOGGER.debug('PUT Request to '+url)
payload = json.dumps({'values':list_of_entries})
LOGGER.debug('PUT Request payload: '+payload)
head = self.__get_headers('PUT')
LOGGER.debug('PUT Request headers: '+str(head))
veri = self.__HTTPS_verify
# Send request to server:
resp = self.__send_put_request_to_server(url, payload, head, veri, handle)
if b2handle.hsresponses.is_redirect_from_http_to_https(resp):
resp = self.__resend_put_request_on_302(payload, head, veri, handle, resp)
# Check response for authentication issues:
if b2handle.hsresponses.not_authenticated(resp):
raise HandleAuthenticationError(
operation=op,
handle=handle,
response=resp,
username=self.__username
)
self.__first_request = False
return resp, payload
|
[
"def",
"send_handle_put_request",
"(",
"self",
",",
"*",
"*",
"args",
")",
":",
"# Check if we have write access at all:",
"if",
"not",
"self",
".",
"__has_write_access",
":",
"raise",
"HandleAuthenticationError",
"(",
"msg",
"=",
"self",
".",
"__no_auth_message",
")",
"# Check args:",
"mandatory_args",
"=",
"[",
"'handle'",
",",
"'list_of_entries'",
"]",
"optional_args",
"=",
"[",
"'indices'",
",",
"'op'",
",",
"'overwrite'",
"]",
"b2handle",
".",
"util",
".",
"add_missing_optional_args_with_value_none",
"(",
"args",
",",
"optional_args",
")",
"b2handle",
".",
"util",
".",
"check_presence_of_mandatory_args",
"(",
"args",
",",
"mandatory_args",
")",
"handle",
"=",
"args",
"[",
"'handle'",
"]",
"list_of_entries",
"=",
"args",
"[",
"'list_of_entries'",
"]",
"indices",
"=",
"args",
"[",
"'indices'",
"]",
"op",
"=",
"args",
"[",
"'op'",
"]",
"overwrite",
"=",
"args",
"[",
"'overwrite'",
"]",
"or",
"False",
"# Make necessary values:",
"url",
"=",
"self",
".",
"make_handle_URL",
"(",
"handle",
",",
"indices",
",",
"overwrite",
"=",
"overwrite",
")",
"LOGGER",
".",
"debug",
"(",
"'PUT Request to '",
"+",
"url",
")",
"payload",
"=",
"json",
".",
"dumps",
"(",
"{",
"'values'",
":",
"list_of_entries",
"}",
")",
"LOGGER",
".",
"debug",
"(",
"'PUT Request payload: '",
"+",
"payload",
")",
"head",
"=",
"self",
".",
"__get_headers",
"(",
"'PUT'",
")",
"LOGGER",
".",
"debug",
"(",
"'PUT Request headers: '",
"+",
"str",
"(",
"head",
")",
")",
"veri",
"=",
"self",
".",
"__HTTPS_verify",
"# Send request to server:",
"resp",
"=",
"self",
".",
"__send_put_request_to_server",
"(",
"url",
",",
"payload",
",",
"head",
",",
"veri",
",",
"handle",
")",
"if",
"b2handle",
".",
"hsresponses",
".",
"is_redirect_from_http_to_https",
"(",
"resp",
")",
":",
"resp",
"=",
"self",
".",
"__resend_put_request_on_302",
"(",
"payload",
",",
"head",
",",
"veri",
",",
"handle",
",",
"resp",
")",
"# Check response for authentication issues:",
"if",
"b2handle",
".",
"hsresponses",
".",
"not_authenticated",
"(",
"resp",
")",
":",
"raise",
"HandleAuthenticationError",
"(",
"operation",
"=",
"op",
",",
"handle",
"=",
"handle",
",",
"response",
"=",
"resp",
",",
"username",
"=",
"self",
".",
"__username",
")",
"self",
".",
"__first_request",
"=",
"False",
"return",
"resp",
",",
"payload"
] |
Send a HTTP PUT request to the handle server to write either an entire
handle or to some specified values to an handle record, using the
requests module.
:param handle: The handle.
:param list_of_entries: A list of handle record entries to be written,
in the format [{"index":xyz, "type":"xyz", "data":"xyz"}] or similar.
:param indices: Optional. A list of indices to delete. Defaults
to None (i.e. the entire handle is deleted.). The list can
contain integers or strings.
:param overwrite: Optional. Whether the handle should be overwritten
if it exists already.
:return: The server's response.
|
[
"Send",
"a",
"HTTP",
"PUT",
"request",
"to",
"the",
"handle",
"server",
"to",
"write",
"either",
"an",
"entire",
"handle",
"or",
"to",
"some",
"specified",
"values",
"to",
"an",
"handle",
"record",
"using",
"the",
"requests",
"module",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handlesystemconnector.py#L301-L356
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/handlesystemconnector.py
|
HandleSystemConnector.send_handle_delete_request
|
def send_handle_delete_request(self, **args):
'''
Send a HTTP DELETE request to the handle server to delete either an
entire handle or to some specified values from a handle record,
using the requests module.
:param handle: The handle.
:param indices: Optional. A list of indices to delete. Defaults to
None (i.e. the entire handle is deleted.). The list can contain
integers or strings.
:return: The server's response.
'''
# Check if we have write access at all:
if not self.__has_write_access:
raise HandleAuthenticationError(msg=self.__no_auth_message)
# Check args:
mandatory_args = ['handle']
optional_args = ['indices', 'op']
b2handle.util.add_missing_optional_args_with_value_none(args, optional_args)
b2handle.util.check_presence_of_mandatory_args(args, mandatory_args)
handle = args['handle']
indices = args['indices']
op = args['op']
# Make necessary values:
url = self.make_handle_URL(handle, indices)
if indices is not None and len(indices) > 0:
LOGGER.debug('__send_handle_delete_request: Deleting values '+str(indices)+' from handle '+handle+'.')
else:
LOGGER.debug('__send_handle_delete_request: Deleting handle '+handle+'.')
LOGGER.debug('DELETE Request to '+url)
head = self.__get_headers('DELETE')
veri = self.__HTTPS_verify
# Make request:
resp = None
if self.__authentication_method == self.__auth_methods['user_pw']:
resp = self.__session.delete(url, headers=head, verify=veri)
elif self.__authentication_method == self.__auth_methods['cert']:
resp = self.__session.delete(url, headers=head, verify=veri, cert=self.__cert_object)
self.__log_request_response_to_file(
logger=REQUESTLOGGER,
op='DELETE',
handle=handle,
url=url,
headers=head,
verify=veri,
resp=resp
)
# Check response for authentication issues:
if b2handle.hsresponses.not_authenticated(resp):
raise HandleAuthenticationError(
operation=op,
handle=handle,
response=resp,
username=self.__username
)
self.__first_request = False
return resp
|
python
|
def send_handle_delete_request(self, **args):
'''
Send a HTTP DELETE request to the handle server to delete either an
entire handle or to some specified values from a handle record,
using the requests module.
:param handle: The handle.
:param indices: Optional. A list of indices to delete. Defaults to
None (i.e. the entire handle is deleted.). The list can contain
integers or strings.
:return: The server's response.
'''
# Check if we have write access at all:
if not self.__has_write_access:
raise HandleAuthenticationError(msg=self.__no_auth_message)
# Check args:
mandatory_args = ['handle']
optional_args = ['indices', 'op']
b2handle.util.add_missing_optional_args_with_value_none(args, optional_args)
b2handle.util.check_presence_of_mandatory_args(args, mandatory_args)
handle = args['handle']
indices = args['indices']
op = args['op']
# Make necessary values:
url = self.make_handle_URL(handle, indices)
if indices is not None and len(indices) > 0:
LOGGER.debug('__send_handle_delete_request: Deleting values '+str(indices)+' from handle '+handle+'.')
else:
LOGGER.debug('__send_handle_delete_request: Deleting handle '+handle+'.')
LOGGER.debug('DELETE Request to '+url)
head = self.__get_headers('DELETE')
veri = self.__HTTPS_verify
# Make request:
resp = None
if self.__authentication_method == self.__auth_methods['user_pw']:
resp = self.__session.delete(url, headers=head, verify=veri)
elif self.__authentication_method == self.__auth_methods['cert']:
resp = self.__session.delete(url, headers=head, verify=veri, cert=self.__cert_object)
self.__log_request_response_to_file(
logger=REQUESTLOGGER,
op='DELETE',
handle=handle,
url=url,
headers=head,
verify=veri,
resp=resp
)
# Check response for authentication issues:
if b2handle.hsresponses.not_authenticated(resp):
raise HandleAuthenticationError(
operation=op,
handle=handle,
response=resp,
username=self.__username
)
self.__first_request = False
return resp
|
[
"def",
"send_handle_delete_request",
"(",
"self",
",",
"*",
"*",
"args",
")",
":",
"# Check if we have write access at all:",
"if",
"not",
"self",
".",
"__has_write_access",
":",
"raise",
"HandleAuthenticationError",
"(",
"msg",
"=",
"self",
".",
"__no_auth_message",
")",
"# Check args:",
"mandatory_args",
"=",
"[",
"'handle'",
"]",
"optional_args",
"=",
"[",
"'indices'",
",",
"'op'",
"]",
"b2handle",
".",
"util",
".",
"add_missing_optional_args_with_value_none",
"(",
"args",
",",
"optional_args",
")",
"b2handle",
".",
"util",
".",
"check_presence_of_mandatory_args",
"(",
"args",
",",
"mandatory_args",
")",
"handle",
"=",
"args",
"[",
"'handle'",
"]",
"indices",
"=",
"args",
"[",
"'indices'",
"]",
"op",
"=",
"args",
"[",
"'op'",
"]",
"# Make necessary values:",
"url",
"=",
"self",
".",
"make_handle_URL",
"(",
"handle",
",",
"indices",
")",
"if",
"indices",
"is",
"not",
"None",
"and",
"len",
"(",
"indices",
")",
">",
"0",
":",
"LOGGER",
".",
"debug",
"(",
"'__send_handle_delete_request: Deleting values '",
"+",
"str",
"(",
"indices",
")",
"+",
"' from handle '",
"+",
"handle",
"+",
"'.'",
")",
"else",
":",
"LOGGER",
".",
"debug",
"(",
"'__send_handle_delete_request: Deleting handle '",
"+",
"handle",
"+",
"'.'",
")",
"LOGGER",
".",
"debug",
"(",
"'DELETE Request to '",
"+",
"url",
")",
"head",
"=",
"self",
".",
"__get_headers",
"(",
"'DELETE'",
")",
"veri",
"=",
"self",
".",
"__HTTPS_verify",
"# Make request:",
"resp",
"=",
"None",
"if",
"self",
".",
"__authentication_method",
"==",
"self",
".",
"__auth_methods",
"[",
"'user_pw'",
"]",
":",
"resp",
"=",
"self",
".",
"__session",
".",
"delete",
"(",
"url",
",",
"headers",
"=",
"head",
",",
"verify",
"=",
"veri",
")",
"elif",
"self",
".",
"__authentication_method",
"==",
"self",
".",
"__auth_methods",
"[",
"'cert'",
"]",
":",
"resp",
"=",
"self",
".",
"__session",
".",
"delete",
"(",
"url",
",",
"headers",
"=",
"head",
",",
"verify",
"=",
"veri",
",",
"cert",
"=",
"self",
".",
"__cert_object",
")",
"self",
".",
"__log_request_response_to_file",
"(",
"logger",
"=",
"REQUESTLOGGER",
",",
"op",
"=",
"'DELETE'",
",",
"handle",
"=",
"handle",
",",
"url",
"=",
"url",
",",
"headers",
"=",
"head",
",",
"verify",
"=",
"veri",
",",
"resp",
"=",
"resp",
")",
"# Check response for authentication issues:",
"if",
"b2handle",
".",
"hsresponses",
".",
"not_authenticated",
"(",
"resp",
")",
":",
"raise",
"HandleAuthenticationError",
"(",
"operation",
"=",
"op",
",",
"handle",
"=",
"handle",
",",
"response",
"=",
"resp",
",",
"username",
"=",
"self",
".",
"__username",
")",
"self",
".",
"__first_request",
"=",
"False",
"return",
"resp"
] |
Send a HTTP DELETE request to the handle server to delete either an
entire handle or to some specified values from a handle record,
using the requests module.
:param handle: The handle.
:param indices: Optional. A list of indices to delete. Defaults to
None (i.e. the entire handle is deleted.). The list can contain
integers or strings.
:return: The server's response.
|
[
"Send",
"a",
"HTTP",
"DELETE",
"request",
"to",
"the",
"handle",
"server",
"to",
"delete",
"either",
"an",
"entire",
"handle",
"or",
"to",
"some",
"specified",
"values",
"from",
"a",
"handle",
"record",
"using",
"the",
"requests",
"module",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handlesystemconnector.py#L384-L445
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/handlesystemconnector.py
|
HandleSystemConnector.check_if_username_exists
|
def check_if_username_exists(self, username):
'''
Check if the username handles exists.
:param username: The username, in the form index:prefix/suffix
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
:raises: :exc:`~b2handle.handleexceptions.GenericHandleError`
:return: True. If it does not exist, an exception is raised.
*Note:* Only the existence of the handle is verified. The existence or
validity of the index is not checked, because entries containing
a key are hidden anyway.
'''
LOGGER.debug('check_if_username_exists...')
_, handle = b2handle.utilhandle.remove_index_from_handle(username)
resp = self.send_handle_get_request(handle)
resp_content = decoded_response(resp)
if b2handle.hsresponses.does_handle_exist(resp):
handlerecord_json = json.loads(resp_content)
if not handlerecord_json['handle'] == handle:
raise GenericHandleError(
operation='Checking if username exists',
handle=handle,
reponse=resp,
msg='The check returned a different handle than was asked for.'
)
return True
elif b2handle.hsresponses.handle_not_found(resp):
msg = 'The username handle does not exist'
raise HandleNotFoundException(handle=handle, msg=msg, response=resp)
else:
op = 'checking if handle exists'
msg = 'Checking if username exists went wrong'
raise GenericHandleError(operation=op, handle=handle, response=resp, msg=msg)
|
python
|
def check_if_username_exists(self, username):
'''
Check if the username handles exists.
:param username: The username, in the form index:prefix/suffix
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
:raises: :exc:`~b2handle.handleexceptions.GenericHandleError`
:return: True. If it does not exist, an exception is raised.
*Note:* Only the existence of the handle is verified. The existence or
validity of the index is not checked, because entries containing
a key are hidden anyway.
'''
LOGGER.debug('check_if_username_exists...')
_, handle = b2handle.utilhandle.remove_index_from_handle(username)
resp = self.send_handle_get_request(handle)
resp_content = decoded_response(resp)
if b2handle.hsresponses.does_handle_exist(resp):
handlerecord_json = json.loads(resp_content)
if not handlerecord_json['handle'] == handle:
raise GenericHandleError(
operation='Checking if username exists',
handle=handle,
reponse=resp,
msg='The check returned a different handle than was asked for.'
)
return True
elif b2handle.hsresponses.handle_not_found(resp):
msg = 'The username handle does not exist'
raise HandleNotFoundException(handle=handle, msg=msg, response=resp)
else:
op = 'checking if handle exists'
msg = 'Checking if username exists went wrong'
raise GenericHandleError(operation=op, handle=handle, response=resp, msg=msg)
|
[
"def",
"check_if_username_exists",
"(",
"self",
",",
"username",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'check_if_username_exists...'",
")",
"_",
",",
"handle",
"=",
"b2handle",
".",
"utilhandle",
".",
"remove_index_from_handle",
"(",
"username",
")",
"resp",
"=",
"self",
".",
"send_handle_get_request",
"(",
"handle",
")",
"resp_content",
"=",
"decoded_response",
"(",
"resp",
")",
"if",
"b2handle",
".",
"hsresponses",
".",
"does_handle_exist",
"(",
"resp",
")",
":",
"handlerecord_json",
"=",
"json",
".",
"loads",
"(",
"resp_content",
")",
"if",
"not",
"handlerecord_json",
"[",
"'handle'",
"]",
"==",
"handle",
":",
"raise",
"GenericHandleError",
"(",
"operation",
"=",
"'Checking if username exists'",
",",
"handle",
"=",
"handle",
",",
"reponse",
"=",
"resp",
",",
"msg",
"=",
"'The check returned a different handle than was asked for.'",
")",
"return",
"True",
"elif",
"b2handle",
".",
"hsresponses",
".",
"handle_not_found",
"(",
"resp",
")",
":",
"msg",
"=",
"'The username handle does not exist'",
"raise",
"HandleNotFoundException",
"(",
"handle",
"=",
"handle",
",",
"msg",
"=",
"msg",
",",
"response",
"=",
"resp",
")",
"else",
":",
"op",
"=",
"'checking if handle exists'",
"msg",
"=",
"'Checking if username exists went wrong'",
"raise",
"GenericHandleError",
"(",
"operation",
"=",
"op",
",",
"handle",
"=",
"handle",
",",
"response",
"=",
"resp",
",",
"msg",
"=",
"msg",
")"
] |
Check if the username handles exists.
:param username: The username, in the form index:prefix/suffix
:raises: :exc:`~b2handle.handleexceptions.HandleNotFoundException`
:raises: :exc:`~b2handle.handleexceptions.GenericHandleError`
:return: True. If it does not exist, an exception is raised.
*Note:* Only the existence of the handle is verified. The existence or
validity of the index is not checked, because entries containing
a key are hidden anyway.
|
[
"Check",
"if",
"the",
"username",
"handles",
"exists",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handlesystemconnector.py#L447-L482
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/handlesystemconnector.py
|
HandleSystemConnector.__get_headers
|
def __get_headers(self, action):
'''
Create HTTP headers for different HTTP requests. Content-type and
Accept are 'application/json', as the library is interacting with
a REST API.
:param action: Action for which to create the header ('GET', 'PUT',
'DELETE', 'SEARCH').
:return: dict containing key-value pairs, e.g. 'Accept',
'Content-Type', etc. (depening on the action).
'''
header = {}
accept = 'application/json'
content_type = 'application/json'
if action is 'GET':
header['Accept'] = accept
elif action is 'PUT' or action is 'DELETE':
if self.__authentication_method == self.__auth_methods['cert']:
header['Authorization'] = 'Handle clientCert="true"'
elif self.__authentication_method == self.__auth_methods['user_pw']:
header['Authorization'] = 'Basic ' + self.__basic_authentication_string
if action is 'PUT':
header['Content-Type'] = content_type
else:
LOGGER.debug('__getHeader: ACTION is unknown ('+action+')')
return header
|
python
|
def __get_headers(self, action):
'''
Create HTTP headers for different HTTP requests. Content-type and
Accept are 'application/json', as the library is interacting with
a REST API.
:param action: Action for which to create the header ('GET', 'PUT',
'DELETE', 'SEARCH').
:return: dict containing key-value pairs, e.g. 'Accept',
'Content-Type', etc. (depening on the action).
'''
header = {}
accept = 'application/json'
content_type = 'application/json'
if action is 'GET':
header['Accept'] = accept
elif action is 'PUT' or action is 'DELETE':
if self.__authentication_method == self.__auth_methods['cert']:
header['Authorization'] = 'Handle clientCert="true"'
elif self.__authentication_method == self.__auth_methods['user_pw']:
header['Authorization'] = 'Basic ' + self.__basic_authentication_string
if action is 'PUT':
header['Content-Type'] = content_type
else:
LOGGER.debug('__getHeader: ACTION is unknown ('+action+')')
return header
|
[
"def",
"__get_headers",
"(",
"self",
",",
"action",
")",
":",
"header",
"=",
"{",
"}",
"accept",
"=",
"'application/json'",
"content_type",
"=",
"'application/json'",
"if",
"action",
"is",
"'GET'",
":",
"header",
"[",
"'Accept'",
"]",
"=",
"accept",
"elif",
"action",
"is",
"'PUT'",
"or",
"action",
"is",
"'DELETE'",
":",
"if",
"self",
".",
"__authentication_method",
"==",
"self",
".",
"__auth_methods",
"[",
"'cert'",
"]",
":",
"header",
"[",
"'Authorization'",
"]",
"=",
"'Handle clientCert=\"true\"'",
"elif",
"self",
".",
"__authentication_method",
"==",
"self",
".",
"__auth_methods",
"[",
"'user_pw'",
"]",
":",
"header",
"[",
"'Authorization'",
"]",
"=",
"'Basic '",
"+",
"self",
".",
"__basic_authentication_string",
"if",
"action",
"is",
"'PUT'",
":",
"header",
"[",
"'Content-Type'",
"]",
"=",
"content_type",
"else",
":",
"LOGGER",
".",
"debug",
"(",
"'__getHeader: ACTION is unknown ('",
"+",
"action",
"+",
"')'",
")",
"return",
"header"
] |
Create HTTP headers for different HTTP requests. Content-type and
Accept are 'application/json', as the library is interacting with
a REST API.
:param action: Action for which to create the header ('GET', 'PUT',
'DELETE', 'SEARCH').
:return: dict containing key-value pairs, e.g. 'Accept',
'Content-Type', etc. (depening on the action).
|
[
"Create",
"HTTP",
"headers",
"for",
"different",
"HTTP",
"requests",
".",
"Content",
"-",
"type",
"and",
"Accept",
"are",
"application",
"/",
"json",
"as",
"the",
"library",
"is",
"interacting",
"with",
"a",
"REST",
"API",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handlesystemconnector.py#L484-L517
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/handlesystemconnector.py
|
HandleSystemConnector.make_handle_URL
|
def make_handle_URL(self, handle, indices=None, overwrite=None, other_url=None):
'''
Create the URL for a HTTP request (URL + query string) to request
a specific handle from the Handle Server.
:param handle: The handle to access.
:param indices: Optional. A list of integers or strings. Indices of
the handle record entries to read or write. Defaults to None.
:param overwrite: Optional. If set, an overwrite flag will be appended
to the URL ({?,&}overwrite=true or {?,&}overwrite=false). If not set, no
flag is set, thus the Handle Server's default behaviour will be
used. Defaults to None.
:param other_url: Optional. If a different Handle Server URL than the
one specified in the constructor should be used. Defaults to None.
If set, it should be set including the URL extension,
e.g. '/api/handles/'.
:return: The complete URL, e.g.
'http://some.handle.server/api/handles/prefix/suffix?index=2&index=6&overwrite=false
'''
LOGGER.debug('make_handle_URL...')
separator = '?'
if other_url is not None:
url = other_url
else:
url = self.__handle_server_url.strip('/') +'/'+\
self.__REST_API_url_extension.strip('/')
url = url.strip('/')+'/'+ handle
if indices is None:
indices = []
if len(indices) > 0:
for index in indices:
url = url+separator+'index='+str(index)
separator = '&'
if overwrite is not None:
if overwrite:
url = url+separator+'overwrite=true'
else:
url = url+separator+'overwrite=false'
return url
|
python
|
def make_handle_URL(self, handle, indices=None, overwrite=None, other_url=None):
'''
Create the URL for a HTTP request (URL + query string) to request
a specific handle from the Handle Server.
:param handle: The handle to access.
:param indices: Optional. A list of integers or strings. Indices of
the handle record entries to read or write. Defaults to None.
:param overwrite: Optional. If set, an overwrite flag will be appended
to the URL ({?,&}overwrite=true or {?,&}overwrite=false). If not set, no
flag is set, thus the Handle Server's default behaviour will be
used. Defaults to None.
:param other_url: Optional. If a different Handle Server URL than the
one specified in the constructor should be used. Defaults to None.
If set, it should be set including the URL extension,
e.g. '/api/handles/'.
:return: The complete URL, e.g.
'http://some.handle.server/api/handles/prefix/suffix?index=2&index=6&overwrite=false
'''
LOGGER.debug('make_handle_URL...')
separator = '?'
if other_url is not None:
url = other_url
else:
url = self.__handle_server_url.strip('/') +'/'+\
self.__REST_API_url_extension.strip('/')
url = url.strip('/')+'/'+ handle
if indices is None:
indices = []
if len(indices) > 0:
for index in indices:
url = url+separator+'index='+str(index)
separator = '&'
if overwrite is not None:
if overwrite:
url = url+separator+'overwrite=true'
else:
url = url+separator+'overwrite=false'
return url
|
[
"def",
"make_handle_URL",
"(",
"self",
",",
"handle",
",",
"indices",
"=",
"None",
",",
"overwrite",
"=",
"None",
",",
"other_url",
"=",
"None",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'make_handle_URL...'",
")",
"separator",
"=",
"'?'",
"if",
"other_url",
"is",
"not",
"None",
":",
"url",
"=",
"other_url",
"else",
":",
"url",
"=",
"self",
".",
"__handle_server_url",
".",
"strip",
"(",
"'/'",
")",
"+",
"'/'",
"+",
"self",
".",
"__REST_API_url_extension",
".",
"strip",
"(",
"'/'",
")",
"url",
"=",
"url",
".",
"strip",
"(",
"'/'",
")",
"+",
"'/'",
"+",
"handle",
"if",
"indices",
"is",
"None",
":",
"indices",
"=",
"[",
"]",
"if",
"len",
"(",
"indices",
")",
">",
"0",
":",
"for",
"index",
"in",
"indices",
":",
"url",
"=",
"url",
"+",
"separator",
"+",
"'index='",
"+",
"str",
"(",
"index",
")",
"separator",
"=",
"'&'",
"if",
"overwrite",
"is",
"not",
"None",
":",
"if",
"overwrite",
":",
"url",
"=",
"url",
"+",
"separator",
"+",
"'overwrite=true'",
"else",
":",
"url",
"=",
"url",
"+",
"separator",
"+",
"'overwrite=false'",
"return",
"url"
] |
Create the URL for a HTTP request (URL + query string) to request
a specific handle from the Handle Server.
:param handle: The handle to access.
:param indices: Optional. A list of integers or strings. Indices of
the handle record entries to read or write. Defaults to None.
:param overwrite: Optional. If set, an overwrite flag will be appended
to the URL ({?,&}overwrite=true or {?,&}overwrite=false). If not set, no
flag is set, thus the Handle Server's default behaviour will be
used. Defaults to None.
:param other_url: Optional. If a different Handle Server URL than the
one specified in the constructor should be used. Defaults to None.
If set, it should be set including the URL extension,
e.g. '/api/handles/'.
:return: The complete URL, e.g.
'http://some.handle.server/api/handles/prefix/suffix?index=2&index=6&overwrite=false
|
[
"Create",
"the",
"URL",
"for",
"a",
"HTTP",
"request",
"(",
"URL",
"+",
"query",
"string",
")",
"to",
"request",
"a",
"specific",
"handle",
"from",
"the",
"Handle",
"Server",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/handlesystemconnector.py#L519-L561
|
train
|
fdChasm/txCarbonClient
|
src/txCarbonClient/carbon_client_service.py
|
CarbonClientService.publish_metric
|
def publish_metric(self, metric_name, metric_value, epoch_seconds=None):
'''Record a single hit on a given metric.
Args:
metric_name: The name of the metric to record with Carbon.
metric_value: The value to record with Carbon.
epoch_seconds: Optionally specify the time for the metric hit.
Returns:
None
'''
if epoch_seconds is None:
epoch_seconds = self._reactor.seconds()
self._client_factory.publish_metric(metric_name, metric_value, int(epoch_seconds))
|
python
|
def publish_metric(self, metric_name, metric_value, epoch_seconds=None):
'''Record a single hit on a given metric.
Args:
metric_name: The name of the metric to record with Carbon.
metric_value: The value to record with Carbon.
epoch_seconds: Optionally specify the time for the metric hit.
Returns:
None
'''
if epoch_seconds is None:
epoch_seconds = self._reactor.seconds()
self._client_factory.publish_metric(metric_name, metric_value, int(epoch_seconds))
|
[
"def",
"publish_metric",
"(",
"self",
",",
"metric_name",
",",
"metric_value",
",",
"epoch_seconds",
"=",
"None",
")",
":",
"if",
"epoch_seconds",
"is",
"None",
":",
"epoch_seconds",
"=",
"self",
".",
"_reactor",
".",
"seconds",
"(",
")",
"self",
".",
"_client_factory",
".",
"publish_metric",
"(",
"metric_name",
",",
"metric_value",
",",
"int",
"(",
"epoch_seconds",
")",
")"
] |
Record a single hit on a given metric.
Args:
metric_name: The name of the metric to record with Carbon.
metric_value: The value to record with Carbon.
epoch_seconds: Optionally specify the time for the metric hit.
Returns:
None
|
[
"Record",
"a",
"single",
"hit",
"on",
"a",
"given",
"metric",
"."
] |
c342eff1957d281cba3c83fc578f08c4bf9fcd03
|
https://github.com/fdChasm/txCarbonClient/blob/c342eff1957d281cba3c83fc578f08c4bf9fcd03/src/txCarbonClient/carbon_client_service.py#L30-L44
|
train
|
fdChasm/txCarbonClient
|
src/txCarbonClient/carbon_client_service.py
|
CarbonClientService.register_repeating_metric
|
def register_repeating_metric(self, metric_name, frequency, getter):
'''Record hits to a metric at a specified interval.
Args:
metric_name: The name of the metric to record with Carbon.
frequency: The frequency with which to poll the getter and record the value with Carbon.
getter: A function which takes no arguments and returns the value to record with Carbon.
Returns:
RepeatingMetricHandle instance. Call .stop() on it to stop recording the metric.
'''
l = task.LoopingCall(self._publish_repeating_metric, metric_name, getter)
repeating_metric_handle = RepeatingMetricHandle(l, frequency)
self._repeating_metric_handles.append(repeating_metric_handle)
if self.running:
repeating_metric_handle.start()
return repeating_metric_handle
|
python
|
def register_repeating_metric(self, metric_name, frequency, getter):
'''Record hits to a metric at a specified interval.
Args:
metric_name: The name of the metric to record with Carbon.
frequency: The frequency with which to poll the getter and record the value with Carbon.
getter: A function which takes no arguments and returns the value to record with Carbon.
Returns:
RepeatingMetricHandle instance. Call .stop() on it to stop recording the metric.
'''
l = task.LoopingCall(self._publish_repeating_metric, metric_name, getter)
repeating_metric_handle = RepeatingMetricHandle(l, frequency)
self._repeating_metric_handles.append(repeating_metric_handle)
if self.running:
repeating_metric_handle.start()
return repeating_metric_handle
|
[
"def",
"register_repeating_metric",
"(",
"self",
",",
"metric_name",
",",
"frequency",
",",
"getter",
")",
":",
"l",
"=",
"task",
".",
"LoopingCall",
"(",
"self",
".",
"_publish_repeating_metric",
",",
"metric_name",
",",
"getter",
")",
"repeating_metric_handle",
"=",
"RepeatingMetricHandle",
"(",
"l",
",",
"frequency",
")",
"self",
".",
"_repeating_metric_handles",
".",
"append",
"(",
"repeating_metric_handle",
")",
"if",
"self",
".",
"running",
":",
"repeating_metric_handle",
".",
"start",
"(",
")",
"return",
"repeating_metric_handle"
] |
Record hits to a metric at a specified interval.
Args:
metric_name: The name of the metric to record with Carbon.
frequency: The frequency with which to poll the getter and record the value with Carbon.
getter: A function which takes no arguments and returns the value to record with Carbon.
Returns:
RepeatingMetricHandle instance. Call .stop() on it to stop recording the metric.
|
[
"Record",
"hits",
"to",
"a",
"metric",
"at",
"a",
"specified",
"interval",
"."
] |
c342eff1957d281cba3c83fc578f08c4bf9fcd03
|
https://github.com/fdChasm/txCarbonClient/blob/c342eff1957d281cba3c83fc578f08c4bf9fcd03/src/txCarbonClient/carbon_client_service.py#L46-L63
|
train
|
pyblish/pyblish-nuke
|
pyblish_nuke/lib.py
|
setup
|
def setup(console=False, port=None, menu=True):
"""Setup integration
Registers Pyblish for Maya plug-ins and appends an item to the File-menu
Arguments:
console (bool): Display console with GUI
port (int, optional): Port from which to start looking for an
available port to connect with Pyblish QML, default
provided by Pyblish Integration.
"""
if self._has_been_setup:
teardown()
register_plugins()
register_host()
if menu:
add_to_filemenu()
self._has_menu = True
self._has_been_setup = True
print("pyblish: Loaded successfully.")
|
python
|
def setup(console=False, port=None, menu=True):
"""Setup integration
Registers Pyblish for Maya plug-ins and appends an item to the File-menu
Arguments:
console (bool): Display console with GUI
port (int, optional): Port from which to start looking for an
available port to connect with Pyblish QML, default
provided by Pyblish Integration.
"""
if self._has_been_setup:
teardown()
register_plugins()
register_host()
if menu:
add_to_filemenu()
self._has_menu = True
self._has_been_setup = True
print("pyblish: Loaded successfully.")
|
[
"def",
"setup",
"(",
"console",
"=",
"False",
",",
"port",
"=",
"None",
",",
"menu",
"=",
"True",
")",
":",
"if",
"self",
".",
"_has_been_setup",
":",
"teardown",
"(",
")",
"register_plugins",
"(",
")",
"register_host",
"(",
")",
"if",
"menu",
":",
"add_to_filemenu",
"(",
")",
"self",
".",
"_has_menu",
"=",
"True",
"self",
".",
"_has_been_setup",
"=",
"True",
"print",
"(",
"\"pyblish: Loaded successfully.\"",
")"
] |
Setup integration
Registers Pyblish for Maya plug-ins and appends an item to the File-menu
Arguments:
console (bool): Display console with GUI
port (int, optional): Port from which to start looking for an
available port to connect with Pyblish QML, default
provided by Pyblish Integration.
|
[
"Setup",
"integration"
] |
5fbd766774e999e5e3015201094a07a92d800c4f
|
https://github.com/pyblish/pyblish-nuke/blob/5fbd766774e999e5e3015201094a07a92d800c4f/pyblish_nuke/lib.py#L28-L52
|
train
|
pyblish/pyblish-nuke
|
pyblish_nuke/lib.py
|
show
|
def show():
"""Try showing the most desirable GUI
This function cycles through the currently registered
graphical user interfaces, if any, and presents it to
the user.
"""
parent = None
current = QtWidgets.QApplication.activeWindow()
while current:
parent = current
current = parent.parent()
window = (_discover_gui() or _show_no_gui)(parent)
return window
|
python
|
def show():
"""Try showing the most desirable GUI
This function cycles through the currently registered
graphical user interfaces, if any, and presents it to
the user.
"""
parent = None
current = QtWidgets.QApplication.activeWindow()
while current:
parent = current
current = parent.parent()
window = (_discover_gui() or _show_no_gui)(parent)
return window
|
[
"def",
"show",
"(",
")",
":",
"parent",
"=",
"None",
"current",
"=",
"QtWidgets",
".",
"QApplication",
".",
"activeWindow",
"(",
")",
"while",
"current",
":",
"parent",
"=",
"current",
"current",
"=",
"parent",
".",
"parent",
"(",
")",
"window",
"=",
"(",
"_discover_gui",
"(",
")",
"or",
"_show_no_gui",
")",
"(",
"parent",
")",
"return",
"window"
] |
Try showing the most desirable GUI
This function cycles through the currently registered
graphical user interfaces, if any, and presents it to
the user.
|
[
"Try",
"showing",
"the",
"most",
"desirable",
"GUI"
] |
5fbd766774e999e5e3015201094a07a92d800c4f
|
https://github.com/pyblish/pyblish-nuke/blob/5fbd766774e999e5e3015201094a07a92d800c4f/pyblish_nuke/lib.py#L55-L72
|
train
|
pyblish/pyblish-nuke
|
pyblish_nuke/lib.py
|
_nuke_set_zero_margins
|
def _nuke_set_zero_margins(widget_object):
"""Remove Nuke margins when docked UI
.. _More info:
https://gist.github.com/maty974/4739917
"""
parentApp = QtWidgets.QApplication.allWidgets()
parentWidgetList = []
for parent in parentApp:
for child in parent.children():
if widget_object.__class__.__name__ == child.__class__.__name__:
parentWidgetList.append(
parent.parentWidget())
parentWidgetList.append(
parent.parentWidget().parentWidget())
parentWidgetList.append(
parent.parentWidget().parentWidget().parentWidget())
for sub in parentWidgetList:
for tinychild in sub.children():
try:
tinychild.setContentsMargins(0, 0, 0, 0)
except Exception:
pass
|
python
|
def _nuke_set_zero_margins(widget_object):
"""Remove Nuke margins when docked UI
.. _More info:
https://gist.github.com/maty974/4739917
"""
parentApp = QtWidgets.QApplication.allWidgets()
parentWidgetList = []
for parent in parentApp:
for child in parent.children():
if widget_object.__class__.__name__ == child.__class__.__name__:
parentWidgetList.append(
parent.parentWidget())
parentWidgetList.append(
parent.parentWidget().parentWidget())
parentWidgetList.append(
parent.parentWidget().parentWidget().parentWidget())
for sub in parentWidgetList:
for tinychild in sub.children():
try:
tinychild.setContentsMargins(0, 0, 0, 0)
except Exception:
pass
|
[
"def",
"_nuke_set_zero_margins",
"(",
"widget_object",
")",
":",
"parentApp",
"=",
"QtWidgets",
".",
"QApplication",
".",
"allWidgets",
"(",
")",
"parentWidgetList",
"=",
"[",
"]",
"for",
"parent",
"in",
"parentApp",
":",
"for",
"child",
"in",
"parent",
".",
"children",
"(",
")",
":",
"if",
"widget_object",
".",
"__class__",
".",
"__name__",
"==",
"child",
".",
"__class__",
".",
"__name__",
":",
"parentWidgetList",
".",
"append",
"(",
"parent",
".",
"parentWidget",
"(",
")",
")",
"parentWidgetList",
".",
"append",
"(",
"parent",
".",
"parentWidget",
"(",
")",
".",
"parentWidget",
"(",
")",
")",
"parentWidgetList",
".",
"append",
"(",
"parent",
".",
"parentWidget",
"(",
")",
".",
"parentWidget",
"(",
")",
".",
"parentWidget",
"(",
")",
")",
"for",
"sub",
"in",
"parentWidgetList",
":",
"for",
"tinychild",
"in",
"sub",
".",
"children",
"(",
")",
":",
"try",
":",
"tinychild",
".",
"setContentsMargins",
"(",
"0",
",",
"0",
",",
"0",
",",
"0",
")",
"except",
"Exception",
":",
"pass"
] |
Remove Nuke margins when docked UI
.. _More info:
https://gist.github.com/maty974/4739917
|
[
"Remove",
"Nuke",
"margins",
"when",
"docked",
"UI",
"..",
"_More",
"info",
":",
"https",
":",
"//",
"gist",
".",
"github",
".",
"com",
"/",
"maty974",
"/",
"4739917"
] |
5fbd766774e999e5e3015201094a07a92d800c4f
|
https://github.com/pyblish/pyblish-nuke/blob/5fbd766774e999e5e3015201094a07a92d800c4f/pyblish_nuke/lib.py#L303-L325
|
train
|
pyblish/pyblish-nuke
|
pyblish_nuke/lib.py
|
dock
|
def dock(window):
""" Expecting a window to parent into a Nuke panel, that is dockable. """
# Deleting existing dock
# There is a bug where existing docks are kept in-memory when closed via UI
if self._dock:
print("Deleting existing dock...")
parent = self._dock
dialog = None
stacked_widget = None
main_windows = []
# Getting dock parents
while parent:
if isinstance(parent, QtWidgets.QDialog):
dialog = parent
if isinstance(parent, QtWidgets.QStackedWidget):
stacked_widget = parent
if isinstance(parent, QtWidgets.QMainWindow):
main_windows.append(parent)
parent = parent.parent()
dialog.deleteLater()
if len(main_windows) > 1:
# Then it's a floating window
if stacked_widget.count() == 1:
# Then it's empty and we can close it,
# as is native Nuke UI behaviour
main_windows[0].deleteLater()
# Creating new dock
pane = nuke.getPaneFor("Properties.1")
widget_path = "pyblish_nuke.lib.pyblish_nuke_dockwidget"
panel = nukescripts.panels.registerWidgetAsPanel(widget_path,
window.windowTitle(),
"pyblish_nuke.dock",
True).addToPane(pane)
panel_widget = panel.customKnob.getObject().widget
panel_widget.layout().addWidget(window)
_nuke_set_zero_margins(panel_widget)
self._dock = panel_widget
return self._dock
|
python
|
def dock(window):
""" Expecting a window to parent into a Nuke panel, that is dockable. """
# Deleting existing dock
# There is a bug where existing docks are kept in-memory when closed via UI
if self._dock:
print("Deleting existing dock...")
parent = self._dock
dialog = None
stacked_widget = None
main_windows = []
# Getting dock parents
while parent:
if isinstance(parent, QtWidgets.QDialog):
dialog = parent
if isinstance(parent, QtWidgets.QStackedWidget):
stacked_widget = parent
if isinstance(parent, QtWidgets.QMainWindow):
main_windows.append(parent)
parent = parent.parent()
dialog.deleteLater()
if len(main_windows) > 1:
# Then it's a floating window
if stacked_widget.count() == 1:
# Then it's empty and we can close it,
# as is native Nuke UI behaviour
main_windows[0].deleteLater()
# Creating new dock
pane = nuke.getPaneFor("Properties.1")
widget_path = "pyblish_nuke.lib.pyblish_nuke_dockwidget"
panel = nukescripts.panels.registerWidgetAsPanel(widget_path,
window.windowTitle(),
"pyblish_nuke.dock",
True).addToPane(pane)
panel_widget = panel.customKnob.getObject().widget
panel_widget.layout().addWidget(window)
_nuke_set_zero_margins(panel_widget)
self._dock = panel_widget
return self._dock
|
[
"def",
"dock",
"(",
"window",
")",
":",
"# Deleting existing dock",
"# There is a bug where existing docks are kept in-memory when closed via UI",
"if",
"self",
".",
"_dock",
":",
"print",
"(",
"\"Deleting existing dock...\"",
")",
"parent",
"=",
"self",
".",
"_dock",
"dialog",
"=",
"None",
"stacked_widget",
"=",
"None",
"main_windows",
"=",
"[",
"]",
"# Getting dock parents",
"while",
"parent",
":",
"if",
"isinstance",
"(",
"parent",
",",
"QtWidgets",
".",
"QDialog",
")",
":",
"dialog",
"=",
"parent",
"if",
"isinstance",
"(",
"parent",
",",
"QtWidgets",
".",
"QStackedWidget",
")",
":",
"stacked_widget",
"=",
"parent",
"if",
"isinstance",
"(",
"parent",
",",
"QtWidgets",
".",
"QMainWindow",
")",
":",
"main_windows",
".",
"append",
"(",
"parent",
")",
"parent",
"=",
"parent",
".",
"parent",
"(",
")",
"dialog",
".",
"deleteLater",
"(",
")",
"if",
"len",
"(",
"main_windows",
")",
">",
"1",
":",
"# Then it's a floating window",
"if",
"stacked_widget",
".",
"count",
"(",
")",
"==",
"1",
":",
"# Then it's empty and we can close it,",
"# as is native Nuke UI behaviour",
"main_windows",
"[",
"0",
"]",
".",
"deleteLater",
"(",
")",
"# Creating new dock",
"pane",
"=",
"nuke",
".",
"getPaneFor",
"(",
"\"Properties.1\"",
")",
"widget_path",
"=",
"\"pyblish_nuke.lib.pyblish_nuke_dockwidget\"",
"panel",
"=",
"nukescripts",
".",
"panels",
".",
"registerWidgetAsPanel",
"(",
"widget_path",
",",
"window",
".",
"windowTitle",
"(",
")",
",",
"\"pyblish_nuke.dock\"",
",",
"True",
")",
".",
"addToPane",
"(",
"pane",
")",
"panel_widget",
"=",
"panel",
".",
"customKnob",
".",
"getObject",
"(",
")",
".",
"widget",
"panel_widget",
".",
"layout",
"(",
")",
".",
"addWidget",
"(",
"window",
")",
"_nuke_set_zero_margins",
"(",
"panel_widget",
")",
"self",
".",
"_dock",
"=",
"panel_widget",
"return",
"self",
".",
"_dock"
] |
Expecting a window to parent into a Nuke panel, that is dockable.
|
[
"Expecting",
"a",
"window",
"to",
"parent",
"into",
"a",
"Nuke",
"panel",
"that",
"is",
"dockable",
"."
] |
5fbd766774e999e5e3015201094a07a92d800c4f
|
https://github.com/pyblish/pyblish-nuke/blob/5fbd766774e999e5e3015201094a07a92d800c4f/pyblish_nuke/lib.py#L335-L379
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/utilhandle.py
|
remove_index_from_handle
|
def remove_index_from_handle(handle_with_index):
'''
Returns index and handle separately, in a tuple.
:handle_with_index: The handle string with an index (e.g.
500:prefix/suffix)
:return: index and handle as a tuple.
'''
split = handle_with_index.split(':')
if len(split) == 2:
split[0] = int(split[0])
return split
elif len(split) == 1:
return (None, handle_with_index)
elif len(split) > 2:
raise handleexceptions.HandleSyntaxError(
msg='Too many colons',
handle=handle_with_index,
expected_syntax='index:prefix/suffix')
|
python
|
def remove_index_from_handle(handle_with_index):
'''
Returns index and handle separately, in a tuple.
:handle_with_index: The handle string with an index (e.g.
500:prefix/suffix)
:return: index and handle as a tuple.
'''
split = handle_with_index.split(':')
if len(split) == 2:
split[0] = int(split[0])
return split
elif len(split) == 1:
return (None, handle_with_index)
elif len(split) > 2:
raise handleexceptions.HandleSyntaxError(
msg='Too many colons',
handle=handle_with_index,
expected_syntax='index:prefix/suffix')
|
[
"def",
"remove_index_from_handle",
"(",
"handle_with_index",
")",
":",
"split",
"=",
"handle_with_index",
".",
"split",
"(",
"':'",
")",
"if",
"len",
"(",
"split",
")",
"==",
"2",
":",
"split",
"[",
"0",
"]",
"=",
"int",
"(",
"split",
"[",
"0",
"]",
")",
"return",
"split",
"elif",
"len",
"(",
"split",
")",
"==",
"1",
":",
"return",
"(",
"None",
",",
"handle_with_index",
")",
"elif",
"len",
"(",
"split",
")",
">",
"2",
":",
"raise",
"handleexceptions",
".",
"HandleSyntaxError",
"(",
"msg",
"=",
"'Too many colons'",
",",
"handle",
"=",
"handle_with_index",
",",
"expected_syntax",
"=",
"'index:prefix/suffix'",
")"
] |
Returns index and handle separately, in a tuple.
:handle_with_index: The handle string with an index (e.g.
500:prefix/suffix)
:return: index and handle as a tuple.
|
[
"Returns",
"index",
"and",
"handle",
"separately",
"in",
"a",
"tuple",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/utilhandle.py#L14-L33
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/utilhandle.py
|
check_handle_syntax
|
def check_handle_syntax(string):
'''
Checks the syntax of a handle without an index (are prefix
and suffix there, are there too many slashes?).
:string: The handle without index, as string prefix/suffix.
:raise: :exc:`~b2handle.handleexceptions.handleexceptions.HandleSyntaxError`
:return: True. If it's not ok, exceptions are raised.
'''
expected = 'prefix/suffix'
try:
arr = string.split('/')
except AttributeError:
raise handleexceptions.HandleSyntaxError(msg='The provided handle is None', expected_syntax=expected)
if len(arr) < 2:
msg = 'No slash'
raise handleexceptions.HandleSyntaxError(msg=msg, handle=string, expected_syntax=expected)
if len(arr[0]) == 0:
msg = 'Empty prefix'
raise handleexceptions.HandleSyntaxError(msg=msg, handle=string, expected_syntax=expected)
if len(arr[1]) == 0:
msg = 'Empty suffix'
raise handleexceptions.HandleSyntaxError(msg=msg, handle=string, expected_syntax=expected)
if ':' in string:
check_handle_syntax_with_index(string, base_already_checked=True)
return True
|
python
|
def check_handle_syntax(string):
'''
Checks the syntax of a handle without an index (are prefix
and suffix there, are there too many slashes?).
:string: The handle without index, as string prefix/suffix.
:raise: :exc:`~b2handle.handleexceptions.handleexceptions.HandleSyntaxError`
:return: True. If it's not ok, exceptions are raised.
'''
expected = 'prefix/suffix'
try:
arr = string.split('/')
except AttributeError:
raise handleexceptions.HandleSyntaxError(msg='The provided handle is None', expected_syntax=expected)
if len(arr) < 2:
msg = 'No slash'
raise handleexceptions.HandleSyntaxError(msg=msg, handle=string, expected_syntax=expected)
if len(arr[0]) == 0:
msg = 'Empty prefix'
raise handleexceptions.HandleSyntaxError(msg=msg, handle=string, expected_syntax=expected)
if len(arr[1]) == 0:
msg = 'Empty suffix'
raise handleexceptions.HandleSyntaxError(msg=msg, handle=string, expected_syntax=expected)
if ':' in string:
check_handle_syntax_with_index(string, base_already_checked=True)
return True
|
[
"def",
"check_handle_syntax",
"(",
"string",
")",
":",
"expected",
"=",
"'prefix/suffix'",
"try",
":",
"arr",
"=",
"string",
".",
"split",
"(",
"'/'",
")",
"except",
"AttributeError",
":",
"raise",
"handleexceptions",
".",
"HandleSyntaxError",
"(",
"msg",
"=",
"'The provided handle is None'",
",",
"expected_syntax",
"=",
"expected",
")",
"if",
"len",
"(",
"arr",
")",
"<",
"2",
":",
"msg",
"=",
"'No slash'",
"raise",
"handleexceptions",
".",
"HandleSyntaxError",
"(",
"msg",
"=",
"msg",
",",
"handle",
"=",
"string",
",",
"expected_syntax",
"=",
"expected",
")",
"if",
"len",
"(",
"arr",
"[",
"0",
"]",
")",
"==",
"0",
":",
"msg",
"=",
"'Empty prefix'",
"raise",
"handleexceptions",
".",
"HandleSyntaxError",
"(",
"msg",
"=",
"msg",
",",
"handle",
"=",
"string",
",",
"expected_syntax",
"=",
"expected",
")",
"if",
"len",
"(",
"arr",
"[",
"1",
"]",
")",
"==",
"0",
":",
"msg",
"=",
"'Empty suffix'",
"raise",
"handleexceptions",
".",
"HandleSyntaxError",
"(",
"msg",
"=",
"msg",
",",
"handle",
"=",
"string",
",",
"expected_syntax",
"=",
"expected",
")",
"if",
"':'",
"in",
"string",
":",
"check_handle_syntax_with_index",
"(",
"string",
",",
"base_already_checked",
"=",
"True",
")",
"return",
"True"
] |
Checks the syntax of a handle without an index (are prefix
and suffix there, are there too many slashes?).
:string: The handle without index, as string prefix/suffix.
:raise: :exc:`~b2handle.handleexceptions.handleexceptions.HandleSyntaxError`
:return: True. If it's not ok, exceptions are raised.
|
[
"Checks",
"the",
"syntax",
"of",
"a",
"handle",
"without",
"an",
"index",
"(",
"are",
"prefix",
"and",
"suffix",
"there",
"are",
"there",
"too",
"many",
"slashes?",
")",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/utilhandle.py#L35-L68
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/utilhandle.py
|
create_authentication_string
|
def create_authentication_string(username, password):
'''
Creates an authentication string from the username and password.
:username: Username.
:password: Password.
:return: The encoded string.
'''
username_utf8 = username.encode('utf-8')
userpw_utf8 = password.encode('utf-8')
username_perc = quote(username_utf8)
userpw_perc = quote(userpw_utf8)
authinfostring = username_perc + ':' + userpw_perc
authinfostring_base64 = base64.b64encode(authinfostring.encode('utf-8')).decode('utf-8')
return authinfostring_base64
|
python
|
def create_authentication_string(username, password):
'''
Creates an authentication string from the username and password.
:username: Username.
:password: Password.
:return: The encoded string.
'''
username_utf8 = username.encode('utf-8')
userpw_utf8 = password.encode('utf-8')
username_perc = quote(username_utf8)
userpw_perc = quote(userpw_utf8)
authinfostring = username_perc + ':' + userpw_perc
authinfostring_base64 = base64.b64encode(authinfostring.encode('utf-8')).decode('utf-8')
return authinfostring_base64
|
[
"def",
"create_authentication_string",
"(",
"username",
",",
"password",
")",
":",
"username_utf8",
"=",
"username",
".",
"encode",
"(",
"'utf-8'",
")",
"userpw_utf8",
"=",
"password",
".",
"encode",
"(",
"'utf-8'",
")",
"username_perc",
"=",
"quote",
"(",
"username_utf8",
")",
"userpw_perc",
"=",
"quote",
"(",
"userpw_utf8",
")",
"authinfostring",
"=",
"username_perc",
"+",
"':'",
"+",
"userpw_perc",
"authinfostring_base64",
"=",
"base64",
".",
"b64encode",
"(",
"authinfostring",
".",
"encode",
"(",
"'utf-8'",
")",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"return",
"authinfostring_base64"
] |
Creates an authentication string from the username and password.
:username: Username.
:password: Password.
:return: The encoded string.
|
[
"Creates",
"an",
"authentication",
"string",
"from",
"the",
"username",
"and",
"password",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/utilhandle.py#L102-L118
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/utilhandle.py
|
make_request_log_message
|
def make_request_log_message(**args):
'''
Creates a string containing all relevant information
about a request made to the Handle System, for
logging purposes.
:handle: The handle that the request is about.
:url: The url the request is sent to.
:headers: The headers sent along with the request.
:verify: Boolean parameter passed to the requests
module (https verification).
:resp: The request's response.
:op: The library operation during which the request
was sent.
:payload: Optional. The payload sent with the request.
:return: A formatted string.
'''
mandatory_args = ['op', 'handle', 'url', 'headers', 'verify', 'resp']
optional_args = ['payload']
util.check_presence_of_mandatory_args(args, mandatory_args)
util.add_missing_optional_args_with_value_none(args, optional_args)
space = '\n '
message = ''
message += '\n'+args['op']+' '+args['handle']
message += space+'URL: '+args['url']
message += space+'HEADERS: '+str(args['headers'])
message += space+'VERIFY: '+str(args['verify'])
if 'payload' in args.keys():
message += space+'PAYLOAD:'+space+str(args['payload'])
message += space+'RESPONSECODE: '+str(args['resp'].status_code)
message += space+'RESPONSE:'+space+str(args['resp'].content)
return message
|
python
|
def make_request_log_message(**args):
'''
Creates a string containing all relevant information
about a request made to the Handle System, for
logging purposes.
:handle: The handle that the request is about.
:url: The url the request is sent to.
:headers: The headers sent along with the request.
:verify: Boolean parameter passed to the requests
module (https verification).
:resp: The request's response.
:op: The library operation during which the request
was sent.
:payload: Optional. The payload sent with the request.
:return: A formatted string.
'''
mandatory_args = ['op', 'handle', 'url', 'headers', 'verify', 'resp']
optional_args = ['payload']
util.check_presence_of_mandatory_args(args, mandatory_args)
util.add_missing_optional_args_with_value_none(args, optional_args)
space = '\n '
message = ''
message += '\n'+args['op']+' '+args['handle']
message += space+'URL: '+args['url']
message += space+'HEADERS: '+str(args['headers'])
message += space+'VERIFY: '+str(args['verify'])
if 'payload' in args.keys():
message += space+'PAYLOAD:'+space+str(args['payload'])
message += space+'RESPONSECODE: '+str(args['resp'].status_code)
message += space+'RESPONSE:'+space+str(args['resp'].content)
return message
|
[
"def",
"make_request_log_message",
"(",
"*",
"*",
"args",
")",
":",
"mandatory_args",
"=",
"[",
"'op'",
",",
"'handle'",
",",
"'url'",
",",
"'headers'",
",",
"'verify'",
",",
"'resp'",
"]",
"optional_args",
"=",
"[",
"'payload'",
"]",
"util",
".",
"check_presence_of_mandatory_args",
"(",
"args",
",",
"mandatory_args",
")",
"util",
".",
"add_missing_optional_args_with_value_none",
"(",
"args",
",",
"optional_args",
")",
"space",
"=",
"'\\n '",
"message",
"=",
"''",
"message",
"+=",
"'\\n'",
"+",
"args",
"[",
"'op'",
"]",
"+",
"' '",
"+",
"args",
"[",
"'handle'",
"]",
"message",
"+=",
"space",
"+",
"'URL: '",
"+",
"args",
"[",
"'url'",
"]",
"message",
"+=",
"space",
"+",
"'HEADERS: '",
"+",
"str",
"(",
"args",
"[",
"'headers'",
"]",
")",
"message",
"+=",
"space",
"+",
"'VERIFY: '",
"+",
"str",
"(",
"args",
"[",
"'verify'",
"]",
")",
"if",
"'payload'",
"in",
"args",
".",
"keys",
"(",
")",
":",
"message",
"+=",
"space",
"+",
"'PAYLOAD:'",
"+",
"space",
"+",
"str",
"(",
"args",
"[",
"'payload'",
"]",
")",
"message",
"+=",
"space",
"+",
"'RESPONSECODE: '",
"+",
"str",
"(",
"args",
"[",
"'resp'",
"]",
".",
"status_code",
")",
"message",
"+=",
"space",
"+",
"'RESPONSE:'",
"+",
"space",
"+",
"str",
"(",
"args",
"[",
"'resp'",
"]",
".",
"content",
")",
"return",
"message"
] |
Creates a string containing all relevant information
about a request made to the Handle System, for
logging purposes.
:handle: The handle that the request is about.
:url: The url the request is sent to.
:headers: The headers sent along with the request.
:verify: Boolean parameter passed to the requests
module (https verification).
:resp: The request's response.
:op: The library operation during which the request
was sent.
:payload: Optional. The payload sent with the request.
:return: A formatted string.
|
[
"Creates",
"a",
"string",
"containing",
"all",
"relevant",
"information",
"about",
"a",
"request",
"made",
"to",
"the",
"Handle",
"System",
"for",
"logging",
"purposes",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/utilhandle.py#L120-L154
|
train
|
ioos/thredds_crawler
|
thredds_crawler/crawl.py
|
request_xml
|
def request_xml(url, auth=None):
'''
Returns an etree.XMLRoot object loaded from the url
:param str url: URL for the resource to load as an XML
'''
try:
r = requests.get(url, auth=auth, verify=False)
return r.text.encode('utf-8')
except BaseException:
logger.error("Skipping %s (error parsing the XML)" % url)
return
|
python
|
def request_xml(url, auth=None):
'''
Returns an etree.XMLRoot object loaded from the url
:param str url: URL for the resource to load as an XML
'''
try:
r = requests.get(url, auth=auth, verify=False)
return r.text.encode('utf-8')
except BaseException:
logger.error("Skipping %s (error parsing the XML)" % url)
return
|
[
"def",
"request_xml",
"(",
"url",
",",
"auth",
"=",
"None",
")",
":",
"try",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"auth",
"=",
"auth",
",",
"verify",
"=",
"False",
")",
"return",
"r",
".",
"text",
".",
"encode",
"(",
"'utf-8'",
")",
"except",
"BaseException",
":",
"logger",
".",
"error",
"(",
"\"Skipping %s (error parsing the XML)\"",
"%",
"url",
")",
"return"
] |
Returns an etree.XMLRoot object loaded from the url
:param str url: URL for the resource to load as an XML
|
[
"Returns",
"an",
"etree",
".",
"XMLRoot",
"object",
"loaded",
"from",
"the",
"url",
":",
"param",
"str",
"url",
":",
"URL",
"for",
"the",
"resource",
"to",
"load",
"as",
"an",
"XML"
] |
fb29ea2fb8d079cacc6c09f79245e8f54f77c6a6
|
https://github.com/ioos/thredds_crawler/blob/fb29ea2fb8d079cacc6c09f79245e8f54f77c6a6/thredds_crawler/crawl.py#L35-L45
|
train
|
ioos/thredds_crawler
|
thredds_crawler/crawl.py
|
Crawl._get_catalog_url
|
def _get_catalog_url(self, url):
'''
Returns the appropriate catalog URL by replacing html with xml in some
cases
:param str url: URL to the catalog
'''
u = urlparse.urlsplit(url)
name, ext = os.path.splitext(u.path)
if ext == ".html":
u = urlparse.urlsplit(url.replace(".html", ".xml"))
url = u.geturl()
return url
|
python
|
def _get_catalog_url(self, url):
'''
Returns the appropriate catalog URL by replacing html with xml in some
cases
:param str url: URL to the catalog
'''
u = urlparse.urlsplit(url)
name, ext = os.path.splitext(u.path)
if ext == ".html":
u = urlparse.urlsplit(url.replace(".html", ".xml"))
url = u.geturl()
return url
|
[
"def",
"_get_catalog_url",
"(",
"self",
",",
"url",
")",
":",
"u",
"=",
"urlparse",
".",
"urlsplit",
"(",
"url",
")",
"name",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"u",
".",
"path",
")",
"if",
"ext",
"==",
"\".html\"",
":",
"u",
"=",
"urlparse",
".",
"urlsplit",
"(",
"url",
".",
"replace",
"(",
"\".html\"",
",",
"\".xml\"",
")",
")",
"url",
"=",
"u",
".",
"geturl",
"(",
")",
"return",
"url"
] |
Returns the appropriate catalog URL by replacing html with xml in some
cases
:param str url: URL to the catalog
|
[
"Returns",
"the",
"appropriate",
"catalog",
"URL",
"by",
"replacing",
"html",
"with",
"xml",
"in",
"some",
"cases",
":",
"param",
"str",
"url",
":",
"URL",
"to",
"the",
"catalog"
] |
fb29ea2fb8d079cacc6c09f79245e8f54f77c6a6
|
https://github.com/ioos/thredds_crawler/blob/fb29ea2fb8d079cacc6c09f79245e8f54f77c6a6/thredds_crawler/crawl.py#L133-L144
|
train
|
ioos/thredds_crawler
|
thredds_crawler/crawl.py
|
Crawl._yield_leaves
|
def _yield_leaves(self, url, tree):
'''
Yields a URL corresponding to a leaf dataset for each dataset described by the catalog
:param str url: URL for the current catalog
:param lxml.etree.Eleemnt tree: Current XML Tree
'''
for leaf in tree.findall('.//{%s}dataset[@urlPath]' % INV_NS):
# Subset by the skips
name = leaf.get("name")
if any([x.match(name) for x in self.skip]):
logger.info("Skipping dataset based on 'skips'. Name: %s" % name)
continue
# Subset by before and after
date_tag = leaf.find('.//{%s}date[@type="modified"]' % INV_NS)
if date_tag is not None:
try:
dt = parse(date_tag.text)
except ValueError:
logger.error("Skipping dataset.Wrong date string %s " % date_tag.text)
continue
else:
dt = dt.replace(tzinfo=pytz.utc)
if self.after and dt < self.after:
continue
if self.before and dt > self.before:
continue
# Subset by the Selects defined
gid = leaf.get('ID')
if self.select is not None:
if gid is not None and any([x.match(gid) for x in self.select]):
logger.debug("Processing %s" % gid)
yield "%s?dataset=%s" % (url, gid)
else:
logger.info("Ignoring dataset based on 'selects'. ID: %s" % gid)
continue
else:
logger.debug("Processing %s" % gid)
yield "%s?dataset=%s" % (url, gid)
|
python
|
def _yield_leaves(self, url, tree):
'''
Yields a URL corresponding to a leaf dataset for each dataset described by the catalog
:param str url: URL for the current catalog
:param lxml.etree.Eleemnt tree: Current XML Tree
'''
for leaf in tree.findall('.//{%s}dataset[@urlPath]' % INV_NS):
# Subset by the skips
name = leaf.get("name")
if any([x.match(name) for x in self.skip]):
logger.info("Skipping dataset based on 'skips'. Name: %s" % name)
continue
# Subset by before and after
date_tag = leaf.find('.//{%s}date[@type="modified"]' % INV_NS)
if date_tag is not None:
try:
dt = parse(date_tag.text)
except ValueError:
logger.error("Skipping dataset.Wrong date string %s " % date_tag.text)
continue
else:
dt = dt.replace(tzinfo=pytz.utc)
if self.after and dt < self.after:
continue
if self.before and dt > self.before:
continue
# Subset by the Selects defined
gid = leaf.get('ID')
if self.select is not None:
if gid is not None and any([x.match(gid) for x in self.select]):
logger.debug("Processing %s" % gid)
yield "%s?dataset=%s" % (url, gid)
else:
logger.info("Ignoring dataset based on 'selects'. ID: %s" % gid)
continue
else:
logger.debug("Processing %s" % gid)
yield "%s?dataset=%s" % (url, gid)
|
[
"def",
"_yield_leaves",
"(",
"self",
",",
"url",
",",
"tree",
")",
":",
"for",
"leaf",
"in",
"tree",
".",
"findall",
"(",
"'.//{%s}dataset[@urlPath]'",
"%",
"INV_NS",
")",
":",
"# Subset by the skips",
"name",
"=",
"leaf",
".",
"get",
"(",
"\"name\"",
")",
"if",
"any",
"(",
"[",
"x",
".",
"match",
"(",
"name",
")",
"for",
"x",
"in",
"self",
".",
"skip",
"]",
")",
":",
"logger",
".",
"info",
"(",
"\"Skipping dataset based on 'skips'. Name: %s\"",
"%",
"name",
")",
"continue",
"# Subset by before and after",
"date_tag",
"=",
"leaf",
".",
"find",
"(",
"'.//{%s}date[@type=\"modified\"]'",
"%",
"INV_NS",
")",
"if",
"date_tag",
"is",
"not",
"None",
":",
"try",
":",
"dt",
"=",
"parse",
"(",
"date_tag",
".",
"text",
")",
"except",
"ValueError",
":",
"logger",
".",
"error",
"(",
"\"Skipping dataset.Wrong date string %s \"",
"%",
"date_tag",
".",
"text",
")",
"continue",
"else",
":",
"dt",
"=",
"dt",
".",
"replace",
"(",
"tzinfo",
"=",
"pytz",
".",
"utc",
")",
"if",
"self",
".",
"after",
"and",
"dt",
"<",
"self",
".",
"after",
":",
"continue",
"if",
"self",
".",
"before",
"and",
"dt",
">",
"self",
".",
"before",
":",
"continue",
"# Subset by the Selects defined",
"gid",
"=",
"leaf",
".",
"get",
"(",
"'ID'",
")",
"if",
"self",
".",
"select",
"is",
"not",
"None",
":",
"if",
"gid",
"is",
"not",
"None",
"and",
"any",
"(",
"[",
"x",
".",
"match",
"(",
"gid",
")",
"for",
"x",
"in",
"self",
".",
"select",
"]",
")",
":",
"logger",
".",
"debug",
"(",
"\"Processing %s\"",
"%",
"gid",
")",
"yield",
"\"%s?dataset=%s\"",
"%",
"(",
"url",
",",
"gid",
")",
"else",
":",
"logger",
".",
"info",
"(",
"\"Ignoring dataset based on 'selects'. ID: %s\"",
"%",
"gid",
")",
"continue",
"else",
":",
"logger",
".",
"debug",
"(",
"\"Processing %s\"",
"%",
"gid",
")",
"yield",
"\"%s?dataset=%s\"",
"%",
"(",
"url",
",",
"gid",
")"
] |
Yields a URL corresponding to a leaf dataset for each dataset described by the catalog
:param str url: URL for the current catalog
:param lxml.etree.Eleemnt tree: Current XML Tree
|
[
"Yields",
"a",
"URL",
"corresponding",
"to",
"a",
"leaf",
"dataset",
"for",
"each",
"dataset",
"described",
"by",
"the",
"catalog",
":",
"param",
"str",
"url",
":",
"URL",
"for",
"the",
"current",
"catalog",
":",
"param",
"lxml",
".",
"etree",
".",
"Eleemnt",
"tree",
":",
"Current",
"XML",
"Tree"
] |
fb29ea2fb8d079cacc6c09f79245e8f54f77c6a6
|
https://github.com/ioos/thredds_crawler/blob/fb29ea2fb8d079cacc6c09f79245e8f54f77c6a6/thredds_crawler/crawl.py#L146-L185
|
train
|
ioos/thredds_crawler
|
thredds_crawler/crawl.py
|
Crawl._compile_references
|
def _compile_references(self, url, tree):
'''
Returns a list of catalog reference URLs for the current catalog
:param str url: URL for the current catalog
:param lxml.etree.Eleemnt tree: Current XML Tree
'''
references = []
for ref in tree.findall('.//{%s}catalogRef' % INV_NS):
# Check skips
title = ref.get("{%s}title" % XLINK_NS)
if any([x.match(title) for x in self.skip]):
logger.info("Skipping catalogRef based on 'skips'. Title: %s" % title)
continue
references.append(construct_url(url, ref.get("{%s}href" % XLINK_NS)))
return references
|
python
|
def _compile_references(self, url, tree):
'''
Returns a list of catalog reference URLs for the current catalog
:param str url: URL for the current catalog
:param lxml.etree.Eleemnt tree: Current XML Tree
'''
references = []
for ref in tree.findall('.//{%s}catalogRef' % INV_NS):
# Check skips
title = ref.get("{%s}title" % XLINK_NS)
if any([x.match(title) for x in self.skip]):
logger.info("Skipping catalogRef based on 'skips'. Title: %s" % title)
continue
references.append(construct_url(url, ref.get("{%s}href" % XLINK_NS)))
return references
|
[
"def",
"_compile_references",
"(",
"self",
",",
"url",
",",
"tree",
")",
":",
"references",
"=",
"[",
"]",
"for",
"ref",
"in",
"tree",
".",
"findall",
"(",
"'.//{%s}catalogRef'",
"%",
"INV_NS",
")",
":",
"# Check skips",
"title",
"=",
"ref",
".",
"get",
"(",
"\"{%s}title\"",
"%",
"XLINK_NS",
")",
"if",
"any",
"(",
"[",
"x",
".",
"match",
"(",
"title",
")",
"for",
"x",
"in",
"self",
".",
"skip",
"]",
")",
":",
"logger",
".",
"info",
"(",
"\"Skipping catalogRef based on 'skips'. Title: %s\"",
"%",
"title",
")",
"continue",
"references",
".",
"append",
"(",
"construct_url",
"(",
"url",
",",
"ref",
".",
"get",
"(",
"\"{%s}href\"",
"%",
"XLINK_NS",
")",
")",
")",
"return",
"references"
] |
Returns a list of catalog reference URLs for the current catalog
:param str url: URL for the current catalog
:param lxml.etree.Eleemnt tree: Current XML Tree
|
[
"Returns",
"a",
"list",
"of",
"catalog",
"reference",
"URLs",
"for",
"the",
"current",
"catalog",
":",
"param",
"str",
"url",
":",
"URL",
"for",
"the",
"current",
"catalog",
":",
"param",
"lxml",
".",
"etree",
".",
"Eleemnt",
"tree",
":",
"Current",
"XML",
"Tree"
] |
fb29ea2fb8d079cacc6c09f79245e8f54f77c6a6
|
https://github.com/ioos/thredds_crawler/blob/fb29ea2fb8d079cacc6c09f79245e8f54f77c6a6/thredds_crawler/crawl.py#L187-L201
|
train
|
ioos/thredds_crawler
|
thredds_crawler/crawl.py
|
Crawl._run
|
def _run(self, url, auth):
'''
Performs a multiprocess depth-first-search of the catalog references
and yields a URL for each leaf dataset found
:param str url: URL for the current catalog
:param requests.auth.AuthBase auth: requets auth object to use
'''
if url in self.visited:
logger.debug("Skipping %s (already crawled)" % url)
return
self.visited.append(url)
logger.info("Crawling: %s" % url)
url = self._get_catalog_url(url)
# Get an etree object
xml_content = request_xml(url, auth)
for ds in self._build_catalog(url, xml_content):
yield ds
|
python
|
def _run(self, url, auth):
'''
Performs a multiprocess depth-first-search of the catalog references
and yields a URL for each leaf dataset found
:param str url: URL for the current catalog
:param requests.auth.AuthBase auth: requets auth object to use
'''
if url in self.visited:
logger.debug("Skipping %s (already crawled)" % url)
return
self.visited.append(url)
logger.info("Crawling: %s" % url)
url = self._get_catalog_url(url)
# Get an etree object
xml_content = request_xml(url, auth)
for ds in self._build_catalog(url, xml_content):
yield ds
|
[
"def",
"_run",
"(",
"self",
",",
"url",
",",
"auth",
")",
":",
"if",
"url",
"in",
"self",
".",
"visited",
":",
"logger",
".",
"debug",
"(",
"\"Skipping %s (already crawled)\"",
"%",
"url",
")",
"return",
"self",
".",
"visited",
".",
"append",
"(",
"url",
")",
"logger",
".",
"info",
"(",
"\"Crawling: %s\"",
"%",
"url",
")",
"url",
"=",
"self",
".",
"_get_catalog_url",
"(",
"url",
")",
"# Get an etree object",
"xml_content",
"=",
"request_xml",
"(",
"url",
",",
"auth",
")",
"for",
"ds",
"in",
"self",
".",
"_build_catalog",
"(",
"url",
",",
"xml_content",
")",
":",
"yield",
"ds"
] |
Performs a multiprocess depth-first-search of the catalog references
and yields a URL for each leaf dataset found
:param str url: URL for the current catalog
:param requests.auth.AuthBase auth: requets auth object to use
|
[
"Performs",
"a",
"multiprocess",
"depth",
"-",
"first",
"-",
"search",
"of",
"the",
"catalog",
"references",
"and",
"yields",
"a",
"URL",
"for",
"each",
"leaf",
"dataset",
"found",
":",
"param",
"str",
"url",
":",
"URL",
"for",
"the",
"current",
"catalog",
":",
"param",
"requests",
".",
"auth",
".",
"AuthBase",
"auth",
":",
"requets",
"auth",
"object",
"to",
"use"
] |
fb29ea2fb8d079cacc6c09f79245e8f54f77c6a6
|
https://github.com/ioos/thredds_crawler/blob/fb29ea2fb8d079cacc6c09f79245e8f54f77c6a6/thredds_crawler/crawl.py#L203-L221
|
train
|
ioos/thredds_crawler
|
thredds_crawler/crawl.py
|
Crawl._build_catalog
|
def _build_catalog(self, url, xml_content):
'''
Recursive function to perform the DFS and yield the leaf datasets
:param str url: URL for the current catalog
:param str xml_content: XML Body returned from HTTP Request
'''
try:
tree = etree.XML(xml_content)
except BaseException:
return
# Get a list of URLs
references = self._compile_references(url, tree)
# Using multiple processes, make HTTP requests for each child catalog
jobs = [self.pool.apply_async(request_xml, args=(ref,)) for ref in references]
responses = [j.get() for j in jobs]
# This is essentially the graph traversal step
for i, response in enumerate(responses):
for ds in self._build_catalog(references[i], response):
yield ds
# Yield the leaves
for ds in self._yield_leaves(url, tree):
yield ds
|
python
|
def _build_catalog(self, url, xml_content):
'''
Recursive function to perform the DFS and yield the leaf datasets
:param str url: URL for the current catalog
:param str xml_content: XML Body returned from HTTP Request
'''
try:
tree = etree.XML(xml_content)
except BaseException:
return
# Get a list of URLs
references = self._compile_references(url, tree)
# Using multiple processes, make HTTP requests for each child catalog
jobs = [self.pool.apply_async(request_xml, args=(ref,)) for ref in references]
responses = [j.get() for j in jobs]
# This is essentially the graph traversal step
for i, response in enumerate(responses):
for ds in self._build_catalog(references[i], response):
yield ds
# Yield the leaves
for ds in self._yield_leaves(url, tree):
yield ds
|
[
"def",
"_build_catalog",
"(",
"self",
",",
"url",
",",
"xml_content",
")",
":",
"try",
":",
"tree",
"=",
"etree",
".",
"XML",
"(",
"xml_content",
")",
"except",
"BaseException",
":",
"return",
"# Get a list of URLs",
"references",
"=",
"self",
".",
"_compile_references",
"(",
"url",
",",
"tree",
")",
"# Using multiple processes, make HTTP requests for each child catalog",
"jobs",
"=",
"[",
"self",
".",
"pool",
".",
"apply_async",
"(",
"request_xml",
",",
"args",
"=",
"(",
"ref",
",",
")",
")",
"for",
"ref",
"in",
"references",
"]",
"responses",
"=",
"[",
"j",
".",
"get",
"(",
")",
"for",
"j",
"in",
"jobs",
"]",
"# This is essentially the graph traversal step",
"for",
"i",
",",
"response",
"in",
"enumerate",
"(",
"responses",
")",
":",
"for",
"ds",
"in",
"self",
".",
"_build_catalog",
"(",
"references",
"[",
"i",
"]",
",",
"response",
")",
":",
"yield",
"ds",
"# Yield the leaves",
"for",
"ds",
"in",
"self",
".",
"_yield_leaves",
"(",
"url",
",",
"tree",
")",
":",
"yield",
"ds"
] |
Recursive function to perform the DFS and yield the leaf datasets
:param str url: URL for the current catalog
:param str xml_content: XML Body returned from HTTP Request
|
[
"Recursive",
"function",
"to",
"perform",
"the",
"DFS",
"and",
"yield",
"the",
"leaf",
"datasets",
":",
"param",
"str",
"url",
":",
"URL",
"for",
"the",
"current",
"catalog",
":",
"param",
"str",
"xml_content",
":",
"XML",
"Body",
"returned",
"from",
"HTTP",
"Request"
] |
fb29ea2fb8d079cacc6c09f79245e8f54f77c6a6
|
https://github.com/ioos/thredds_crawler/blob/fb29ea2fb8d079cacc6c09f79245e8f54f77c6a6/thredds_crawler/crawl.py#L223-L247
|
train
|
roman-neuhauser/py-impala
|
impala/__init__.py
|
Finder.find_module
|
def find_module(fdr, fqname, path = None):
'''Find a loader for module or package `fqname`.
This method will be called with the fully qualified name
of the module. If the finder is installed on `sys.meta_path`,
it will receive a second argument, which is `None` for
a top-level module, or `package.__path__` for submodules
or subpackages [5].
It should return a loader object if the module was found, or
`None` if it wasn't. If `find_module()` raises an exception,
it will be propagated to the caller, aborting the import.
[5] The path argument to `finder.find_module()` is there
because the `pkg.__path__` variable may be needed
at this point. It may either come from the actual
parent module or be supplied by `imp.find_module()`
or the proposed `imp.get_loader()` function.
'''
if fqname in fdr.aliases:
return Loader(fqname, fdr.aliases[fqname])
return None
|
python
|
def find_module(fdr, fqname, path = None):
'''Find a loader for module or package `fqname`.
This method will be called with the fully qualified name
of the module. If the finder is installed on `sys.meta_path`,
it will receive a second argument, which is `None` for
a top-level module, or `package.__path__` for submodules
or subpackages [5].
It should return a loader object if the module was found, or
`None` if it wasn't. If `find_module()` raises an exception,
it will be propagated to the caller, aborting the import.
[5] The path argument to `finder.find_module()` is there
because the `pkg.__path__` variable may be needed
at this point. It may either come from the actual
parent module or be supplied by `imp.find_module()`
or the proposed `imp.get_loader()` function.
'''
if fqname in fdr.aliases:
return Loader(fqname, fdr.aliases[fqname])
return None
|
[
"def",
"find_module",
"(",
"fdr",
",",
"fqname",
",",
"path",
"=",
"None",
")",
":",
"if",
"fqname",
"in",
"fdr",
".",
"aliases",
":",
"return",
"Loader",
"(",
"fqname",
",",
"fdr",
".",
"aliases",
"[",
"fqname",
"]",
")",
"return",
"None"
] |
Find a loader for module or package `fqname`.
This method will be called with the fully qualified name
of the module. If the finder is installed on `sys.meta_path`,
it will receive a second argument, which is `None` for
a top-level module, or `package.__path__` for submodules
or subpackages [5].
It should return a loader object if the module was found, or
`None` if it wasn't. If `find_module()` raises an exception,
it will be propagated to the caller, aborting the import.
[5] The path argument to `finder.find_module()` is there
because the `pkg.__path__` variable may be needed
at this point. It may either come from the actual
parent module or be supplied by `imp.find_module()`
or the proposed `imp.get_loader()` function.
|
[
"Find",
"a",
"loader",
"for",
"module",
"or",
"package",
"fqname",
"."
] |
8a22def2744460d20c620beb24c00332e77125d5
|
https://github.com/roman-neuhauser/py-impala/blob/8a22def2744460d20c620beb24c00332e77125d5/impala/__init__.py#L60-L80
|
train
|
roman-neuhauser/py-impala
|
impala/__init__.py
|
Loader.load_module
|
def load_module(ldr, fqname):
'''Load `fqname` from under `ldr.fspath`.
The `fqname` argument is the fully qualified module name,
eg. "spam.eggs.ham". As explained above, when ::
finder.find_module("spam.eggs.ham")
is called, "spam.eggs" has already been imported and added
to `sys.modules`. However, the `find_module()` method isn't
necessarily always called during an actual import:
meta tools that analyze import dependencies (such as freeze,
Installer or py2exe) don't actually load modules, so
a finder shouldn't depend on the parent package being
available in `sys.modules`.
The `load_module()` method has a few responsibilities that
it must fulfill before it runs any code:
* If there is an existing module object named 'fullname' in
`sys.modules`, the loader must use that existing module.
(Otherwise, the `reload()` builtin will not work correctly.)
If a module named 'fullname' does not exist in
`sys.modules`, the loader must create a new module object
and add it to `sys.modules`.
Note that the module object must be in `sys.modules`
before the loader executes the module code. This is
crucial because the module code may (directly or
indirectly) import itself; adding it to `sys.modules`
beforehand prevents unbounded recursion in the worst case
and multiple loading in the best.
If the load fails, the loader needs to remove any module it
may have inserted into `sys.modules`. If the module was
already in `sys.modules` then the loader should leave it
alone.
* The `__file__` attribute must be set. This must be a string,
but it may be a dummy value, for example "<frozen>".
The privilege of not having a `__file__` attribute at all
is reserved for built-in modules.
* The `__name__` attribute must be set. If one uses
`imp.new_module()` then the attribute is set automatically.
* If it's a package, the __path__ variable must be set.
This must be a list, but may be empty if `__path__` has no
further significance to the importer (more on this later).
* The `__loader__` attribute must be set to the loader object.
This is mostly for introspection and reloading, but can be
used for importer-specific extras, for example getting data
associated with an importer.
The `__package__` attribute [8] must be set.
If the module is a Python module (as opposed to a built-in
module or a dynamically loaded extension), it should execute
the module's code in the module's global name space
(`module.__dict__`).
[8] PEP 366: Main module explicit relative imports
http://www.python.org/dev/peps/pep-0366/
'''
scope = ldr.scope.split('.')
modpath = fqname.split('.')
if scope != modpath[0:len(scope)]:
raise AssertionError(
"%s responsible for %s got request for %s" % (
ldr.__class__.__name__,
ldr.scope,
fqname,
)
)
if fqname in sys.modules:
mod = sys.modules[fqname]
else:
mod = sys.modules.setdefault(fqname, types.ModuleType(fqname))
mod.__loader__ = ldr
fspath = ldr.path_to(fqname)
mod.__file__ = str(fspath)
if fs.is_package(fspath):
mod.__path__ = [ldr.fspath]
mod.__package__ = str(fqname)
else:
mod.__package__ = str(fqname.rpartition('.')[0])
exec(fs.get_code(fspath), mod.__dict__)
return mod
|
python
|
def load_module(ldr, fqname):
'''Load `fqname` from under `ldr.fspath`.
The `fqname` argument is the fully qualified module name,
eg. "spam.eggs.ham". As explained above, when ::
finder.find_module("spam.eggs.ham")
is called, "spam.eggs" has already been imported and added
to `sys.modules`. However, the `find_module()` method isn't
necessarily always called during an actual import:
meta tools that analyze import dependencies (such as freeze,
Installer or py2exe) don't actually load modules, so
a finder shouldn't depend on the parent package being
available in `sys.modules`.
The `load_module()` method has a few responsibilities that
it must fulfill before it runs any code:
* If there is an existing module object named 'fullname' in
`sys.modules`, the loader must use that existing module.
(Otherwise, the `reload()` builtin will not work correctly.)
If a module named 'fullname' does not exist in
`sys.modules`, the loader must create a new module object
and add it to `sys.modules`.
Note that the module object must be in `sys.modules`
before the loader executes the module code. This is
crucial because the module code may (directly or
indirectly) import itself; adding it to `sys.modules`
beforehand prevents unbounded recursion in the worst case
and multiple loading in the best.
If the load fails, the loader needs to remove any module it
may have inserted into `sys.modules`. If the module was
already in `sys.modules` then the loader should leave it
alone.
* The `__file__` attribute must be set. This must be a string,
but it may be a dummy value, for example "<frozen>".
The privilege of not having a `__file__` attribute at all
is reserved for built-in modules.
* The `__name__` attribute must be set. If one uses
`imp.new_module()` then the attribute is set automatically.
* If it's a package, the __path__ variable must be set.
This must be a list, but may be empty if `__path__` has no
further significance to the importer (more on this later).
* The `__loader__` attribute must be set to the loader object.
This is mostly for introspection and reloading, but can be
used for importer-specific extras, for example getting data
associated with an importer.
The `__package__` attribute [8] must be set.
If the module is a Python module (as opposed to a built-in
module or a dynamically loaded extension), it should execute
the module's code in the module's global name space
(`module.__dict__`).
[8] PEP 366: Main module explicit relative imports
http://www.python.org/dev/peps/pep-0366/
'''
scope = ldr.scope.split('.')
modpath = fqname.split('.')
if scope != modpath[0:len(scope)]:
raise AssertionError(
"%s responsible for %s got request for %s" % (
ldr.__class__.__name__,
ldr.scope,
fqname,
)
)
if fqname in sys.modules:
mod = sys.modules[fqname]
else:
mod = sys.modules.setdefault(fqname, types.ModuleType(fqname))
mod.__loader__ = ldr
fspath = ldr.path_to(fqname)
mod.__file__ = str(fspath)
if fs.is_package(fspath):
mod.__path__ = [ldr.fspath]
mod.__package__ = str(fqname)
else:
mod.__package__ = str(fqname.rpartition('.')[0])
exec(fs.get_code(fspath), mod.__dict__)
return mod
|
[
"def",
"load_module",
"(",
"ldr",
",",
"fqname",
")",
":",
"scope",
"=",
"ldr",
".",
"scope",
".",
"split",
"(",
"'.'",
")",
"modpath",
"=",
"fqname",
".",
"split",
"(",
"'.'",
")",
"if",
"scope",
"!=",
"modpath",
"[",
"0",
":",
"len",
"(",
"scope",
")",
"]",
":",
"raise",
"AssertionError",
"(",
"\"%s responsible for %s got request for %s\"",
"%",
"(",
"ldr",
".",
"__class__",
".",
"__name__",
",",
"ldr",
".",
"scope",
",",
"fqname",
",",
")",
")",
"if",
"fqname",
"in",
"sys",
".",
"modules",
":",
"mod",
"=",
"sys",
".",
"modules",
"[",
"fqname",
"]",
"else",
":",
"mod",
"=",
"sys",
".",
"modules",
".",
"setdefault",
"(",
"fqname",
",",
"types",
".",
"ModuleType",
"(",
"fqname",
")",
")",
"mod",
".",
"__loader__",
"=",
"ldr",
"fspath",
"=",
"ldr",
".",
"path_to",
"(",
"fqname",
")",
"mod",
".",
"__file__",
"=",
"str",
"(",
"fspath",
")",
"if",
"fs",
".",
"is_package",
"(",
"fspath",
")",
":",
"mod",
".",
"__path__",
"=",
"[",
"ldr",
".",
"fspath",
"]",
"mod",
".",
"__package__",
"=",
"str",
"(",
"fqname",
")",
"else",
":",
"mod",
".",
"__package__",
"=",
"str",
"(",
"fqname",
".",
"rpartition",
"(",
"'.'",
")",
"[",
"0",
"]",
")",
"exec",
"(",
"fs",
".",
"get_code",
"(",
"fspath",
")",
",",
"mod",
".",
"__dict__",
")",
"return",
"mod"
] |
Load `fqname` from under `ldr.fspath`.
The `fqname` argument is the fully qualified module name,
eg. "spam.eggs.ham". As explained above, when ::
finder.find_module("spam.eggs.ham")
is called, "spam.eggs" has already been imported and added
to `sys.modules`. However, the `find_module()` method isn't
necessarily always called during an actual import:
meta tools that analyze import dependencies (such as freeze,
Installer or py2exe) don't actually load modules, so
a finder shouldn't depend on the parent package being
available in `sys.modules`.
The `load_module()` method has a few responsibilities that
it must fulfill before it runs any code:
* If there is an existing module object named 'fullname' in
`sys.modules`, the loader must use that existing module.
(Otherwise, the `reload()` builtin will not work correctly.)
If a module named 'fullname' does not exist in
`sys.modules`, the loader must create a new module object
and add it to `sys.modules`.
Note that the module object must be in `sys.modules`
before the loader executes the module code. This is
crucial because the module code may (directly or
indirectly) import itself; adding it to `sys.modules`
beforehand prevents unbounded recursion in the worst case
and multiple loading in the best.
If the load fails, the loader needs to remove any module it
may have inserted into `sys.modules`. If the module was
already in `sys.modules` then the loader should leave it
alone.
* The `__file__` attribute must be set. This must be a string,
but it may be a dummy value, for example "<frozen>".
The privilege of not having a `__file__` attribute at all
is reserved for built-in modules.
* The `__name__` attribute must be set. If one uses
`imp.new_module()` then the attribute is set automatically.
* If it's a package, the __path__ variable must be set.
This must be a list, but may be empty if `__path__` has no
further significance to the importer (more on this later).
* The `__loader__` attribute must be set to the loader object.
This is mostly for introspection and reloading, but can be
used for importer-specific extras, for example getting data
associated with an importer.
The `__package__` attribute [8] must be set.
If the module is a Python module (as opposed to a built-in
module or a dynamically loaded extension), it should execute
the module's code in the module's global name space
(`module.__dict__`).
[8] PEP 366: Main module explicit relative imports
http://www.python.org/dev/peps/pep-0366/
|
[
"Load",
"fqname",
"from",
"under",
"ldr",
".",
"fspath",
"."
] |
8a22def2744460d20c620beb24c00332e77125d5
|
https://github.com/roman-neuhauser/py-impala/blob/8a22def2744460d20c620beb24c00332e77125d5/impala/__init__.py#L119-L216
|
train
|
csirtgadgets/bearded-avenger-sdk-py
|
cifsdk/utils/zhelper.py
|
zthread_fork
|
def zthread_fork(ctx, func, *args, **kwargs):
"""
Create an attached thread. An attached thread gets a ctx and a PAIR
pipe back to its parent. It must monitor its pipe, and exit if the
pipe becomes unreadable. Returns pipe, or NULL if there was an error.
"""
a = ctx.socket(zmq.PAIR)
a.setsockopt(zmq.LINGER, 0)
a.setsockopt(zmq.RCVHWM, 100)
a.setsockopt(zmq.SNDHWM, 100)
a.setsockopt(zmq.SNDTIMEO, 5000)
a.setsockopt(zmq.RCVTIMEO, 5000)
b = ctx.socket(zmq.PAIR)
b.setsockopt(zmq.LINGER, 0)
b.setsockopt(zmq.RCVHWM, 100)
b.setsockopt(zmq.SNDHWM, 100)
b.setsockopt(zmq.SNDTIMEO, 5000)
a.setsockopt(zmq.RCVTIMEO, 5000)
iface = "inproc://%s" % binascii.hexlify(os.urandom(8))
a.bind(iface)
b.connect(iface)
thread = threading.Thread(target=func, args=((ctx, b) + args), kwargs=kwargs)
thread.daemon = False
thread.start()
return a
|
python
|
def zthread_fork(ctx, func, *args, **kwargs):
"""
Create an attached thread. An attached thread gets a ctx and a PAIR
pipe back to its parent. It must monitor its pipe, and exit if the
pipe becomes unreadable. Returns pipe, or NULL if there was an error.
"""
a = ctx.socket(zmq.PAIR)
a.setsockopt(zmq.LINGER, 0)
a.setsockopt(zmq.RCVHWM, 100)
a.setsockopt(zmq.SNDHWM, 100)
a.setsockopt(zmq.SNDTIMEO, 5000)
a.setsockopt(zmq.RCVTIMEO, 5000)
b = ctx.socket(zmq.PAIR)
b.setsockopt(zmq.LINGER, 0)
b.setsockopt(zmq.RCVHWM, 100)
b.setsockopt(zmq.SNDHWM, 100)
b.setsockopt(zmq.SNDTIMEO, 5000)
a.setsockopt(zmq.RCVTIMEO, 5000)
iface = "inproc://%s" % binascii.hexlify(os.urandom(8))
a.bind(iface)
b.connect(iface)
thread = threading.Thread(target=func, args=((ctx, b) + args), kwargs=kwargs)
thread.daemon = False
thread.start()
return a
|
[
"def",
"zthread_fork",
"(",
"ctx",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"a",
"=",
"ctx",
".",
"socket",
"(",
"zmq",
".",
"PAIR",
")",
"a",
".",
"setsockopt",
"(",
"zmq",
".",
"LINGER",
",",
"0",
")",
"a",
".",
"setsockopt",
"(",
"zmq",
".",
"RCVHWM",
",",
"100",
")",
"a",
".",
"setsockopt",
"(",
"zmq",
".",
"SNDHWM",
",",
"100",
")",
"a",
".",
"setsockopt",
"(",
"zmq",
".",
"SNDTIMEO",
",",
"5000",
")",
"a",
".",
"setsockopt",
"(",
"zmq",
".",
"RCVTIMEO",
",",
"5000",
")",
"b",
"=",
"ctx",
".",
"socket",
"(",
"zmq",
".",
"PAIR",
")",
"b",
".",
"setsockopt",
"(",
"zmq",
".",
"LINGER",
",",
"0",
")",
"b",
".",
"setsockopt",
"(",
"zmq",
".",
"RCVHWM",
",",
"100",
")",
"b",
".",
"setsockopt",
"(",
"zmq",
".",
"SNDHWM",
",",
"100",
")",
"b",
".",
"setsockopt",
"(",
"zmq",
".",
"SNDTIMEO",
",",
"5000",
")",
"a",
".",
"setsockopt",
"(",
"zmq",
".",
"RCVTIMEO",
",",
"5000",
")",
"iface",
"=",
"\"inproc://%s\"",
"%",
"binascii",
".",
"hexlify",
"(",
"os",
".",
"urandom",
"(",
"8",
")",
")",
"a",
".",
"bind",
"(",
"iface",
")",
"b",
".",
"connect",
"(",
"iface",
")",
"thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"func",
",",
"args",
"=",
"(",
"(",
"ctx",
",",
"b",
")",
"+",
"args",
")",
",",
"kwargs",
"=",
"kwargs",
")",
"thread",
".",
"daemon",
"=",
"False",
"thread",
".",
"start",
"(",
")",
"return",
"a"
] |
Create an attached thread. An attached thread gets a ctx and a PAIR
pipe back to its parent. It must monitor its pipe, and exit if the
pipe becomes unreadable. Returns pipe, or NULL if there was an error.
|
[
"Create",
"an",
"attached",
"thread",
".",
"An",
"attached",
"thread",
"gets",
"a",
"ctx",
"and",
"a",
"PAIR",
"pipe",
"back",
"to",
"its",
"parent",
".",
"It",
"must",
"monitor",
"its",
"pipe",
"and",
"exit",
"if",
"the",
"pipe",
"becomes",
"unreadable",
".",
"Returns",
"pipe",
"or",
"NULL",
"if",
"there",
"was",
"an",
"error",
"."
] |
2b3e96cb2e7703ee0402811096da8265a740f378
|
https://github.com/csirtgadgets/bearded-avenger-sdk-py/blob/2b3e96cb2e7703ee0402811096da8265a740f378/cifsdk/utils/zhelper.py#L44-L70
|
train
|
pyblish/pyblish-nuke
|
pyblish_nuke/vendor/Qt.py
|
_remap
|
def _remap(object, name, value, safe=True):
"""Prevent accidental assignment of existing members
Arguments:
object (object): Parent of new attribute
name (str): Name of new attribute
value (object): Value of new attribute
safe (bool): Whether or not to guarantee that
the new attribute was not overwritten.
Can be set to False under condition that
it is superseded by extensive testing.
"""
if os.getenv("QT_TESTING") is not None and safe:
# Cannot alter original binding.
if hasattr(object, name):
raise AttributeError("Cannot override existing name: "
"%s.%s" % (object.__name__, name))
# Cannot alter classes of functions
if type(object).__name__ != "module":
raise AttributeError("%s != 'module': Cannot alter "
"anything but modules" % object)
elif hasattr(object, name):
# Keep track of modifications
self.__modified__.append(name)
self.__remapped__.append(name)
setattr(object, name, value)
|
python
|
def _remap(object, name, value, safe=True):
"""Prevent accidental assignment of existing members
Arguments:
object (object): Parent of new attribute
name (str): Name of new attribute
value (object): Value of new attribute
safe (bool): Whether or not to guarantee that
the new attribute was not overwritten.
Can be set to False under condition that
it is superseded by extensive testing.
"""
if os.getenv("QT_TESTING") is not None and safe:
# Cannot alter original binding.
if hasattr(object, name):
raise AttributeError("Cannot override existing name: "
"%s.%s" % (object.__name__, name))
# Cannot alter classes of functions
if type(object).__name__ != "module":
raise AttributeError("%s != 'module': Cannot alter "
"anything but modules" % object)
elif hasattr(object, name):
# Keep track of modifications
self.__modified__.append(name)
self.__remapped__.append(name)
setattr(object, name, value)
|
[
"def",
"_remap",
"(",
"object",
",",
"name",
",",
"value",
",",
"safe",
"=",
"True",
")",
":",
"if",
"os",
".",
"getenv",
"(",
"\"QT_TESTING\"",
")",
"is",
"not",
"None",
"and",
"safe",
":",
"# Cannot alter original binding.",
"if",
"hasattr",
"(",
"object",
",",
"name",
")",
":",
"raise",
"AttributeError",
"(",
"\"Cannot override existing name: \"",
"\"%s.%s\"",
"%",
"(",
"object",
".",
"__name__",
",",
"name",
")",
")",
"# Cannot alter classes of functions",
"if",
"type",
"(",
"object",
")",
".",
"__name__",
"!=",
"\"module\"",
":",
"raise",
"AttributeError",
"(",
"\"%s != 'module': Cannot alter \"",
"\"anything but modules\"",
"%",
"object",
")",
"elif",
"hasattr",
"(",
"object",
",",
"name",
")",
":",
"# Keep track of modifications",
"self",
".",
"__modified__",
".",
"append",
"(",
"name",
")",
"self",
".",
"__remapped__",
".",
"append",
"(",
"name",
")",
"setattr",
"(",
"object",
",",
"name",
",",
"value",
")"
] |
Prevent accidental assignment of existing members
Arguments:
object (object): Parent of new attribute
name (str): Name of new attribute
value (object): Value of new attribute
safe (bool): Whether or not to guarantee that
the new attribute was not overwritten.
Can be set to False under condition that
it is superseded by extensive testing.
|
[
"Prevent",
"accidental",
"assignment",
"of",
"existing",
"members"
] |
5fbd766774e999e5e3015201094a07a92d800c4f
|
https://github.com/pyblish/pyblish-nuke/blob/5fbd766774e999e5e3015201094a07a92d800c4f/pyblish_nuke/vendor/Qt.py#L77-L108
|
train
|
pyblish/pyblish-nuke
|
pyblish_nuke/vendor/Qt.py
|
init
|
def init():
"""Try loading each binding in turn
Please note: the entire Qt module is replaced with this code:
sys.modules["Qt"] = binding()
This means no functions or variables can be called after
this has executed.
For debugging and testing, this module may be accessed
through `Qt.__shim__`.
"""
preferred = os.getenv("QT_PREFERRED_BINDING")
verbose = os.getenv("QT_VERBOSE") is not None
bindings = (_pyside2, _pyqt5, _pyside, _pyqt4)
if preferred:
# Internal flag (used in installer)
if preferred == "None":
self.__wrapper_version__ = self.__version__
return
preferred = preferred.split(os.pathsep)
available = {
"PySide2": _pyside2,
"PyQt5": _pyqt5,
"PySide": _pyside,
"PyQt4": _pyqt4
}
try:
bindings = [available[binding] for binding in preferred]
except KeyError:
raise ImportError(
"Available preferred Qt bindings: "
"\n".join(preferred)
)
for binding in bindings:
_log("Trying %s" % binding.__name__, verbose)
try:
binding = binding()
except ImportError as e:
_log(" - ImportError(\"%s\")" % e, verbose)
continue
else:
# Reference to this module
binding.__shim__ = self
binding.QtCompat = self
sys.modules.update({
__name__: binding,
# Fix #133, `from Qt.QtWidgets import QPushButton`
__name__ + ".QtWidgets": binding.QtWidgets
})
return
# If not binding were found, throw this error
raise ImportError("No Qt binding were found.")
|
python
|
def init():
"""Try loading each binding in turn
Please note: the entire Qt module is replaced with this code:
sys.modules["Qt"] = binding()
This means no functions or variables can be called after
this has executed.
For debugging and testing, this module may be accessed
through `Qt.__shim__`.
"""
preferred = os.getenv("QT_PREFERRED_BINDING")
verbose = os.getenv("QT_VERBOSE") is not None
bindings = (_pyside2, _pyqt5, _pyside, _pyqt4)
if preferred:
# Internal flag (used in installer)
if preferred == "None":
self.__wrapper_version__ = self.__version__
return
preferred = preferred.split(os.pathsep)
available = {
"PySide2": _pyside2,
"PyQt5": _pyqt5,
"PySide": _pyside,
"PyQt4": _pyqt4
}
try:
bindings = [available[binding] for binding in preferred]
except KeyError:
raise ImportError(
"Available preferred Qt bindings: "
"\n".join(preferred)
)
for binding in bindings:
_log("Trying %s" % binding.__name__, verbose)
try:
binding = binding()
except ImportError as e:
_log(" - ImportError(\"%s\")" % e, verbose)
continue
else:
# Reference to this module
binding.__shim__ = self
binding.QtCompat = self
sys.modules.update({
__name__: binding,
# Fix #133, `from Qt.QtWidgets import QPushButton`
__name__ + ".QtWidgets": binding.QtWidgets
})
return
# If not binding were found, throw this error
raise ImportError("No Qt binding were found.")
|
[
"def",
"init",
"(",
")",
":",
"preferred",
"=",
"os",
".",
"getenv",
"(",
"\"QT_PREFERRED_BINDING\"",
")",
"verbose",
"=",
"os",
".",
"getenv",
"(",
"\"QT_VERBOSE\"",
")",
"is",
"not",
"None",
"bindings",
"=",
"(",
"_pyside2",
",",
"_pyqt5",
",",
"_pyside",
",",
"_pyqt4",
")",
"if",
"preferred",
":",
"# Internal flag (used in installer)",
"if",
"preferred",
"==",
"\"None\"",
":",
"self",
".",
"__wrapper_version__",
"=",
"self",
".",
"__version__",
"return",
"preferred",
"=",
"preferred",
".",
"split",
"(",
"os",
".",
"pathsep",
")",
"available",
"=",
"{",
"\"PySide2\"",
":",
"_pyside2",
",",
"\"PyQt5\"",
":",
"_pyqt5",
",",
"\"PySide\"",
":",
"_pyside",
",",
"\"PyQt4\"",
":",
"_pyqt4",
"}",
"try",
":",
"bindings",
"=",
"[",
"available",
"[",
"binding",
"]",
"for",
"binding",
"in",
"preferred",
"]",
"except",
"KeyError",
":",
"raise",
"ImportError",
"(",
"\"Available preferred Qt bindings: \"",
"\"\\n\"",
".",
"join",
"(",
"preferred",
")",
")",
"for",
"binding",
"in",
"bindings",
":",
"_log",
"(",
"\"Trying %s\"",
"%",
"binding",
".",
"__name__",
",",
"verbose",
")",
"try",
":",
"binding",
"=",
"binding",
"(",
")",
"except",
"ImportError",
"as",
"e",
":",
"_log",
"(",
"\" - ImportError(\\\"%s\\\")\"",
"%",
"e",
",",
"verbose",
")",
"continue",
"else",
":",
"# Reference to this module",
"binding",
".",
"__shim__",
"=",
"self",
"binding",
".",
"QtCompat",
"=",
"self",
"sys",
".",
"modules",
".",
"update",
"(",
"{",
"__name__",
":",
"binding",
",",
"# Fix #133, `from Qt.QtWidgets import QPushButton`",
"__name__",
"+",
"\".QtWidgets\"",
":",
"binding",
".",
"QtWidgets",
"}",
")",
"return",
"# If not binding were found, throw this error",
"raise",
"ImportError",
"(",
"\"No Qt binding were found.\"",
")"
] |
Try loading each binding in turn
Please note: the entire Qt module is replaced with this code:
sys.modules["Qt"] = binding()
This means no functions or variables can be called after
this has executed.
For debugging and testing, this module may be accessed
through `Qt.__shim__`.
|
[
"Try",
"loading",
"each",
"binding",
"in",
"turn"
] |
5fbd766774e999e5e3015201094a07a92d800c4f
|
https://github.com/pyblish/pyblish-nuke/blob/5fbd766774e999e5e3015201094a07a92d800c4f/pyblish_nuke/vendor/Qt.py#L299-L365
|
train
|
EUDAT-B2SAFE/B2HANDLE
|
b2handle/util/logutils.py
|
log_instantiation
|
def log_instantiation(LOGGER, classname, args, forbidden, with_date=False):
'''
Log the instantiation of an object to the given logger.
:LOGGER: A logger to log to. Please see module "logging".
:classname: The name of the class that is being
instantiated.
:args: A dictionary of arguments passed to the instantiation,
which will be logged on debug level.
:forbidden: A list of arguments whose values should not be
logged, e.g. "password".
:with_date: Optional. Boolean. Indicated whether the initiation
date and time should be logged.
'''
# Info:
if with_date:
LOGGER.info('Instantiating '+classname+' at '+datetime.datetime.now().strftime('%Y-%m-%d_%H:%M'))
else:
LOGGER.info('Instantiating '+classname)
# Debug:
for argname in args:
if args[argname] is not None:
if argname in forbidden:
LOGGER.debug('Param '+argname+'*******')
else:
LOGGER.debug('Param '+argname+'='+str(args[argname]))
|
python
|
def log_instantiation(LOGGER, classname, args, forbidden, with_date=False):
'''
Log the instantiation of an object to the given logger.
:LOGGER: A logger to log to. Please see module "logging".
:classname: The name of the class that is being
instantiated.
:args: A dictionary of arguments passed to the instantiation,
which will be logged on debug level.
:forbidden: A list of arguments whose values should not be
logged, e.g. "password".
:with_date: Optional. Boolean. Indicated whether the initiation
date and time should be logged.
'''
# Info:
if with_date:
LOGGER.info('Instantiating '+classname+' at '+datetime.datetime.now().strftime('%Y-%m-%d_%H:%M'))
else:
LOGGER.info('Instantiating '+classname)
# Debug:
for argname in args:
if args[argname] is not None:
if argname in forbidden:
LOGGER.debug('Param '+argname+'*******')
else:
LOGGER.debug('Param '+argname+'='+str(args[argname]))
|
[
"def",
"log_instantiation",
"(",
"LOGGER",
",",
"classname",
",",
"args",
",",
"forbidden",
",",
"with_date",
"=",
"False",
")",
":",
"# Info:",
"if",
"with_date",
":",
"LOGGER",
".",
"info",
"(",
"'Instantiating '",
"+",
"classname",
"+",
"' at '",
"+",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"'%Y-%m-%d_%H:%M'",
")",
")",
"else",
":",
"LOGGER",
".",
"info",
"(",
"'Instantiating '",
"+",
"classname",
")",
"# Debug:",
"for",
"argname",
"in",
"args",
":",
"if",
"args",
"[",
"argname",
"]",
"is",
"not",
"None",
":",
"if",
"argname",
"in",
"forbidden",
":",
"LOGGER",
".",
"debug",
"(",
"'Param '",
"+",
"argname",
"+",
"'*******'",
")",
"else",
":",
"LOGGER",
".",
"debug",
"(",
"'Param '",
"+",
"argname",
"+",
"'='",
"+",
"str",
"(",
"args",
"[",
"argname",
"]",
")",
")"
] |
Log the instantiation of an object to the given logger.
:LOGGER: A logger to log to. Please see module "logging".
:classname: The name of the class that is being
instantiated.
:args: A dictionary of arguments passed to the instantiation,
which will be logged on debug level.
:forbidden: A list of arguments whose values should not be
logged, e.g. "password".
:with_date: Optional. Boolean. Indicated whether the initiation
date and time should be logged.
|
[
"Log",
"the",
"instantiation",
"of",
"an",
"object",
"to",
"the",
"given",
"logger",
"."
] |
a6d216d459644e01fbdfd5b318a535950bc5cdbb
|
https://github.com/EUDAT-B2SAFE/B2HANDLE/blob/a6d216d459644e01fbdfd5b318a535950bc5cdbb/b2handle/util/logutils.py#L31-L58
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.