repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
cescobarresi/ciscoreputation | ciscoreputation/ciscoreputation.py | get_data | def get_data(search_string, search_by='ip'):
"""
Download data from talosintelligence.com for the given IP
Return tabbed data text
"""
r_details = requests.get('https://talosintelligence.com/sb_api/query_lookup',
headers={
'Referer':'https://talosintelligence.com/reputat... | python | def get_data(search_string, search_by='ip'):
"""
Download data from talosintelligence.com for the given IP
Return tabbed data text
"""
r_details = requests.get('https://talosintelligence.com/sb_api/query_lookup',
headers={
'Referer':'https://talosintelligence.com/reputat... | [
"def",
"get_data",
"(",
"search_string",
",",
"search_by",
"=",
"'ip'",
")",
":",
"r_details",
"=",
"requests",
".",
"get",
"(",
"'https://talosintelligence.com/sb_api/query_lookup'",
",",
"headers",
"=",
"{",
"'Referer'",
":",
"'https://talosintelligence.com/reputation... | Download data from talosintelligence.com for the given IP
Return tabbed data text | [
"Download",
"data",
"from",
"talosintelligence",
".",
"com",
"for",
"the",
"given",
"IP"
] | train | https://github.com/cescobarresi/ciscoreputation/blob/5b3f0e7db562ca72cd5d7fe8b6d8c8f53d836d28/ciscoreputation/ciscoreputation.py#L33-L99 |
jwplayer/jwplatform-py | examples/video_channel_insert.py | insert_into_channel | def insert_into_channel(api_key, api_secret, channel_key, video_key, **kwargs):
"""
Function which inserts video into a channel/playlist.
:param api_key: <string> JWPlatform api-key
:param api_secret: <string> JWPlatform shared-secret
:param channel_key: <string> Key of the channel to which add a v... | python | def insert_into_channel(api_key, api_secret, channel_key, video_key, **kwargs):
"""
Function which inserts video into a channel/playlist.
:param api_key: <string> JWPlatform api-key
:param api_secret: <string> JWPlatform shared-secret
:param channel_key: <string> Key of the channel to which add a v... | [
"def",
"insert_into_channel",
"(",
"api_key",
",",
"api_secret",
",",
"channel_key",
",",
"video_key",
",",
"*",
"*",
"kwargs",
")",
":",
"jwplatform_client",
"=",
"jwplatform",
".",
"Client",
"(",
"api_key",
",",
"api_secret",
")",
"logging",
".",
"info",
"... | Function which inserts video into a channel/playlist.
:param api_key: <string> JWPlatform api-key
:param api_secret: <string> JWPlatform shared-secret
:param channel_key: <string> Key of the channel to which add a video.
:param video_key: <string> Key of the video that should be added to the channel.
... | [
"Function",
"which",
"inserts",
"video",
"into",
"a",
"channel",
"/",
"playlist",
"."
] | train | https://github.com/jwplayer/jwplatform-py/blob/804950158fa04a6b153fc86acae9a3f97ba3bd75/examples/video_channel_insert.py#L10-L31 |
jwplayer/jwplatform-py | examples/video_conversions_list.py | list_conversions | def list_conversions(api_key, api_secret, video_key, **kwargs):
"""
Function which retrieves a list of a video object's conversions.
:param api_key: <string> JWPlatform api-key
:param api_secret: <string> JWPlatform shared-secret
:param video_key: <string> Video's object ID. Can be found within JWP... | python | def list_conversions(api_key, api_secret, video_key, **kwargs):
"""
Function which retrieves a list of a video object's conversions.
:param api_key: <string> JWPlatform api-key
:param api_secret: <string> JWPlatform shared-secret
:param video_key: <string> Video's object ID. Can be found within JWP... | [
"def",
"list_conversions",
"(",
"api_key",
",",
"api_secret",
",",
"video_key",
",",
"*",
"*",
"kwargs",
")",
":",
"jwplatform_client",
"=",
"jwplatform",
".",
"Client",
"(",
"api_key",
",",
"api_secret",
")",
"logging",
".",
"info",
"(",
"\"Querying for video... | Function which retrieves a list of a video object's conversions.
:param api_key: <string> JWPlatform api-key
:param api_secret: <string> JWPlatform shared-secret
:param video_key: <string> Video's object ID. Can be found within JWPlayer Dashboard.
:param kwargs: Arguments conforming to standards found ... | [
"Function",
"which",
"retrieves",
"a",
"list",
"of",
"a",
"video",
"object",
"s",
"conversions",
"."
] | train | https://github.com/jwplayer/jwplatform-py/blob/804950158fa04a6b153fc86acae9a3f97ba3bd75/examples/video_conversions_list.py#L10-L27 |
jwplayer/jwplatform-py | jwplatform/client.py | Client._build_request | def _build_request(self, path, params=None):
"""Build API request"""
_url = '{scheme}://{host}{port}/{version}{path}'.format(
scheme=self._scheme,
host=self._host,
port=':{}'.format(self._port) if self._port != 80 else '',
version=self._api_version,
... | python | def _build_request(self, path, params=None):
"""Build API request"""
_url = '{scheme}://{host}{port}/{version}{path}'.format(
scheme=self._scheme,
host=self._host,
port=':{}'.format(self._port) if self._port != 80 else '',
version=self._api_version,
... | [
"def",
"_build_request",
"(",
"self",
",",
"path",
",",
"params",
"=",
"None",
")",
":",
"_url",
"=",
"'{scheme}://{host}{port}/{version}{path}'",
".",
"format",
"(",
"scheme",
"=",
"self",
".",
"_scheme",
",",
"host",
"=",
"self",
".",
"_host",
",",
"port... | Build API request | [
"Build",
"API",
"request"
] | train | https://github.com/jwplayer/jwplatform-py/blob/804950158fa04a6b153fc86acae9a3f97ba3bd75/jwplatform/client.py#L79-L112 |
jwplayer/jwplatform-py | examples/video_singlepart_create.py | create_video | def create_video(api_key, api_secret, local_video_path, api_format='json', **kwargs):
"""
Function which creates new video object via singlefile upload method.
:param api_key: <string> JWPlatform api-key
:param api_secret: <string> JWPlatform shared-secret
:param local_video_path: <string> Path to ... | python | def create_video(api_key, api_secret, local_video_path, api_format='json', **kwargs):
"""
Function which creates new video object via singlefile upload method.
:param api_key: <string> JWPlatform api-key
:param api_secret: <string> JWPlatform shared-secret
:param local_video_path: <string> Path to ... | [
"def",
"create_video",
"(",
"api_key",
",",
"api_secret",
",",
"local_video_path",
",",
"api_format",
"=",
"'json'",
",",
"*",
"*",
"kwargs",
")",
":",
"# Setup API client",
"jwplatform_client",
"=",
"jwplatform",
".",
"Client",
"(",
"api_key",
",",
"api_secret"... | Function which creates new video object via singlefile upload method.
:param api_key: <string> JWPlatform api-key
:param api_secret: <string> JWPlatform shared-secret
:param local_video_path: <string> Path to media on local machine.
:param api_format: <string> Acceptable values include 'py','xml','json... | [
"Function",
"which",
"creates",
"new",
"video",
"object",
"via",
"singlefile",
"upload",
"method",
"."
] | train | https://github.com/jwplayer/jwplatform-py/blob/804950158fa04a6b153fc86acae9a3f97ba3bd75/examples/video_singlepart_create.py#L12-L52 |
jwplayer/jwplatform-py | examples/video_s3_replace_video.py | replace_video | def replace_video(api_key, api_secret, local_video_path, video_key, **kwargs):
"""
Function which allows to replace the content of an EXISTING video object.
:param api_key: <string> JWPlatform api-key
:param api_secret: <string> JWPlatform shared-secret
:param local_video_path: <string> Path to med... | python | def replace_video(api_key, api_secret, local_video_path, video_key, **kwargs):
"""
Function which allows to replace the content of an EXISTING video object.
:param api_key: <string> JWPlatform api-key
:param api_secret: <string> JWPlatform shared-secret
:param local_video_path: <string> Path to med... | [
"def",
"replace_video",
"(",
"api_key",
",",
"api_secret",
",",
"local_video_path",
",",
"video_key",
",",
"*",
"*",
"kwargs",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"local_video_path",
")",
"# Setup API client",
"jwplatform_client",... | Function which allows to replace the content of an EXISTING video object.
:param api_key: <string> JWPlatform api-key
:param api_secret: <string> JWPlatform shared-secret
:param local_video_path: <string> Path to media on local machine.
:param video_key: <string> Video's object ID. Can be found within ... | [
"Function",
"which",
"allows",
"to",
"replace",
"the",
"content",
"of",
"an",
"EXISTING",
"video",
"object",
"."
] | train | https://github.com/jwplayer/jwplatform-py/blob/804950158fa04a6b153fc86acae9a3f97ba3bd75/examples/video_s3_replace_video.py#L14-L57 |
jwplayer/jwplatform-py | examples/video_thumbnail_update.py | update_thumbnail | def update_thumbnail(api_key, api_secret, video_key, position=7.0, **kwargs):
"""
Function which updates the thumbnail for an EXISTING video utilizing position parameter.
This function is useful for selecting a new thumbnail from with the already existing video content.
Instead of position parameter, us... | python | def update_thumbnail(api_key, api_secret, video_key, position=7.0, **kwargs):
"""
Function which updates the thumbnail for an EXISTING video utilizing position parameter.
This function is useful for selecting a new thumbnail from with the already existing video content.
Instead of position parameter, us... | [
"def",
"update_thumbnail",
"(",
"api_key",
",",
"api_secret",
",",
"video_key",
",",
"position",
"=",
"7.0",
",",
"*",
"*",
"kwargs",
")",
":",
"jwplatform_client",
"=",
"jwplatform",
".",
"Client",
"(",
"api_key",
",",
"api_secret",
")",
"logging",
".",
"... | Function which updates the thumbnail for an EXISTING video utilizing position parameter.
This function is useful for selecting a new thumbnail from with the already existing video content.
Instead of position parameter, user may opt to utilize thumbnail_index parameter.
Please eee documentation for further ... | [
"Function",
"which",
"updates",
"the",
"thumbnail",
"for",
"an",
"EXISTING",
"video",
"utilizing",
"position",
"parameter",
".",
"This",
"function",
"is",
"useful",
"for",
"selecting",
"a",
"new",
"thumbnail",
"from",
"with",
"the",
"already",
"existing",
"video... | train | https://github.com/jwplayer/jwplatform-py/blob/804950158fa04a6b153fc86acae9a3f97ba3bd75/examples/video_thumbnail_update.py#L11-L35 |
jwplayer/jwplatform-py | examples/video_thumbnail_update.py | update_thumbnail_via_upload | def update_thumbnail_via_upload(api_key, api_secret, video_key, local_video_image_path='', api_format='json',
**kwargs):
"""
Function which updates the thumbnail for a particular video object with a locally saved image.
:param api_key: <string> JWPlatform api-key
:param ... | python | def update_thumbnail_via_upload(api_key, api_secret, video_key, local_video_image_path='', api_format='json',
**kwargs):
"""
Function which updates the thumbnail for a particular video object with a locally saved image.
:param api_key: <string> JWPlatform api-key
:param ... | [
"def",
"update_thumbnail_via_upload",
"(",
"api_key",
",",
"api_secret",
",",
"video_key",
",",
"local_video_image_path",
"=",
"''",
",",
"api_format",
"=",
"'json'",
",",
"*",
"*",
"kwargs",
")",
":",
"jwplatform_client",
"=",
"jwplatform",
".",
"Client",
"(",
... | Function which updates the thumbnail for a particular video object with a locally saved image.
:param api_key: <string> JWPlatform api-key
:param api_secret: <string> JWPlatform shared-secret
:param video_key: <string> Video's object ID. Can be found within JWPlayer Dashboard.
:param local_video_image_... | [
"Function",
"which",
"updates",
"the",
"thumbnail",
"for",
"a",
"particular",
"video",
"object",
"with",
"a",
"locally",
"saved",
"image",
"."
] | train | https://github.com/jwplayer/jwplatform-py/blob/804950158fa04a6b153fc86acae9a3f97ba3bd75/examples/video_thumbnail_update.py#L38-L77 |
jwplayer/jwplatform-py | examples/video_multipart_create.py | run_upload | def run_upload(video_file_path):
"""
Configures all of the needed upload_parameters and sets up all information pertinent
to the video to be uploaded.
:param video_file_path: <str> the absolute path to the video file
"""
upload_parameters = {
'file_path': video_file_path,
'file... | python | def run_upload(video_file_path):
"""
Configures all of the needed upload_parameters and sets up all information pertinent
to the video to be uploaded.
:param video_file_path: <str> the absolute path to the video file
"""
upload_parameters = {
'file_path': video_file_path,
'file... | [
"def",
"run_upload",
"(",
"video_file_path",
")",
":",
"upload_parameters",
"=",
"{",
"'file_path'",
":",
"video_file_path",
",",
"'file_size'",
":",
"os",
".",
"stat",
"(",
"video_file_path",
")",
".",
"st_size",
",",
"'file_name'",
":",
"os",
".",
"path",
... | Configures all of the needed upload_parameters and sets up all information pertinent
to the video to be uploaded.
:param video_file_path: <str> the absolute path to the video file | [
"Configures",
"all",
"of",
"the",
"needed",
"upload_parameters",
"and",
"sets",
"up",
"all",
"information",
"pertinent",
"to",
"the",
"video",
"to",
"be",
"uploaded",
"."
] | train | https://github.com/jwplayer/jwplatform-py/blob/804950158fa04a6b153fc86acae9a3f97ba3bd75/examples/video_multipart_create.py#L20-L73 |
jwplayer/jwplatform-py | examples/video_multipart_create.py | upload_chunk | def upload_chunk(chunk, upload_parameters):
"""
Handles the POST request needed to upload a single portion of the video file.
Serves as a helper method for upload_by_multipart().
The offset used to determine where a chunk begins and ends is updated in the course of
this method's execution.
:par... | python | def upload_chunk(chunk, upload_parameters):
"""
Handles the POST request needed to upload a single portion of the video file.
Serves as a helper method for upload_by_multipart().
The offset used to determine where a chunk begins and ends is updated in the course of
this method's execution.
:par... | [
"def",
"upload_chunk",
"(",
"chunk",
",",
"upload_parameters",
")",
":",
"begin_chunk",
"=",
"upload_parameters",
"[",
"'chunk_offset'",
"]",
"# The next chunk will begin at (begin_chunk + len(chunk)), so the -1 ensures that the ranges do not overlap",
"end_chunk",
"=",
"begin_chun... | Handles the POST request needed to upload a single portion of the video file.
Serves as a helper method for upload_by_multipart().
The offset used to determine where a chunk begins and ends is updated in the course of
this method's execution.
:param chunk: <byte[]> the raw bytes of data from the video ... | [
"Handles",
"the",
"POST",
"request",
"needed",
"to",
"upload",
"a",
"single",
"portion",
"of",
"the",
"video",
"file",
".",
"Serves",
"as",
"a",
"helper",
"method",
"for",
"upload_by_multipart",
"()",
".",
"The",
"offset",
"used",
"to",
"determine",
"where",... | train | https://github.com/jwplayer/jwplatform-py/blob/804950158fa04a6b153fc86acae9a3f97ba3bd75/examples/video_multipart_create.py#L76-L112 |
jwplayer/jwplatform-py | examples/video_list_to_csv.py | make_csv | def make_csv(api_key, api_secret, path_to_csv=None, result_limit=1000, **kwargs):
"""
Function which fetches a video library and writes each video_objects Metadata to CSV. Useful for CMS systems.
:param api_key: <string> JWPlatform api-key
:param api_secret: <string> JWPlatform shared-secret
:param... | python | def make_csv(api_key, api_secret, path_to_csv=None, result_limit=1000, **kwargs):
"""
Function which fetches a video library and writes each video_objects Metadata to CSV. Useful for CMS systems.
:param api_key: <string> JWPlatform api-key
:param api_secret: <string> JWPlatform shared-secret
:param... | [
"def",
"make_csv",
"(",
"api_key",
",",
"api_secret",
",",
"path_to_csv",
"=",
"None",
",",
"result_limit",
"=",
"1000",
",",
"*",
"*",
"kwargs",
")",
":",
"path_to_csv",
"=",
"path_to_csv",
"or",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd... | Function which fetches a video library and writes each video_objects Metadata to CSV. Useful for CMS systems.
:param api_key: <string> JWPlatform api-key
:param api_secret: <string> JWPlatform shared-secret
:param path_to_csv: <string> Local system path to desired CSV. Default will be within current workin... | [
"Function",
"which",
"fetches",
"a",
"video",
"library",
"and",
"writes",
"each",
"video_objects",
"Metadata",
"to",
"CSV",
".",
"Useful",
"for",
"CMS",
"systems",
"."
] | train | https://github.com/jwplayer/jwplatform-py/blob/804950158fa04a6b153fc86acae9a3f97ba3bd75/examples/video_list_to_csv.py#L13-L73 |
jwplayer/jwplatform-py | examples/video_channel_create.py | create_channel | def create_channel(api_key, api_secret, channel_type='manual', **kwargs):
"""
Function which creates a new channel. Channels serve as containers of video/media objects.
:param api_key: <string> JWPlatform api-key
:param api_secret: <string> JWPlatform shared-secret
:param channel_type: <string> REQ... | python | def create_channel(api_key, api_secret, channel_type='manual', **kwargs):
"""
Function which creates a new channel. Channels serve as containers of video/media objects.
:param api_key: <string> JWPlatform api-key
:param api_secret: <string> JWPlatform shared-secret
:param channel_type: <string> REQ... | [
"def",
"create_channel",
"(",
"api_key",
",",
"api_secret",
",",
"channel_type",
"=",
"'manual'",
",",
"*",
"*",
"kwargs",
")",
":",
"jwplatform_client",
"=",
"jwplatform",
".",
"Client",
"(",
"api_key",
",",
"api_secret",
")",
"logging",
".",
"info",
"(",
... | Function which creates a new channel. Channels serve as containers of video/media objects.
:param api_key: <string> JWPlatform api-key
:param api_secret: <string> JWPlatform shared-secret
:param channel_type: <string> REQUIRED Acceptable values include 'manual','dynamic','trending','feed','search'
:par... | [
"Function",
"which",
"creates",
"a",
"new",
"channel",
".",
"Channels",
"serve",
"as",
"containers",
"of",
"video",
"/",
"media",
"objects",
"."
] | train | https://github.com/jwplayer/jwplatform-py/blob/804950158fa04a6b153fc86acae9a3f97ba3bd75/examples/video_channel_create.py#L10-L27 |
jwplayer/jwplatform-py | examples/video_update_custom_params.py | update_custom_params | def update_custom_params(api_key, api_secret, video_key, params):
"""
Function which allows you to update a video's custom params. Custom params are indicated by key-values of
"custom.<key>" = "<value>" so they must be provided as a dictionary and passed to the platform API call.
:param api_key: <strin... | python | def update_custom_params(api_key, api_secret, video_key, params):
"""
Function which allows you to update a video's custom params. Custom params are indicated by key-values of
"custom.<key>" = "<value>" so they must be provided as a dictionary and passed to the platform API call.
:param api_key: <strin... | [
"def",
"update_custom_params",
"(",
"api_key",
",",
"api_secret",
",",
"video_key",
",",
"params",
")",
":",
"formatted_params",
"=",
"{",
"'custom.{}'",
".",
"format",
"(",
"k",
")",
":",
"v",
"for",
"k",
",",
"v",
"in",
"params",
".",
"items",
"(",
"... | Function which allows you to update a video's custom params. Custom params are indicated by key-values of
"custom.<key>" = "<value>" so they must be provided as a dictionary and passed to the platform API call.
:param api_key: <string> JWPlatform api-key
:param api_secret: <string> JWPlatform shared-secret... | [
"Function",
"which",
"allows",
"you",
"to",
"update",
"a",
"video",
"s",
"custom",
"params",
".",
"Custom",
"params",
"are",
"indicated",
"by",
"key",
"-",
"values",
"of",
"custom",
".",
"<key",
">",
"=",
"<value",
">",
"so",
"they",
"must",
"be",
"pro... | train | https://github.com/jwplayer/jwplatform-py/blob/804950158fa04a6b153fc86acae9a3f97ba3bd75/examples/video_update_custom_params.py#L13-L40 |
kuszaj/claptcha | claptcha/claptcha.py | Claptcha.image | def image(self):
r"""
Tuple with a CAPTCHA text and a Image object.
Images are generated on the fly, using given text source, TTF font and
other parameters passable through __init__. All letters in used text
are morphed. Also a line is morphed and pased onto CAPTCHA text.
... | python | def image(self):
r"""
Tuple with a CAPTCHA text and a Image object.
Images are generated on the fly, using given text source, TTF font and
other parameters passable through __init__. All letters in used text
are morphed. Also a line is morphed and pased onto CAPTCHA text.
... | [
"def",
"image",
"(",
"self",
")",
":",
"text",
"=",
"self",
".",
"text",
"w",
",",
"h",
"=",
"self",
".",
"font",
".",
"getsize",
"(",
"text",
")",
"margin_x",
"=",
"round",
"(",
"self",
".",
"margin_x",
"*",
"w",
"/",
"self",
".",
"w",
")",
... | r"""
Tuple with a CAPTCHA text and a Image object.
Images are generated on the fly, using given text source, TTF font and
other parameters passable through __init__. All letters in used text
are morphed. Also a line is morphed and pased onto CAPTCHA text.
Additionaly, if self.no... | [
"r",
"Tuple",
"with",
"a",
"CAPTCHA",
"text",
"and",
"a",
"Image",
"object",
"."
] | train | https://github.com/kuszaj/claptcha/blob/0245f656e6febf34e32b5238196e992929df42c7/claptcha/claptcha.py#L88-L125 |
kuszaj/claptcha | claptcha/claptcha.py | Claptcha.bytes | def bytes(self):
r"""
Tuple with a CAPTCHA text and a BytesIO object.
Property calls self.image and saves image contents in a BytesIO
instance, returning CAPTCHA text and BytesIO as a tuple.
See: image.
:returns: ``tuple`` (CAPTCHA text, BytesIO object)
"""
... | python | def bytes(self):
r"""
Tuple with a CAPTCHA text and a BytesIO object.
Property calls self.image and saves image contents in a BytesIO
instance, returning CAPTCHA text and BytesIO as a tuple.
See: image.
:returns: ``tuple`` (CAPTCHA text, BytesIO object)
"""
... | [
"def",
"bytes",
"(",
"self",
")",
":",
"text",
",",
"image",
"=",
"self",
".",
"image",
"bytes",
"=",
"BytesIO",
"(",
")",
"image",
".",
"save",
"(",
"bytes",
",",
"format",
"=",
"self",
".",
"format",
")",
"bytes",
".",
"seek",
"(",
"0",
")",
... | r"""
Tuple with a CAPTCHA text and a BytesIO object.
Property calls self.image and saves image contents in a BytesIO
instance, returning CAPTCHA text and BytesIO as a tuple.
See: image.
:returns: ``tuple`` (CAPTCHA text, BytesIO object) | [
"r",
"Tuple",
"with",
"a",
"CAPTCHA",
"text",
"and",
"a",
"BytesIO",
"object",
"."
] | train | https://github.com/kuszaj/claptcha/blob/0245f656e6febf34e32b5238196e992929df42c7/claptcha/claptcha.py#L128-L142 |
kuszaj/claptcha | claptcha/claptcha.py | Claptcha.write | def write(self, file):
r"""
Save CAPTCHA image in given filepath.
Property calls self.image and saves image contents in a file,
returning CAPTCHA text and filepath as a tuple.
See: image.
:param file:
Path to file, where CAPTCHA image will be saved.
... | python | def write(self, file):
r"""
Save CAPTCHA image in given filepath.
Property calls self.image and saves image contents in a file,
returning CAPTCHA text and filepath as a tuple.
See: image.
:param file:
Path to file, where CAPTCHA image will be saved.
... | [
"def",
"write",
"(",
"self",
",",
"file",
")",
":",
"text",
",",
"image",
"=",
"self",
".",
"image",
"image",
".",
"save",
"(",
"file",
",",
"format",
"=",
"self",
".",
"format",
")",
"return",
"(",
"text",
",",
"file",
")"
] | r"""
Save CAPTCHA image in given filepath.
Property calls self.image and saves image contents in a file,
returning CAPTCHA text and filepath as a tuple.
See: image.
:param file:
Path to file, where CAPTCHA image will be saved.
:returns: ``tuple`` (CAPTCHA te... | [
"r",
"Save",
"CAPTCHA",
"image",
"in",
"given",
"filepath",
"."
] | train | https://github.com/kuszaj/claptcha/blob/0245f656e6febf34e32b5238196e992929df42c7/claptcha/claptcha.py#L144-L158 |
kuszaj/claptcha | claptcha/claptcha.py | Claptcha.text | def text(self):
"""Text received from self.source."""
if isinstance(self.source, str):
return self.source
else:
return self.source() | python | def text(self):
"""Text received from self.source."""
if isinstance(self.source, str):
return self.source
else:
return self.source() | [
"def",
"text",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"source",
",",
"str",
")",
":",
"return",
"self",
".",
"source",
"else",
":",
"return",
"self",
".",
"source",
"(",
")"
] | Text received from self.source. | [
"Text",
"received",
"from",
"self",
".",
"source",
"."
] | train | https://github.com/kuszaj/claptcha/blob/0245f656e6febf34e32b5238196e992929df42c7/claptcha/claptcha.py#L172-L177 |
kuszaj/claptcha | claptcha/claptcha.py | Claptcha._writeText | def _writeText(self, image, text, pos):
"""Write morphed text in Image object."""
offset = 0
x, y = pos
for c in text:
# Write letter
c_size = self.font.getsize(c)
c_image = Image.new('RGBA', c_size, (0, 0, 0, 0))
c_draw = ImageDraw.Draw(c... | python | def _writeText(self, image, text, pos):
"""Write morphed text in Image object."""
offset = 0
x, y = pos
for c in text:
# Write letter
c_size = self.font.getsize(c)
c_image = Image.new('RGBA', c_size, (0, 0, 0, 0))
c_draw = ImageDraw.Draw(c... | [
"def",
"_writeText",
"(",
"self",
",",
"image",
",",
"text",
",",
"pos",
")",
":",
"offset",
"=",
"0",
"x",
",",
"y",
"=",
"pos",
"for",
"c",
"in",
"text",
":",
"# Write letter",
"c_size",
"=",
"self",
".",
"font",
".",
"getsize",
"(",
"c",
")",
... | Write morphed text in Image object. | [
"Write",
"morphed",
"text",
"in",
"Image",
"object",
"."
] | train | https://github.com/kuszaj/claptcha/blob/0245f656e6febf34e32b5238196e992929df42c7/claptcha/claptcha.py#L267-L284 |
kuszaj/claptcha | claptcha/claptcha.py | Claptcha._drawLine | def _drawLine(self, image):
"""Draw morphed line in Image object."""
w, h = image.size
w *= 5
h *= 5
l_image = Image.new('RGBA', (w, h), (0, 0, 0, 0))
l_draw = ImageDraw.Draw(l_image)
x1 = int(w * random.uniform(0, 0.1))
y1 = int(h * random.uniform(0, 1)... | python | def _drawLine(self, image):
"""Draw morphed line in Image object."""
w, h = image.size
w *= 5
h *= 5
l_image = Image.new('RGBA', (w, h), (0, 0, 0, 0))
l_draw = ImageDraw.Draw(l_image)
x1 = int(w * random.uniform(0, 0.1))
y1 = int(h * random.uniform(0, 1)... | [
"def",
"_drawLine",
"(",
"self",
",",
"image",
")",
":",
"w",
",",
"h",
"=",
"image",
".",
"size",
"w",
"*=",
"5",
"h",
"*=",
"5",
"l_image",
"=",
"Image",
".",
"new",
"(",
"'RGBA'",
",",
"(",
"w",
",",
"h",
")",
",",
"(",
"0",
",",
"0",
... | Draw morphed line in Image object. | [
"Draw",
"morphed",
"line",
"in",
"Image",
"object",
"."
] | train | https://github.com/kuszaj/claptcha/blob/0245f656e6febf34e32b5238196e992929df42c7/claptcha/claptcha.py#L286-L312 |
kuszaj/claptcha | claptcha/claptcha.py | Claptcha._whiteNoise | def _whiteNoise(self, size):
"""Generate white noise and merge it with given Image object."""
if self.noise > 0.003921569: # 1./255.
w, h = size
pixel = (lambda noise: round(255 * random.uniform(1-noise, 1)))
n_image = Image.new('RGB', size, (0, 0, 0, 0))
... | python | def _whiteNoise(self, size):
"""Generate white noise and merge it with given Image object."""
if self.noise > 0.003921569: # 1./255.
w, h = size
pixel = (lambda noise: round(255 * random.uniform(1-noise, 1)))
n_image = Image.new('RGB', size, (0, 0, 0, 0))
... | [
"def",
"_whiteNoise",
"(",
"self",
",",
"size",
")",
":",
"if",
"self",
".",
"noise",
">",
"0.003921569",
":",
"# 1./255.",
"w",
",",
"h",
"=",
"size",
"pixel",
"=",
"(",
"lambda",
"noise",
":",
"round",
"(",
"255",
"*",
"random",
".",
"uniform",
"... | Generate white noise and merge it with given Image object. | [
"Generate",
"white",
"noise",
"and",
"merge",
"it",
"with",
"given",
"Image",
"object",
"."
] | train | https://github.com/kuszaj/claptcha/blob/0245f656e6febf34e32b5238196e992929df42c7/claptcha/claptcha.py#L314-L327 |
kuszaj/claptcha | claptcha/claptcha.py | Claptcha._rndLetterTransform | def _rndLetterTransform(self, image):
"""Randomly morph a single character."""
w, h = image.size
dx = w * random.uniform(0.2, 0.7)
dy = h * random.uniform(0.2, 0.7)
x1, y1 = self.__class__._rndPointDisposition(dx, dy)
x2, y2 = self.__class__._rndPointDisposition(dx, dy)... | python | def _rndLetterTransform(self, image):
"""Randomly morph a single character."""
w, h = image.size
dx = w * random.uniform(0.2, 0.7)
dy = h * random.uniform(0.2, 0.7)
x1, y1 = self.__class__._rndPointDisposition(dx, dy)
x2, y2 = self.__class__._rndPointDisposition(dx, dy)... | [
"def",
"_rndLetterTransform",
"(",
"self",
",",
"image",
")",
":",
"w",
",",
"h",
"=",
"image",
".",
"size",
"dx",
"=",
"w",
"*",
"random",
".",
"uniform",
"(",
"0.2",
",",
"0.7",
")",
"dy",
"=",
"h",
"*",
"random",
".",
"uniform",
"(",
"0.2",
... | Randomly morph a single character. | [
"Randomly",
"morph",
"a",
"single",
"character",
"."
] | train | https://github.com/kuszaj/claptcha/blob/0245f656e6febf34e32b5238196e992929df42c7/claptcha/claptcha.py#L329-L345 |
kuszaj/claptcha | claptcha/claptcha.py | Claptcha._rndPointDisposition | def _rndPointDisposition(dx, dy):
"""Return random disposition point."""
x = int(random.uniform(-dx, dx))
y = int(random.uniform(-dy, dy))
return (x, y) | python | def _rndPointDisposition(dx, dy):
"""Return random disposition point."""
x = int(random.uniform(-dx, dx))
y = int(random.uniform(-dy, dy))
return (x, y) | [
"def",
"_rndPointDisposition",
"(",
"dx",
",",
"dy",
")",
":",
"x",
"=",
"int",
"(",
"random",
".",
"uniform",
"(",
"-",
"dx",
",",
"dx",
")",
")",
"y",
"=",
"int",
"(",
"random",
".",
"uniform",
"(",
"-",
"dy",
",",
"dy",
")",
")",
"return",
... | Return random disposition point. | [
"Return",
"random",
"disposition",
"point",
"."
] | train | https://github.com/kuszaj/claptcha/blob/0245f656e6febf34e32b5238196e992929df42c7/claptcha/claptcha.py#L363-L367 |
kuszaj/claptcha | claptcha/claptcha.py | Claptcha._quadPoints | def _quadPoints(size, disp1, disp2):
"""Return points for QUAD transformation."""
w, h = size
x1, y1 = disp1
x2, y2 = disp2
return (
x1, -y1,
-x1, h + y2,
w + x2, h - y2,
w - x2, y1
) | python | def _quadPoints(size, disp1, disp2):
"""Return points for QUAD transformation."""
w, h = size
x1, y1 = disp1
x2, y2 = disp2
return (
x1, -y1,
-x1, h + y2,
w + x2, h - y2,
w - x2, y1
) | [
"def",
"_quadPoints",
"(",
"size",
",",
"disp1",
",",
"disp2",
")",
":",
"w",
",",
"h",
"=",
"size",
"x1",
",",
"y1",
"=",
"disp1",
"x2",
",",
"y2",
"=",
"disp2",
"return",
"(",
"x1",
",",
"-",
"y1",
",",
"-",
"x1",
",",
"h",
"+",
"y2",
","... | Return points for QUAD transformation. | [
"Return",
"points",
"for",
"QUAD",
"transformation",
"."
] | train | https://github.com/kuszaj/claptcha/blob/0245f656e6febf34e32b5238196e992929df42c7/claptcha/claptcha.py#L370-L381 |
marshmallow-code/apispec-webframeworks | src/apispec_webframeworks/bottle.py | BottlePlugin.path_helper | def path_helper(self, operations, view, **kwargs):
"""Path helper that allows passing a bottle view function."""
operations.update(yaml_utils.load_operations_from_docstring(view.__doc__))
app = kwargs.get('app', _default_app)
route = self._route_for_view(app, view)
return self.bo... | python | def path_helper(self, operations, view, **kwargs):
"""Path helper that allows passing a bottle view function."""
operations.update(yaml_utils.load_operations_from_docstring(view.__doc__))
app = kwargs.get('app', _default_app)
route = self._route_for_view(app, view)
return self.bo... | [
"def",
"path_helper",
"(",
"self",
",",
"operations",
",",
"view",
",",
"*",
"*",
"kwargs",
")",
":",
"operations",
".",
"update",
"(",
"yaml_utils",
".",
"load_operations_from_docstring",
"(",
"view",
".",
"__doc__",
")",
")",
"app",
"=",
"kwargs",
".",
... | Path helper that allows passing a bottle view function. | [
"Path",
"helper",
"that",
"allows",
"passing",
"a",
"bottle",
"view",
"function",
"."
] | train | https://github.com/marshmallow-code/apispec-webframeworks/blob/21b0b4135c073d2ada47a4228377e63bc03ac7f9/src/apispec_webframeworks/bottle.py#L56-L61 |
marshmallow-code/apispec-webframeworks | src/apispec_webframeworks/flask.py | FlaskPlugin.path_helper | def path_helper(self, operations, view, app=None, **kwargs):
"""Path helper that allows passing a Flask view function."""
rule = self._rule_for_view(view, app=app)
operations.update(yaml_utils.load_operations_from_docstring(view.__doc__))
if hasattr(view, 'view_class') and issubclass(vie... | python | def path_helper(self, operations, view, app=None, **kwargs):
"""Path helper that allows passing a Flask view function."""
rule = self._rule_for_view(view, app=app)
operations.update(yaml_utils.load_operations_from_docstring(view.__doc__))
if hasattr(view, 'view_class') and issubclass(vie... | [
"def",
"path_helper",
"(",
"self",
",",
"operations",
",",
"view",
",",
"app",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"rule",
"=",
"self",
".",
"_rule_for_view",
"(",
"view",
",",
"app",
"=",
"app",
")",
"operations",
".",
"update",
"(",
"... | Path helper that allows passing a Flask view function. | [
"Path",
"helper",
"that",
"allows",
"passing",
"a",
"Flask",
"view",
"function",
"."
] | train | https://github.com/marshmallow-code/apispec-webframeworks/blob/21b0b4135c073d2ada47a4228377e63bc03ac7f9/src/apispec_webframeworks/flask.py#L113-L123 |
marshmallow-code/apispec-webframeworks | src/apispec_webframeworks/tornado.py | TornadoPlugin._operations_from_methods | def _operations_from_methods(handler_class):
"""Generator of operations described in handler's http methods
:param handler_class:
:type handler_class: RequestHandler descendant
"""
for httpmethod in yaml_utils.PATH_KEYS:
method = getattr(handler_class, httpmethod)
... | python | def _operations_from_methods(handler_class):
"""Generator of operations described in handler's http methods
:param handler_class:
:type handler_class: RequestHandler descendant
"""
for httpmethod in yaml_utils.PATH_KEYS:
method = getattr(handler_class, httpmethod)
... | [
"def",
"_operations_from_methods",
"(",
"handler_class",
")",
":",
"for",
"httpmethod",
"in",
"yaml_utils",
".",
"PATH_KEYS",
":",
"method",
"=",
"getattr",
"(",
"handler_class",
",",
"httpmethod",
")",
"operation_data",
"=",
"yaml_utils",
".",
"load_yaml_from_docst... | Generator of operations described in handler's http methods
:param handler_class:
:type handler_class: RequestHandler descendant | [
"Generator",
"of",
"operations",
"described",
"in",
"handler",
"s",
"http",
"methods"
] | train | https://github.com/marshmallow-code/apispec-webframeworks/blob/21b0b4135c073d2ada47a4228377e63bc03ac7f9/src/apispec_webframeworks/tornado.py#L45-L56 |
marshmallow-code/apispec-webframeworks | src/apispec_webframeworks/tornado.py | TornadoPlugin.tornadopath2openapi | def tornadopath2openapi(urlspec, method):
"""Convert Tornado URLSpec to OpenAPI-compliant path.
:param urlspec:
:type urlspec: URLSpec
:param method: Handler http method
:type method: function
"""
if sys.version_info >= (3, 3):
args = list(inspect.sig... | python | def tornadopath2openapi(urlspec, method):
"""Convert Tornado URLSpec to OpenAPI-compliant path.
:param urlspec:
:type urlspec: URLSpec
:param method: Handler http method
:type method: function
"""
if sys.version_info >= (3, 3):
args = list(inspect.sig... | [
"def",
"tornadopath2openapi",
"(",
"urlspec",
",",
"method",
")",
":",
"if",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
"3",
")",
":",
"args",
"=",
"list",
"(",
"inspect",
".",
"signature",
"(",
"method",
")",
".",
"parameters",
".",
"keys",
"(... | Convert Tornado URLSpec to OpenAPI-compliant path.
:param urlspec:
:type urlspec: URLSpec
:param method: Handler http method
:type method: function | [
"Convert",
"Tornado",
"URLSpec",
"to",
"OpenAPI",
"-",
"compliant",
"path",
"."
] | train | https://github.com/marshmallow-code/apispec-webframeworks/blob/21b0b4135c073d2ada47a4228377e63bc03ac7f9/src/apispec_webframeworks/tornado.py#L59-L81 |
marshmallow-code/apispec-webframeworks | src/apispec_webframeworks/tornado.py | TornadoPlugin.path_helper | def path_helper(self, operations, urlspec, **kwargs):
"""Path helper that allows passing a Tornado URLSpec or tuple."""
if not isinstance(urlspec, URLSpec):
urlspec = URLSpec(*urlspec)
for operation in self._operations_from_methods(urlspec.handler_class):
operations.updat... | python | def path_helper(self, operations, urlspec, **kwargs):
"""Path helper that allows passing a Tornado URLSpec or tuple."""
if not isinstance(urlspec, URLSpec):
urlspec = URLSpec(*urlspec)
for operation in self._operations_from_methods(urlspec.handler_class):
operations.updat... | [
"def",
"path_helper",
"(",
"self",
",",
"operations",
",",
"urlspec",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"urlspec",
",",
"URLSpec",
")",
":",
"urlspec",
"=",
"URLSpec",
"(",
"*",
"urlspec",
")",
"for",
"operation",
"in",... | Path helper that allows passing a Tornado URLSpec or tuple. | [
"Path",
"helper",
"that",
"allows",
"passing",
"a",
"Tornado",
"URLSpec",
"or",
"tuple",
"."
] | train | https://github.com/marshmallow-code/apispec-webframeworks/blob/21b0b4135c073d2ada47a4228377e63bc03ac7f9/src/apispec_webframeworks/tornado.py#L92-L104 |
onelogin/onelogin-python-sdk | src/onelogin/api/client.py | OneLoginClient.generate_mfa_token | def generate_mfa_token(self, user_id, expires_in=259200, reusable=False):
"""
Use to generate a temporary MFA token that can be used in place of other MFA tokens for a set time period.
For example, use this token for account recovery.
:param user_id: Id of the user
:type user_id... | python | def generate_mfa_token(self, user_id, expires_in=259200, reusable=False):
"""
Use to generate a temporary MFA token that can be used in place of other MFA tokens for a set time period.
For example, use this token for account recovery.
:param user_id: Id of the user
:type user_id... | [
"def",
"generate_mfa_token",
"(",
"self",
",",
"user_id",
",",
"expires_in",
"=",
"259200",
",",
"reusable",
"=",
"False",
")",
":",
"self",
".",
"clean_error",
"(",
")",
"try",
":",
"url",
"=",
"self",
".",
"get_url",
"(",
"Constants",
".",
"GENERATE_MF... | Use to generate a temporary MFA token that can be used in place of other MFA tokens for a set time period.
For example, use this token for account recovery.
:param user_id: Id of the user
:type user_id: int
:param expires_in: Set the duration of the token in seconds.
... | [
"Use",
"to",
"generate",
"a",
"temporary",
"MFA",
"token",
"that",
"can",
"be",
"used",
"in",
"place",
"of",
"other",
"MFA",
"tokens",
"for",
"a",
"set",
"time",
"period",
".",
"For",
"example",
"use",
"this",
"token",
"for",
"account",
"recovery",
"."
] | train | https://github.com/onelogin/onelogin-python-sdk/blob/2891b2efbd0a94298611f7c9c220a1f32126d339/src/onelogin/api/client.py#L1039-L1081 |
artefactual-labs/mets-reader-writer | metsrw/plugins/premisrw/utils.py | camel_to_snake | def camel_to_snake(camel):
"""Convert camelCase to snake_case."""
ret = []
last_lower = False
for char in camel:
current_upper = char.upper() == char
if current_upper and last_lower:
ret.append("_")
ret.append(char.lower())
else:
ret.append(cha... | python | def camel_to_snake(camel):
"""Convert camelCase to snake_case."""
ret = []
last_lower = False
for char in camel:
current_upper = char.upper() == char
if current_upper and last_lower:
ret.append("_")
ret.append(char.lower())
else:
ret.append(cha... | [
"def",
"camel_to_snake",
"(",
"camel",
")",
":",
"ret",
"=",
"[",
"]",
"last_lower",
"=",
"False",
"for",
"char",
"in",
"camel",
":",
"current_upper",
"=",
"char",
".",
"upper",
"(",
")",
"==",
"char",
"if",
"current_upper",
"and",
"last_lower",
":",
"... | Convert camelCase to snake_case. | [
"Convert",
"camelCase",
"to",
"snake_case",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/plugins/premisrw/utils.py#L69-L81 |
artefactual-labs/mets-reader-writer | metsrw/metadata.py | IdGenerator.register_id | def register_id(self, id_string):
"""Register a manually assigned id as used, to avoid collisions.
"""
try:
prefix, count = id_string.rsplit("_", 1)
count = int(count)
except ValueError:
# We don't need to worry about ids that don't match our pattern
... | python | def register_id(self, id_string):
"""Register a manually assigned id as used, to avoid collisions.
"""
try:
prefix, count = id_string.rsplit("_", 1)
count = int(count)
except ValueError:
# We don't need to worry about ids that don't match our pattern
... | [
"def",
"register_id",
"(",
"self",
",",
"id_string",
")",
":",
"try",
":",
"prefix",
",",
"count",
"=",
"id_string",
".",
"rsplit",
"(",
"\"_\"",
",",
"1",
")",
"count",
"=",
"int",
"(",
"count",
")",
"except",
"ValueError",
":",
"# We don't need to worr... | Register a manually assigned id as used, to avoid collisions. | [
"Register",
"a",
"manually",
"assigned",
"id",
"as",
"used",
"to",
"avoid",
"collisions",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/metadata.py#L35-L46 |
artefactual-labs/mets-reader-writer | metsrw/metadata.py | AMDSec.parse | def parse(cls, root):
"""
Create a new AMDSec by parsing root.
:param root: Element or ElementTree to be parsed into an object.
"""
if root.tag != utils.lxmlns("mets") + "amdSec":
raise exceptions.ParseError(
"AMDSec can only parse amdSec elements wit... | python | def parse(cls, root):
"""
Create a new AMDSec by parsing root.
:param root: Element or ElementTree to be parsed into an object.
"""
if root.tag != utils.lxmlns("mets") + "amdSec":
raise exceptions.ParseError(
"AMDSec can only parse amdSec elements wit... | [
"def",
"parse",
"(",
"cls",
",",
"root",
")",
":",
"if",
"root",
".",
"tag",
"!=",
"utils",
".",
"lxmlns",
"(",
"\"mets\"",
")",
"+",
"\"amdSec\"",
":",
"raise",
"exceptions",
".",
"ParseError",
"(",
"\"AMDSec can only parse amdSec elements with METS namespace.\... | Create a new AMDSec by parsing root.
:param root: Element or ElementTree to be parsed into an object. | [
"Create",
"a",
"new",
"AMDSec",
"by",
"parsing",
"root",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/metadata.py#L88-L103 |
artefactual-labs/mets-reader-writer | metsrw/metadata.py | AMDSec.serialize | def serialize(self, now=None):
"""
Serialize this amdSec and all children to lxml Element and return it.
:param str now: Default value for CREATED in children if none set
:return: amdSec Element with all children
"""
if self._tree is not None:
return self._tr... | python | def serialize(self, now=None):
"""
Serialize this amdSec and all children to lxml Element and return it.
:param str now: Default value for CREATED in children if none set
:return: amdSec Element with all children
"""
if self._tree is not None:
return self._tr... | [
"def",
"serialize",
"(",
"self",
",",
"now",
"=",
"None",
")",
":",
"if",
"self",
".",
"_tree",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_tree",
"el",
"=",
"etree",
".",
"Element",
"(",
"utils",
".",
"lxmlns",
"(",
"\"mets\"",
")",
"+",
... | Serialize this amdSec and all children to lxml Element and return it.
:param str now: Default value for CREATED in children if none set
:return: amdSec Element with all children | [
"Serialize",
"this",
"amdSec",
"and",
"all",
"children",
"to",
"lxml",
"Element",
"and",
"return",
"it",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/metadata.py#L105-L118 |
artefactual-labs/mets-reader-writer | metsrw/metadata.py | AltRecordID.parse | def parse(cls, element):
"""
Create a new AltRecordID by parsing root.
:param element: Element to be parsed into an AltRecordID.
:raises exceptions.ParseError: If element is not a valid altRecordID.
"""
if element.tag != cls.ALT_RECORD_ID_TAG:
raise exception... | python | def parse(cls, element):
"""
Create a new AltRecordID by parsing root.
:param element: Element to be parsed into an AltRecordID.
:raises exceptions.ParseError: If element is not a valid altRecordID.
"""
if element.tag != cls.ALT_RECORD_ID_TAG:
raise exception... | [
"def",
"parse",
"(",
"cls",
",",
"element",
")",
":",
"if",
"element",
".",
"tag",
"!=",
"cls",
".",
"ALT_RECORD_ID_TAG",
":",
"raise",
"exceptions",
".",
"ParseError",
"(",
"u\"AltRecordID got unexpected tag {}; expected {}\"",
".",
"format",
"(",
"element",
".... | Create a new AltRecordID by parsing root.
:param element: Element to be parsed into an AltRecordID.
:raises exceptions.ParseError: If element is not a valid altRecordID. | [
"Create",
"a",
"new",
"AltRecordID",
"by",
"parsing",
"root",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/metadata.py#L142-L156 |
artefactual-labs/mets-reader-writer | metsrw/metadata.py | Agent.parse | def parse(cls, element):
"""
Create a new Agent by parsing root.
:param element: Element to be parsed into an Agent.
:raises exceptions.ParseError: If element is not a valid agent.
"""
if element.tag != cls.AGENT_TAG:
raise exceptions.ParseError(
... | python | def parse(cls, element):
"""
Create a new Agent by parsing root.
:param element: Element to be parsed into an Agent.
:raises exceptions.ParseError: If element is not a valid agent.
"""
if element.tag != cls.AGENT_TAG:
raise exceptions.ParseError(
... | [
"def",
"parse",
"(",
"cls",
",",
"element",
")",
":",
"if",
"element",
".",
"tag",
"!=",
"cls",
".",
"AGENT_TAG",
":",
"raise",
"exceptions",
".",
"ParseError",
"(",
"u\"Agent got unexpected tag {}; expected {}\"",
".",
"format",
"(",
"element",
".",
"tag",
... | Create a new Agent by parsing root.
:param element: Element to be parsed into an Agent.
:raises exceptions.ParseError: If element is not a valid agent. | [
"Create",
"a",
"new",
"Agent",
"by",
"parsing",
"root",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/metadata.py#L211-L240 |
artefactual-labs/mets-reader-writer | metsrw/metadata.py | SubSection.get_status | def get_status(self):
"""
Returns the STATUS when serializing.
Calculates based on the subsection type and if it's replacing anything.
:returns: None or the STATUS string.
"""
if self.status is not None:
return self.status
if self.subsection == "dmdS... | python | def get_status(self):
"""
Returns the STATUS when serializing.
Calculates based on the subsection type and if it's replacing anything.
:returns: None or the STATUS string.
"""
if self.status is not None:
return self.status
if self.subsection == "dmdS... | [
"def",
"get_status",
"(",
"self",
")",
":",
"if",
"self",
".",
"status",
"is",
"not",
"None",
":",
"return",
"self",
".",
"status",
"if",
"self",
".",
"subsection",
"==",
"\"dmdSec\"",
":",
"if",
"self",
".",
"older",
"is",
"None",
":",
"return",
"\"... | Returns the STATUS when serializing.
Calculates based on the subsection type and if it's replacing anything.
:returns: None or the STATUS string. | [
"Returns",
"the",
"STATUS",
"when",
"serializing",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/metadata.py#L327-L348 |
artefactual-labs/mets-reader-writer | metsrw/metadata.py | SubSection.replace_with | def replace_with(self, new_subsection):
"""
Replace this SubSection with new_subsection.
Replacing SubSection must be the same time. That is, you can only
replace a dmdSec with another dmdSec, or a rightsMD with a rightsMD etc.
:param new_subsection: Updated version of this Su... | python | def replace_with(self, new_subsection):
"""
Replace this SubSection with new_subsection.
Replacing SubSection must be the same time. That is, you can only
replace a dmdSec with another dmdSec, or a rightsMD with a rightsMD etc.
:param new_subsection: Updated version of this Su... | [
"def",
"replace_with",
"(",
"self",
",",
"new_subsection",
")",
":",
"if",
"self",
".",
"subsection",
"!=",
"new_subsection",
".",
"subsection",
":",
"raise",
"exceptions",
".",
"MetsError",
"(",
"\"Must replace a SubSection with one of the same type.\"",
")",
"# TODO... | Replace this SubSection with new_subsection.
Replacing SubSection must be the same time. That is, you can only
replace a dmdSec with another dmdSec, or a rightsMD with a rightsMD etc.
:param new_subsection: Updated version of this SubSection
:type new_subsection: :class:`SubSection` | [
"Replace",
"this",
"SubSection",
"with",
"new_subsection",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/metadata.py#L350-L367 |
artefactual-labs/mets-reader-writer | metsrw/metadata.py | SubSection.parse | def parse(cls, root):
"""
Create a new SubSection by parsing root.
:param root: Element or ElementTree to be parsed into an object.
:raises exceptions.ParseError: If root's tag is not in :const:`SubSection.ALLOWED_SUBSECTIONS`.
:raises exceptions.ParseError: If the first child o... | python | def parse(cls, root):
"""
Create a new SubSection by parsing root.
:param root: Element or ElementTree to be parsed into an object.
:raises exceptions.ParseError: If root's tag is not in :const:`SubSection.ALLOWED_SUBSECTIONS`.
:raises exceptions.ParseError: If the first child o... | [
"def",
"parse",
"(",
"cls",
",",
"root",
")",
":",
"subsection",
"=",
"root",
".",
"tag",
".",
"replace",
"(",
"utils",
".",
"lxmlns",
"(",
"\"mets\"",
")",
",",
"\"\"",
",",
"1",
")",
"if",
"subsection",
"not",
"in",
"cls",
".",
"ALLOWED_SUBSECTIONS... | Create a new SubSection by parsing root.
:param root: Element or ElementTree to be parsed into an object.
:raises exceptions.ParseError: If root's tag is not in :const:`SubSection.ALLOWED_SUBSECTIONS`.
:raises exceptions.ParseError: If the first child of root is not mdRef or mdWrap. | [
"Create",
"a",
"new",
"SubSection",
"by",
"parsing",
"root",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/metadata.py#L370-L400 |
artefactual-labs/mets-reader-writer | metsrw/metadata.py | SubSection.serialize | def serialize(self, now=None):
"""
Serialize this SubSection and all children to lxml Element and return it.
:param str now: Default value for CREATED if none set
:return: dmdSec/techMD/rightsMD/sourceMD/digiprovMD Element with all children
"""
created = self.created if ... | python | def serialize(self, now=None):
"""
Serialize this SubSection and all children to lxml Element and return it.
:param str now: Default value for CREATED if none set
:return: dmdSec/techMD/rightsMD/sourceMD/digiprovMD Element with all children
"""
created = self.created if ... | [
"def",
"serialize",
"(",
"self",
",",
"now",
"=",
"None",
")",
":",
"created",
"=",
"self",
".",
"created",
"if",
"self",
".",
"created",
"is",
"not",
"None",
"else",
"now",
"el",
"=",
"etree",
".",
"Element",
"(",
"utils",
".",
"lxmlns",
"(",
"\"m... | Serialize this SubSection and all children to lxml Element and return it.
:param str now: Default value for CREATED if none set
:return: dmdSec/techMD/rightsMD/sourceMD/digiprovMD Element with all children | [
"Serialize",
"this",
"SubSection",
"and",
"all",
"children",
"to",
"lxml",
"Element",
"and",
"return",
"it",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/metadata.py#L402-L418 |
artefactual-labs/mets-reader-writer | metsrw/metadata.py | MDRef.parse | def parse(cls, root):
"""
Create a new MDWrap by parsing root.
:param root: Element or ElementTree to be parsed into a MDWrap.
"""
if root.tag != utils.lxmlns("mets") + "mdRef":
raise exceptions.ParseError(
"MDRef can only parse mdRef elements with ME... | python | def parse(cls, root):
"""
Create a new MDWrap by parsing root.
:param root: Element or ElementTree to be parsed into a MDWrap.
"""
if root.tag != utils.lxmlns("mets") + "mdRef":
raise exceptions.ParseError(
"MDRef can only parse mdRef elements with ME... | [
"def",
"parse",
"(",
"cls",
",",
"root",
")",
":",
"if",
"root",
".",
"tag",
"!=",
"utils",
".",
"lxmlns",
"(",
"\"mets\"",
")",
"+",
"\"mdRef\"",
":",
"raise",
"exceptions",
".",
"ParseError",
"(",
"\"MDRef can only parse mdRef elements with METS namespace.\"",... | Create a new MDWrap by parsing root.
:param root: Element or ElementTree to be parsed into a MDWrap. | [
"Create",
"a",
"new",
"MDWrap",
"by",
"parsing",
"root",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/metadata.py#L449-L480 |
artefactual-labs/mets-reader-writer | metsrw/metadata.py | MDWrap.parse | def parse(cls, root):
"""
Create a new MDWrap by parsing root.
:param root: Element or ElementTree to be parsed into a MDWrap.
:raises exceptions.ParseError: If mdWrap does not contain MDTYPE
:raises exceptions.ParseError: If xmlData contains no children
"""
if r... | python | def parse(cls, root):
"""
Create a new MDWrap by parsing root.
:param root: Element or ElementTree to be parsed into a MDWrap.
:raises exceptions.ParseError: If mdWrap does not contain MDTYPE
:raises exceptions.ParseError: If xmlData contains no children
"""
if r... | [
"def",
"parse",
"(",
"cls",
",",
"root",
")",
":",
"if",
"root",
".",
"tag",
"!=",
"utils",
".",
"lxmlns",
"(",
"\"mets\"",
")",
"+",
"\"mdWrap\"",
":",
"raise",
"exceptions",
".",
"ParseError",
"(",
"\"MDWrap can only parse mdWrap elements with METS namespace.\... | Create a new MDWrap by parsing root.
:param root: Element or ElementTree to be parsed into a MDWrap.
:raises exceptions.ParseError: If mdWrap does not contain MDTYPE
:raises exceptions.ParseError: If xmlData contains no children | [
"Create",
"a",
"new",
"MDWrap",
"by",
"parsing",
"root",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/metadata.py#L540-L568 |
artefactual-labs/mets-reader-writer | metsrw/plugins/premisrw/premis.py | _data_to_lxml_el | def _data_to_lxml_el(data, ns, nsmap, element_maker=None, snake=True):
"""Convert tuple/list ``data`` to an ``lxml.etree._Element`` instance.
:param tuple/list data: iterable whose first element is the snake-case
string which is the name of the root XML element. Subsequent elements
may be dicts ... | python | def _data_to_lxml_el(data, ns, nsmap, element_maker=None, snake=True):
"""Convert tuple/list ``data`` to an ``lxml.etree._Element`` instance.
:param tuple/list data: iterable whose first element is the snake-case
string which is the name of the root XML element. Subsequent elements
may be dicts ... | [
"def",
"_data_to_lxml_el",
"(",
"data",
",",
"ns",
",",
"nsmap",
",",
"element_maker",
"=",
"None",
",",
"snake",
"=",
"True",
")",
":",
"if",
"not",
"element_maker",
":",
"element_maker",
"=",
"ElementMaker",
"(",
"namespace",
"=",
"nsmap",
"[",
"ns",
"... | Convert tuple/list ``data`` to an ``lxml.etree._Element`` instance.
:param tuple/list data: iterable whose first element is the snake-case
string which is the name of the root XML element. Subsequent elements
may be dicts (which encode XML attributes), tuples/lists (which encode
sub-elements... | [
"Convert",
"tuple",
"/",
"list",
"data",
"to",
"an",
"lxml",
".",
"etree",
".",
"_Element",
"instance",
".",
":",
"param",
"tuple",
"/",
"list",
"data",
":",
"iterable",
"whose",
"first",
"element",
"is",
"the",
"snake",
"-",
"case",
"string",
"which",
... | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/plugins/premisrw/premis.py#L577-L626 |
artefactual-labs/mets-reader-writer | metsrw/plugins/premisrw/premis.py | _to_colon_ns | def _to_colon_ns(bracket_ns, default_ns=None, nsmap=None, snake=True):
"""Convert a namespaced tag/attribute name from explicit XML "bracket"
notation to a more succinct Pythonic colon-separated notation using
snake_case, e.g.,::
>>> _to_colon_ns(
'{info:lc/xmlns/premis-v2}objectIdentif... | python | def _to_colon_ns(bracket_ns, default_ns=None, nsmap=None, snake=True):
"""Convert a namespaced tag/attribute name from explicit XML "bracket"
notation to a more succinct Pythonic colon-separated notation using
snake_case, e.g.,::
>>> _to_colon_ns(
'{info:lc/xmlns/premis-v2}objectIdentif... | [
"def",
"_to_colon_ns",
"(",
"bracket_ns",
",",
"default_ns",
"=",
"None",
",",
"nsmap",
"=",
"None",
",",
"snake",
"=",
"True",
")",
":",
"parts",
"=",
"[",
"x",
".",
"strip",
"(",
"\"{\"",
")",
"for",
"x",
"in",
"bracket_ns",
".",
"split",
"(",
"\... | Convert a namespaced tag/attribute name from explicit XML "bracket"
notation to a more succinct Pythonic colon-separated notation using
snake_case, e.g.,::
>>> _to_colon_ns(
'{info:lc/xmlns/premis-v2}objectIdentifier',
'premis', utils.NAMESPACES)
'object_identifier'
... | [
"Convert",
"a",
"namespaced",
"tag",
"/",
"attribute",
"name",
"from",
"explicit",
"XML",
"bracket",
"notation",
"to",
"a",
"more",
"succinct",
"Pythonic",
"colon",
"-",
"separated",
"notation",
"using",
"snake_case",
"e",
".",
"g",
".",
"::"
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/plugins/premisrw/premis.py#L629-L659 |
artefactual-labs/mets-reader-writer | metsrw/plugins/premisrw/premis.py | _get_el_attributes | def _get_el_attributes(lxml_el, ns=None, nsmap=None):
"""Return the XML attributes of lxml ``Element`` instance lxml_el as a dict
where namespaced attributes are represented via colon-delimiting and using
snake case.
"""
attrs = {}
for attr, val in lxml_el.items():
attr = _to_colon_ns(at... | python | def _get_el_attributes(lxml_el, ns=None, nsmap=None):
"""Return the XML attributes of lxml ``Element`` instance lxml_el as a dict
where namespaced attributes are represented via colon-delimiting and using
snake case.
"""
attrs = {}
for attr, val in lxml_el.items():
attr = _to_colon_ns(at... | [
"def",
"_get_el_attributes",
"(",
"lxml_el",
",",
"ns",
"=",
"None",
",",
"nsmap",
"=",
"None",
")",
":",
"attrs",
"=",
"{",
"}",
"for",
"attr",
",",
"val",
"in",
"lxml_el",
".",
"items",
"(",
")",
":",
"attr",
"=",
"_to_colon_ns",
"(",
"attr",
","... | Return the XML attributes of lxml ``Element`` instance lxml_el as a dict
where namespaced attributes are represented via colon-delimiting and using
snake case. | [
"Return",
"the",
"XML",
"attributes",
"of",
"lxml",
"Element",
"instance",
"lxml_el",
"as",
"a",
"dict",
"where",
"namespaced",
"attributes",
"are",
"represented",
"via",
"colon",
"-",
"delimiting",
"and",
"using",
"snake",
"case",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/plugins/premisrw/premis.py#L662-L671 |
artefactual-labs/mets-reader-writer | metsrw/plugins/premisrw/premis.py | _lxml_el_to_data | def _lxml_el_to_data(lxml_el, ns, nsmap, snake=True):
"""Convert an ``lxml._Element`` instance to a Python tuple."""
tag_name = _to_colon_ns(lxml_el.tag, default_ns=ns, nsmap=nsmap)
ret = [tag_name]
attributes = _get_el_attributes(lxml_el, ns=ns, nsmap=nsmap)
if attributes:
ret.append(attrib... | python | def _lxml_el_to_data(lxml_el, ns, nsmap, snake=True):
"""Convert an ``lxml._Element`` instance to a Python tuple."""
tag_name = _to_colon_ns(lxml_el.tag, default_ns=ns, nsmap=nsmap)
ret = [tag_name]
attributes = _get_el_attributes(lxml_el, ns=ns, nsmap=nsmap)
if attributes:
ret.append(attrib... | [
"def",
"_lxml_el_to_data",
"(",
"lxml_el",
",",
"ns",
",",
"nsmap",
",",
"snake",
"=",
"True",
")",
":",
"tag_name",
"=",
"_to_colon_ns",
"(",
"lxml_el",
".",
"tag",
",",
"default_ns",
"=",
"ns",
",",
"nsmap",
"=",
"nsmap",
")",
"ret",
"=",
"[",
"tag... | Convert an ``lxml._Element`` instance to a Python tuple. | [
"Convert",
"an",
"lxml",
".",
"_Element",
"instance",
"to",
"a",
"Python",
"tuple",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/plugins/premisrw/premis.py#L674-L686 |
artefactual-labs/mets-reader-writer | metsrw/plugins/premisrw/premis.py | data_to_premis | def data_to_premis(data, premis_version=utils.PREMIS_VERSION):
"""Given tuple ``data`` representing a PREMIS entity (object, event or
agent), return an ``lxml.etree._Element`` instance. E.g.,::
>>> p = data_to_premis((
'event',
utils.PREMIS_META,
(
'e... | python | def data_to_premis(data, premis_version=utils.PREMIS_VERSION):
"""Given tuple ``data`` representing a PREMIS entity (object, event or
agent), return an ``lxml.etree._Element`` instance. E.g.,::
>>> p = data_to_premis((
'event',
utils.PREMIS_META,
(
'e... | [
"def",
"data_to_premis",
"(",
"data",
",",
"premis_version",
"=",
"utils",
".",
"PREMIS_VERSION",
")",
":",
"nsmap",
"=",
"utils",
".",
"PREMIS_VERSIONS_MAP",
"[",
"premis_version",
"]",
"[",
"\"namespaces\"",
"]",
"return",
"_data_to_lxml_el",
"(",
"data",
",",... | Given tuple ``data`` representing a PREMIS entity (object, event or
agent), return an ``lxml.etree._Element`` instance. E.g.,::
>>> p = data_to_premis((
'event',
utils.PREMIS_META,
(
'event_identifier',
('event_identifier_type', 'UUID'),
... | [
"Given",
"tuple",
"data",
"representing",
"a",
"PREMIS",
"entity",
"(",
"object",
"event",
"or",
"agent",
")",
"return",
"an",
"lxml",
".",
"etree",
".",
"_Element",
"instance",
".",
"E",
".",
"g",
".",
"::"
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/plugins/premisrw/premis.py#L689-L715 |
artefactual-labs/mets-reader-writer | metsrw/plugins/premisrw/premis.py | premis_to_data | def premis_to_data(premis_lxml_el):
"""Transform a PREMIS ``lxml._Element`` instance to a Python tuple."""
premis_version = premis_lxml_el.get("version", utils.PREMIS_VERSION)
nsmap = utils.PREMIS_VERSIONS_MAP[premis_version]["namespaces"]
return _lxml_el_to_data(premis_lxml_el, "premis", nsmap) | python | def premis_to_data(premis_lxml_el):
"""Transform a PREMIS ``lxml._Element`` instance to a Python tuple."""
premis_version = premis_lxml_el.get("version", utils.PREMIS_VERSION)
nsmap = utils.PREMIS_VERSIONS_MAP[premis_version]["namespaces"]
return _lxml_el_to_data(premis_lxml_el, "premis", nsmap) | [
"def",
"premis_to_data",
"(",
"premis_lxml_el",
")",
":",
"premis_version",
"=",
"premis_lxml_el",
".",
"get",
"(",
"\"version\"",
",",
"utils",
".",
"PREMIS_VERSION",
")",
"nsmap",
"=",
"utils",
".",
"PREMIS_VERSIONS_MAP",
"[",
"premis_version",
"]",
"[",
"\"na... | Transform a PREMIS ``lxml._Element`` instance to a Python tuple. | [
"Transform",
"a",
"PREMIS",
"lxml",
".",
"_Element",
"instance",
"to",
"a",
"Python",
"tuple",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/plugins/premisrw/premis.py#L718-L722 |
artefactual-labs/mets-reader-writer | metsrw/plugins/premisrw/premis.py | data_find | def data_find(data, path):
"""Find and return the first element-as-tuple in tuple ``data`` using simplified
XPath ``path``.
"""
path_parts = path.split("/")
try:
sub_elm = [
el
for el in data
if isinstance(el, (tuple, list)) and el[0] == path_parts[0]
... | python | def data_find(data, path):
"""Find and return the first element-as-tuple in tuple ``data`` using simplified
XPath ``path``.
"""
path_parts = path.split("/")
try:
sub_elm = [
el
for el in data
if isinstance(el, (tuple, list)) and el[0] == path_parts[0]
... | [
"def",
"data_find",
"(",
"data",
",",
"path",
")",
":",
"path_parts",
"=",
"path",
".",
"split",
"(",
"\"/\"",
")",
"try",
":",
"sub_elm",
"=",
"[",
"el",
"for",
"el",
"in",
"data",
"if",
"isinstance",
"(",
"el",
",",
"(",
"tuple",
",",
"list",
"... | Find and return the first element-as-tuple in tuple ``data`` using simplified
XPath ``path``. | [
"Find",
"and",
"return",
"the",
"first",
"element",
"-",
"as",
"-",
"tuple",
"in",
"tuple",
"data",
"using",
"simplified",
"XPath",
"path",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/plugins/premisrw/premis.py#L725-L741 |
artefactual-labs/mets-reader-writer | metsrw/plugins/premisrw/premis.py | tuple_to_schema | def tuple_to_schema(tuple_):
"""Convert a tuple representing an XML data structure into a schema tuple
that can be used in the ``.schema`` property of a sub-class of
PREMISElement.
"""
schema = []
for element in tuple_:
if isinstance(element, (tuple, list)):
try:
... | python | def tuple_to_schema(tuple_):
"""Convert a tuple representing an XML data structure into a schema tuple
that can be used in the ``.schema`` property of a sub-class of
PREMISElement.
"""
schema = []
for element in tuple_:
if isinstance(element, (tuple, list)):
try:
... | [
"def",
"tuple_to_schema",
"(",
"tuple_",
")",
":",
"schema",
"=",
"[",
"]",
"for",
"element",
"in",
"tuple_",
":",
"if",
"isinstance",
"(",
"element",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"element",
"[",... | Convert a tuple representing an XML data structure into a schema tuple
that can be used in the ``.schema`` property of a sub-class of
PREMISElement. | [
"Convert",
"a",
"tuple",
"representing",
"an",
"XML",
"data",
"structure",
"into",
"a",
"schema",
"tuple",
"that",
"can",
"be",
"used",
"in",
"the",
".",
"schema",
"property",
"of",
"a",
"sub",
"-",
"class",
"of",
"PREMISElement",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/plugins/premisrw/premis.py#L744-L761 |
artefactual-labs/mets-reader-writer | metsrw/plugins/premisrw/premis.py | generate_element_class | def generate_element_class(tuple_instance):
"""Dynamically create a sub-class of PREMISElement given
``tuple_instance``, which is a tuple representing an XML data structure.
"""
schema = tuple_to_schema(tuple_instance)
def defaults(self):
return {}
def schema_getter(self):
retu... | python | def generate_element_class(tuple_instance):
"""Dynamically create a sub-class of PREMISElement given
``tuple_instance``, which is a tuple representing an XML data structure.
"""
schema = tuple_to_schema(tuple_instance)
def defaults(self):
return {}
def schema_getter(self):
retu... | [
"def",
"generate_element_class",
"(",
"tuple_instance",
")",
":",
"schema",
"=",
"tuple_to_schema",
"(",
"tuple_instance",
")",
"def",
"defaults",
"(",
"self",
")",
":",
"return",
"{",
"}",
"def",
"schema_getter",
"(",
"self",
")",
":",
"return",
"schema",
"... | Dynamically create a sub-class of PREMISElement given
``tuple_instance``, which is a tuple representing an XML data structure. | [
"Dynamically",
"create",
"a",
"sub",
"-",
"class",
"of",
"PREMISElement",
"given",
"tuple_instance",
"which",
"is",
"a",
"tuple",
"representing",
"an",
"XML",
"data",
"structure",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/plugins/premisrw/premis.py#L764-L781 |
artefactual-labs/mets-reader-writer | metsrw/plugins/premisrw/premis.py | data_find_all | def data_find_all(data, path, dyn_cls=False):
"""Find and return all element-as-tuples in tuple ``data`` using simplified
XPath ``path``.
"""
path_parts = path.split("/")
try:
sub_elms = tuple(
el
for el in data
if isinstance(el, (tuple, list)) and el[0] =... | python | def data_find_all(data, path, dyn_cls=False):
"""Find and return all element-as-tuples in tuple ``data`` using simplified
XPath ``path``.
"""
path_parts = path.split("/")
try:
sub_elms = tuple(
el
for el in data
if isinstance(el, (tuple, list)) and el[0] =... | [
"def",
"data_find_all",
"(",
"data",
",",
"path",
",",
"dyn_cls",
"=",
"False",
")",
":",
"path_parts",
"=",
"path",
".",
"split",
"(",
"\"/\"",
")",
"try",
":",
"sub_elms",
"=",
"tuple",
"(",
"el",
"for",
"el",
"in",
"data",
"if",
"isinstance",
"(",... | Find and return all element-as-tuples in tuple ``data`` using simplified
XPath ``path``. | [
"Find",
"and",
"return",
"all",
"element",
"-",
"as",
"-",
"tuples",
"in",
"tuple",
"data",
"using",
"simplified",
"XPath",
"path",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/plugins/premisrw/premis.py#L784-L808 |
artefactual-labs/mets-reader-writer | metsrw/plugins/premisrw/premis.py | data_find_text | def data_find_text(data, path):
"""Return the text value of the element-as-tuple in tuple ``data`` using
simplified XPath ``path``.
"""
el = data_find(data, path)
if not isinstance(el, (list, tuple)):
return None
texts = [child for child in el[1:] if not isinstance(child, (tuple, list, d... | python | def data_find_text(data, path):
"""Return the text value of the element-as-tuple in tuple ``data`` using
simplified XPath ``path``.
"""
el = data_find(data, path)
if not isinstance(el, (list, tuple)):
return None
texts = [child for child in el[1:] if not isinstance(child, (tuple, list, d... | [
"def",
"data_find_text",
"(",
"data",
",",
"path",
")",
":",
"el",
"=",
"data_find",
"(",
"data",
",",
"path",
")",
"if",
"not",
"isinstance",
"(",
"el",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"None",
"texts",
"=",
"[",
"child",
... | Return the text value of the element-as-tuple in tuple ``data`` using
simplified XPath ``path``. | [
"Return",
"the",
"text",
"value",
"of",
"the",
"element",
"-",
"as",
"-",
"tuple",
"in",
"tuple",
"data",
"using",
"simplified",
"XPath",
"path",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/plugins/premisrw/premis.py#L811-L829 |
artefactual-labs/mets-reader-writer | metsrw/plugins/premisrw/premis.py | _generate_data | def _generate_data(schema, elements, attributes=None, path=None):
"""Using tree-as-tuple ``schema`` as guide, return a tree-as-tuple ``data``
representing a PREMIS XML element, where the values in dict ``elements`` and
the values in dict ``attributes`` are located in the appropriate locations
in the ``d... | python | def _generate_data(schema, elements, attributes=None, path=None):
"""Using tree-as-tuple ``schema`` as guide, return a tree-as-tuple ``data``
representing a PREMIS XML element, where the values in dict ``elements`` and
the values in dict ``attributes`` are located in the appropriate locations
in the ``d... | [
"def",
"_generate_data",
"(",
"schema",
",",
"elements",
",",
"attributes",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"path",
"=",
"path",
"or",
"[",
"]",
"attributes",
"=",
"attributes",
"or",
"{",
"}",
"tag_name",
"=",
"schema",
"[",
"0",
"]... | Using tree-as-tuple ``schema`` as guide, return a tree-as-tuple ``data``
representing a PREMIS XML element, where the values in dict ``elements`` and
the values in dict ``attributes`` are located in the appropriate locations
in the ``data`` tree structure. | [
"Using",
"tree",
"-",
"as",
"-",
"tuple",
"schema",
"as",
"guide",
"return",
"a",
"tree",
"-",
"as",
"-",
"tuple",
"data",
"representing",
"a",
"PREMIS",
"XML",
"element",
"where",
"the",
"values",
"in",
"dict",
"elements",
"and",
"the",
"values",
"in",
... | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/plugins/premisrw/premis.py#L865-L903 |
artefactual-labs/mets-reader-writer | metsrw/plugins/premisrw/premis.py | el_is_empty | def el_is_empty(el):
"""Return ``True`` if tuple ``el`` represents an empty XML element."""
if len(el) == 1 and not isinstance(el[0], (list, tuple)):
return True
subels_are_empty = []
for subel in el:
if isinstance(subel, (list, tuple)):
subels_are_empty.append(el_is_empty(su... | python | def el_is_empty(el):
"""Return ``True`` if tuple ``el`` represents an empty XML element."""
if len(el) == 1 and not isinstance(el[0], (list, tuple)):
return True
subels_are_empty = []
for subel in el:
if isinstance(subel, (list, tuple)):
subels_are_empty.append(el_is_empty(su... | [
"def",
"el_is_empty",
"(",
"el",
")",
":",
"if",
"len",
"(",
"el",
")",
"==",
"1",
"and",
"not",
"isinstance",
"(",
"el",
"[",
"0",
"]",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"True",
"subels_are_empty",
"=",
"[",
"]",
"for",
... | Return ``True`` if tuple ``el`` represents an empty XML element. | [
"Return",
"True",
"if",
"tuple",
"el",
"represents",
"an",
"empty",
"XML",
"element",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/plugins/premisrw/premis.py#L906-L916 |
artefactual-labs/mets-reader-writer | metsrw/plugins/premisrw/premis.py | get_attrs_to_paths | def get_attrs_to_paths(schema, attrs_to_paths=None, path=None):
"""Analyze PREMIS-element-as-tuple ``schema`` and return a dict that maps
attribute names to the simplified XPaths needed to retrieve them, e.g.,::
>>> {'object_identifier_type':
'object_identifier/object_identifier_type',
... | python | def get_attrs_to_paths(schema, attrs_to_paths=None, path=None):
"""Analyze PREMIS-element-as-tuple ``schema`` and return a dict that maps
attribute names to the simplified XPaths needed to retrieve them, e.g.,::
>>> {'object_identifier_type':
'object_identifier/object_identifier_type',
... | [
"def",
"get_attrs_to_paths",
"(",
"schema",
",",
"attrs_to_paths",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"attrs_to_paths",
"=",
"attrs_to_paths",
"or",
"{",
"}",
"tag",
"=",
"schema",
"[",
"0",
"]",
"if",
"len",
"(",
"schema",
")",
"==",
"1"... | Analyze PREMIS-element-as-tuple ``schema`` and return a dict that maps
attribute names to the simplified XPaths needed to retrieve them, e.g.,::
>>> {'object_identifier_type':
'object_identifier/object_identifier_type',
'object_identifier_value':
'object_identif... | [
"Analyze",
"PREMIS",
"-",
"element",
"-",
"as",
"-",
"tuple",
"schema",
"and",
"return",
"a",
"dict",
"that",
"maps",
"attribute",
"names",
"to",
"the",
"simplified",
"XPaths",
"needed",
"to",
"retrieve",
"them",
"e",
".",
"g",
".",
"::"
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/plugins/premisrw/premis.py#L926-L952 |
artefactual-labs/mets-reader-writer | metsrw/plugins/premisrw/premis.py | _premis_version_from_data | def _premis_version_from_data(data):
"""Given tuple ``data`` encoding a PREMIS element, attempt to return the
PREMIS version it is using. If none can be found, return the default PREMIS
version.
"""
for child in data:
if isinstance(child, dict):
version = child.get("version")
... | python | def _premis_version_from_data(data):
"""Given tuple ``data`` encoding a PREMIS element, attempt to return the
PREMIS version it is using. If none can be found, return the default PREMIS
version.
"""
for child in data:
if isinstance(child, dict):
version = child.get("version")
... | [
"def",
"_premis_version_from_data",
"(",
"data",
")",
":",
"for",
"child",
"in",
"data",
":",
"if",
"isinstance",
"(",
"child",
",",
"dict",
")",
":",
"version",
"=",
"child",
".",
"get",
"(",
"\"version\"",
")",
"if",
"version",
":",
"return",
"version"... | Given tuple ``data`` encoding a PREMIS element, attempt to return the
PREMIS version it is using. If none can be found, return the default PREMIS
version. | [
"Given",
"tuple",
"data",
"encoding",
"a",
"PREMIS",
"element",
"attempt",
"to",
"return",
"the",
"PREMIS",
"version",
"it",
"is",
"using",
".",
"If",
"none",
"can",
"be",
"found",
"return",
"the",
"default",
"PREMIS",
"version",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/plugins/premisrw/premis.py#L963-L973 |
artefactual-labs/mets-reader-writer | metsrw/plugins/premisrw/premis.py | PREMISEvent.parsed_event_detail | def parsed_event_detail(self):
"""Parse and return our PREMIS eventDetail string value like::
'program="7z"; version="9.20"; algorithm="bzip2"'
and return a dict like::
{'algorithm': 'bzip2', 'version': '9.20', 'program': '7z'}
"""
attr = (
"event_d... | python | def parsed_event_detail(self):
"""Parse and return our PREMIS eventDetail string value like::
'program="7z"; version="9.20"; algorithm="bzip2"'
and return a dict like::
{'algorithm': 'bzip2', 'version': '9.20', 'program': '7z'}
"""
attr = (
"event_d... | [
"def",
"parsed_event_detail",
"(",
"self",
")",
":",
"attr",
"=",
"(",
"\"event_detail_information__event_detail\"",
"if",
"self",
".",
"premis_version",
"==",
"utils",
".",
"PREMIS_3_0_VERSION",
"else",
"\"event_detail\"",
")",
"return",
"dict",
"(",
"[",
"tuple",
... | Parse and return our PREMIS eventDetail string value like::
'program="7z"; version="9.20"; algorithm="bzip2"'
and return a dict like::
{'algorithm': 'bzip2', 'version': '9.20', 'program': '7z'} | [
"Parse",
"and",
"return",
"our",
"PREMIS",
"eventDetail",
"string",
"value",
"like",
"::"
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/plugins/premisrw/premis.py#L362-L381 |
artefactual-labs/mets-reader-writer | metsrw/plugins/premisrw/premis.py | PREMISEvent.compression_details | def compression_details(self):
"""Return as a 3-tuple, this PREMIS compression event's program,
version, and algorithm used to perform the compression.
"""
event_type = self.findtext("event_type")
if event_type != "compression":
raise AttributeError(
'... | python | def compression_details(self):
"""Return as a 3-tuple, this PREMIS compression event's program,
version, and algorithm used to perform the compression.
"""
event_type = self.findtext("event_type")
if event_type != "compression":
raise AttributeError(
'... | [
"def",
"compression_details",
"(",
"self",
")",
":",
"event_type",
"=",
"self",
".",
"findtext",
"(",
"\"event_type\"",
")",
"if",
"event_type",
"!=",
"\"compression\"",
":",
"raise",
"AttributeError",
"(",
"'PREMIS events of type \"{}\" have no compression'",
"\" detai... | Return as a 3-tuple, this PREMIS compression event's program,
version, and algorithm used to perform the compression. | [
"Return",
"as",
"a",
"3",
"-",
"tuple",
"this",
"PREMIS",
"compression",
"event",
"s",
"program",
"version",
"and",
"algorithm",
"used",
"to",
"perform",
"the",
"compression",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/plugins/premisrw/premis.py#L387-L408 |
artefactual-labs/mets-reader-writer | metsrw/plugins/premisrw/premis.py | PREMISEvent.get_decompression_transform_files | def get_decompression_transform_files(self, offset=0):
"""Returns a list of dicts representing ``<mets:transformFile>``
elements with ``TRANSFORMTYPE="decompression"`` given
``compression_algorithm`` which is a comma-separated string of
algorithms that must be used in the order provided ... | python | def get_decompression_transform_files(self, offset=0):
"""Returns a list of dicts representing ``<mets:transformFile>``
elements with ``TRANSFORMTYPE="decompression"`` given
``compression_algorithm`` which is a comma-separated string of
algorithms that must be used in the order provided ... | [
"def",
"get_decompression_transform_files",
"(",
"self",
",",
"offset",
"=",
"0",
")",
":",
"compression_algorithm",
",",
"_",
",",
"_",
"=",
"self",
".",
"compression_details",
"return",
"[",
"{",
"\"algorithm\"",
":",
"algorithm",
",",
"\"order\"",
":",
"str... | Returns a list of dicts representing ``<mets:transformFile>``
elements with ``TRANSFORMTYPE="decompression"`` given
``compression_algorithm`` which is a comma-separated string of
algorithms that must be used in the order provided to decompress
the package, e.g., 'bzip2,tar' or 'lzma'. | [
"Returns",
"a",
"list",
"of",
"dicts",
"representing",
"<mets",
":",
"transformFile",
">",
"elements",
"with",
"TRANSFORMTYPE",
"=",
"decompression",
"given",
"compression_algorithm",
"which",
"is",
"a",
"comma",
"-",
"separated",
"string",
"of",
"algorithms",
"th... | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/plugins/premisrw/premis.py#L410-L425 |
artefactual-labs/mets-reader-writer | metsrw/plugins/premisrw/premis.py | PREMISEvent.encryption_details | def encryption_details(self):
"""Return as a 3-tuple, this PREMIS encryption event's program,
version, and key used to perform the encryption.
"""
event_type = self.findtext("event_type")
if event_type != "encryption":
raise AttributeError(
'PREMIS eve... | python | def encryption_details(self):
"""Return as a 3-tuple, this PREMIS encryption event's program,
version, and key used to perform the encryption.
"""
event_type = self.findtext("event_type")
if event_type != "encryption":
raise AttributeError(
'PREMIS eve... | [
"def",
"encryption_details",
"(",
"self",
")",
":",
"event_type",
"=",
"self",
".",
"findtext",
"(",
"\"event_type\"",
")",
"if",
"event_type",
"!=",
"\"encryption\"",
":",
"raise",
"AttributeError",
"(",
"'PREMIS events of type \"{}\" have no encryption'",
"\" details\... | Return as a 3-tuple, this PREMIS encryption event's program,
version, and key used to perform the encryption. | [
"Return",
"as",
"a",
"3",
"-",
"tuple",
"this",
"PREMIS",
"encryption",
"event",
"s",
"program",
"version",
"and",
"key",
"used",
"to",
"perform",
"the",
"encryption",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/plugins/premisrw/premis.py#L431-L449 |
artefactual-labs/mets-reader-writer | metsrw/di.py | has_class_methods | def has_class_methods(*class_method_names):
"""Return a test function that, when given a class, returns ``True`` if that
class has all of the class methods in ``class_method_names``. If an object
is passed to the test function, check for the class methods on its
class.
"""
def test(cls):
... | python | def has_class_methods(*class_method_names):
"""Return a test function that, when given a class, returns ``True`` if that
class has all of the class methods in ``class_method_names``. If an object
is passed to the test function, check for the class methods on its
class.
"""
def test(cls):
... | [
"def",
"has_class_methods",
"(",
"*",
"class_method_names",
")",
":",
"def",
"test",
"(",
"cls",
")",
":",
"if",
"not",
"isinstance",
"(",
"cls",
",",
"type",
")",
":",
"cls",
"=",
"type",
"(",
"cls",
")",
"for",
"class_method_name",
"in",
"class_method_... | Return a test function that, when given a class, returns ``True`` if that
class has all of the class methods in ``class_method_names``. If an object
is passed to the test function, check for the class methods on its
class. | [
"Return",
"a",
"test",
"function",
"that",
"when",
"given",
"a",
"class",
"returns",
"True",
"if",
"that",
"class",
"has",
"all",
"of",
"the",
"class",
"methods",
"in",
"class_method_names",
".",
"If",
"an",
"object",
"is",
"passed",
"to",
"the",
"test",
... | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/di.py#L136-L155 |
artefactual-labs/mets-reader-writer | metsrw/di.py | has_methods | def has_methods(*method_names):
"""Return a test function that, when given an object (class or an
instance), returns ``True`` if that object has all of the (regular) methods
in ``method_names``. Note: this is testing for regular methods only and the
test function will correctly return ``False`` if an in... | python | def has_methods(*method_names):
"""Return a test function that, when given an object (class or an
instance), returns ``True`` if that object has all of the (regular) methods
in ``method_names``. Note: this is testing for regular methods only and the
test function will correctly return ``False`` if an in... | [
"def",
"has_methods",
"(",
"*",
"method_names",
")",
":",
"def",
"test",
"(",
"obj",
")",
":",
"for",
"method_name",
"in",
"method_names",
":",
"try",
":",
"method",
"=",
"getattr",
"(",
"obj",
",",
"method_name",
")",
"except",
"AttributeError",
":",
"r... | Return a test function that, when given an object (class or an
instance), returns ``True`` if that object has all of the (regular) methods
in ``method_names``. Note: this is testing for regular methods only and the
test function will correctly return ``False`` if an instance has one of the
specified met... | [
"Return",
"a",
"test",
"function",
"that",
"when",
"given",
"an",
"object",
"(",
"class",
"or",
"an",
"instance",
")",
"returns",
"True",
"if",
"that",
"object",
"has",
"all",
"of",
"the",
"(",
"regular",
")",
"methods",
"in",
"method_names",
".",
"Note"... | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/di.py#L158-L187 |
artefactual-labs/mets-reader-writer | metsrw/di.py | FeatureBroker.provide | def provide(self, feature_name, provider, *args, **kwargs):
"""Provide a feature named ``feature_name`` using the provider object
``provider`` and any arguments (``args``, ``kwargs``) needed by the
provider if it is callable.
"""
if not self.allow_replace:
assert feat... | python | def provide(self, feature_name, provider, *args, **kwargs):
"""Provide a feature named ``feature_name`` using the provider object
``provider`` and any arguments (``args``, ``kwargs``) needed by the
provider if it is callable.
"""
if not self.allow_replace:
assert feat... | [
"def",
"provide",
"(",
"self",
",",
"feature_name",
",",
"provider",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"allow_replace",
":",
"assert",
"feature_name",
"not",
"in",
"self",
".",
"providers",
",",
"\"Duplicate f... | Provide a feature named ``feature_name`` using the provider object
``provider`` and any arguments (``args``, ``kwargs``) needed by the
provider if it is callable. | [
"Provide",
"a",
"feature",
"named",
"feature_name",
"using",
"the",
"provider",
"object",
"provider",
"and",
"any",
"arguments",
"(",
"args",
"kwargs",
")",
"needed",
"by",
"the",
"provider",
"if",
"it",
"is",
"callable",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/di.py#L40-L52 |
artefactual-labs/mets-reader-writer | metsrw/utils.py | _urlendecode | def _urlendecode(url, func):
"""Encode or decode ``url`` by applying ``func`` to all of its
URL-encodable parts.
"""
parsed = urlparse(url)
for attr in URL_ENCODABLE_PARTS:
parsed = parsed._replace(**{attr: func(getattr(parsed, attr))})
return urlunparse(parsed) | python | def _urlendecode(url, func):
"""Encode or decode ``url`` by applying ``func`` to all of its
URL-encodable parts.
"""
parsed = urlparse(url)
for attr in URL_ENCODABLE_PARTS:
parsed = parsed._replace(**{attr: func(getattr(parsed, attr))})
return urlunparse(parsed) | [
"def",
"_urlendecode",
"(",
"url",
",",
"func",
")",
":",
"parsed",
"=",
"urlparse",
"(",
"url",
")",
"for",
"attr",
"in",
"URL_ENCODABLE_PARTS",
":",
"parsed",
"=",
"parsed",
".",
"_replace",
"(",
"*",
"*",
"{",
"attr",
":",
"func",
"(",
"getattr",
... | Encode or decode ``url`` by applying ``func`` to all of its
URL-encodable parts. | [
"Encode",
"or",
"decode",
"url",
"by",
"applying",
"func",
"to",
"all",
"of",
"its",
"URL",
"-",
"encodable",
"parts",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/utils.py#L45-L52 |
zmathew/django-backbone | backbone/__init__.py | autodiscover | def autodiscover():
"""
Auto-discover INSTALLED_APPS backbone_api.py modules.
"""
# This code is based off django.contrib.admin.__init__
from django.conf import settings
try:
# Django versions >= 1.9
from django.utils.module_loading import import_module
except ImportError:
... | python | def autodiscover():
"""
Auto-discover INSTALLED_APPS backbone_api.py modules.
"""
# This code is based off django.contrib.admin.__init__
from django.conf import settings
try:
# Django versions >= 1.9
from django.utils.module_loading import import_module
except ImportError:
... | [
"def",
"autodiscover",
"(",
")",
":",
"# This code is based off django.contrib.admin.__init__",
"from",
"django",
".",
"conf",
"import",
"settings",
"try",
":",
"# Django versions >= 1.9",
"from",
"django",
".",
"utils",
".",
"module_loading",
"import",
"import_module",
... | Auto-discover INSTALLED_APPS backbone_api.py modules. | [
"Auto",
"-",
"discover",
"INSTALLED_APPS",
"backbone_api",
".",
"py",
"modules",
"."
] | train | https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/__init__.py#L16-L41 |
zmathew/django-backbone | backbone/sites.py | BackboneSite.register | def register(self, backbone_view_class):
"""
Registers the given backbone view class.
"""
if backbone_view_class not in self._registry:
self._registry.append(backbone_view_class) | python | def register(self, backbone_view_class):
"""
Registers the given backbone view class.
"""
if backbone_view_class not in self._registry:
self._registry.append(backbone_view_class) | [
"def",
"register",
"(",
"self",
",",
"backbone_view_class",
")",
":",
"if",
"backbone_view_class",
"not",
"in",
"self",
".",
"_registry",
":",
"self",
".",
"_registry",
".",
"append",
"(",
"backbone_view_class",
")"
] | Registers the given backbone view class. | [
"Registers",
"the",
"given",
"backbone",
"view",
"class",
"."
] | train | https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/sites.py#L10-L15 |
zmathew/django-backbone | backbone/views.py | BackboneAPIView.queryset | def queryset(self, request, **kwargs):
"""
Returns the queryset (along with ordering) to be used when retrieving object(s).
"""
qs = self.model._default_manager.all()
if self.ordering:
qs = qs.order_by(*self.ordering)
return qs | python | def queryset(self, request, **kwargs):
"""
Returns the queryset (along with ordering) to be used when retrieving object(s).
"""
qs = self.model._default_manager.all()
if self.ordering:
qs = qs.order_by(*self.ordering)
return qs | [
"def",
"queryset",
"(",
"self",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"qs",
"=",
"self",
".",
"model",
".",
"_default_manager",
".",
"all",
"(",
")",
"if",
"self",
".",
"ordering",
":",
"qs",
"=",
"qs",
".",
"order_by",
"(",
"*",
"se... | Returns the queryset (along with ordering) to be used when retrieving object(s). | [
"Returns",
"the",
"queryset",
"(",
"along",
"with",
"ordering",
")",
"to",
"be",
"used",
"when",
"retrieving",
"object",
"(",
"s",
")",
"."
] | train | https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L29-L36 |
zmathew/django-backbone | backbone/views.py | BackboneAPIView.get | def get(self, request, id=None, **kwargs):
"""
Handles get requests for either the collection or an object detail.
"""
if not self.has_get_permission(request):
return HttpResponseForbidden(_('You do not have permission to perform this action.'))
if id:
ob... | python | def get(self, request, id=None, **kwargs):
"""
Handles get requests for either the collection or an object detail.
"""
if not self.has_get_permission(request):
return HttpResponseForbidden(_('You do not have permission to perform this action.'))
if id:
ob... | [
"def",
"get",
"(",
"self",
",",
"request",
",",
"id",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"has_get_permission",
"(",
"request",
")",
":",
"return",
"HttpResponseForbidden",
"(",
"_",
"(",
"'You do not have permission t... | Handles get requests for either the collection or an object detail. | [
"Handles",
"get",
"requests",
"for",
"either",
"the",
"collection",
"or",
"an",
"object",
"detail",
"."
] | train | https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L38-L49 |
zmathew/django-backbone | backbone/views.py | BackboneAPIView.get_object_detail | def get_object_detail(self, request, obj):
"""
Handles get requests for the details of the given object.
"""
if self.display_detail_fields:
display_fields = self.display_detail_fields
else:
display_fields = self.display_fields
data = self.serializ... | python | def get_object_detail(self, request, obj):
"""
Handles get requests for the details of the given object.
"""
if self.display_detail_fields:
display_fields = self.display_detail_fields
else:
display_fields = self.display_fields
data = self.serializ... | [
"def",
"get_object_detail",
"(",
"self",
",",
"request",
",",
"obj",
")",
":",
"if",
"self",
".",
"display_detail_fields",
":",
"display_fields",
"=",
"self",
".",
"display_detail_fields",
"else",
":",
"display_fields",
"=",
"self",
".",
"display_fields",
"data"... | Handles get requests for the details of the given object. | [
"Handles",
"get",
"requests",
"for",
"the",
"details",
"of",
"the",
"given",
"object",
"."
] | train | https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L51-L61 |
zmathew/django-backbone | backbone/views.py | BackboneAPIView.get_collection | def get_collection(self, request, **kwargs):
"""
Handles get requests for the list of objects.
"""
qs = self.queryset(request, **kwargs)
if self.display_collection_fields:
display_fields = self.display_collection_fields
else:
display_fields = self... | python | def get_collection(self, request, **kwargs):
"""
Handles get requests for the list of objects.
"""
qs = self.queryset(request, **kwargs)
if self.display_collection_fields:
display_fields = self.display_collection_fields
else:
display_fields = self... | [
"def",
"get_collection",
"(",
"self",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"qs",
"=",
"self",
".",
"queryset",
"(",
"request",
",",
"*",
"*",
"kwargs",
")",
"if",
"self",
".",
"display_collection_fields",
":",
"display_fields",
"=",
"self",... | Handles get requests for the list of objects. | [
"Handles",
"get",
"requests",
"for",
"the",
"list",
"of",
"objects",
"."
] | train | https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L63-L88 |
zmathew/django-backbone | backbone/views.py | BackboneAPIView.post | def post(self, request, id=None, **kwargs):
"""
Handles post requests.
"""
if id:
# No posting to an object detail page
return HttpResponseForbidden()
else:
if not self.has_add_permission(request):
return HttpResponseForbidden(_... | python | def post(self, request, id=None, **kwargs):
"""
Handles post requests.
"""
if id:
# No posting to an object detail page
return HttpResponseForbidden()
else:
if not self.has_add_permission(request):
return HttpResponseForbidden(_... | [
"def",
"post",
"(",
"self",
",",
"request",
",",
"id",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"id",
":",
"# No posting to an object detail page",
"return",
"HttpResponseForbidden",
"(",
")",
"else",
":",
"if",
"not",
"self",
".",
"has_add_pe... | Handles post requests. | [
"Handles",
"post",
"requests",
"."
] | train | https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L90-L101 |
zmathew/django-backbone | backbone/views.py | BackboneAPIView.add_object | def add_object(self, request):
"""
Adds an object.
"""
try:
# backbone sends data in the body in json format
# Conditional statement is for backwards compatibility with Django <= 1.3
data = json.loads(request.body if hasattr(request, 'body') else reque... | python | def add_object(self, request):
"""
Adds an object.
"""
try:
# backbone sends data in the body in json format
# Conditional statement is for backwards compatibility with Django <= 1.3
data = json.loads(request.body if hasattr(request, 'body') else reque... | [
"def",
"add_object",
"(",
"self",
",",
"request",
")",
":",
"try",
":",
"# backbone sends data in the body in json format",
"# Conditional statement is for backwards compatibility with Django <= 1.3",
"data",
"=",
"json",
".",
"loads",
"(",
"request",
".",
"body",
"if",
"... | Adds an object. | [
"Adds",
"an",
"object",
"."
] | train | https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L103-L133 |
zmathew/django-backbone | backbone/views.py | BackboneAPIView.put | def put(self, request, id=None, **kwargs):
"""
Handles put requests.
"""
if id:
obj = get_object_or_404(self.queryset(request), id=id)
if not self.has_update_permission(request, obj):
return HttpResponseForbidden(_('You do not have permission to pe... | python | def put(self, request, id=None, **kwargs):
"""
Handles put requests.
"""
if id:
obj = get_object_or_404(self.queryset(request), id=id)
if not self.has_update_permission(request, obj):
return HttpResponseForbidden(_('You do not have permission to pe... | [
"def",
"put",
"(",
"self",
",",
"request",
",",
"id",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"id",
":",
"obj",
"=",
"get_object_or_404",
"(",
"self",
".",
"queryset",
"(",
"request",
")",
",",
"id",
"=",
"id",
")",
"if",
"not",
"... | Handles put requests. | [
"Handles",
"put",
"requests",
"."
] | train | https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L135-L147 |
zmathew/django-backbone | backbone/views.py | BackboneAPIView.update_object | def update_object(self, request, obj):
"""
Updates an object.
"""
try:
# backbone sends data in the body in json format
# Conditional statement is for backwards compatibility with Django <= 1.3
data = json.loads(request.body if hasattr(request, 'bo... | python | def update_object(self, request, obj):
"""
Updates an object.
"""
try:
# backbone sends data in the body in json format
# Conditional statement is for backwards compatibility with Django <= 1.3
data = json.loads(request.body if hasattr(request, 'bo... | [
"def",
"update_object",
"(",
"self",
",",
"request",
",",
"obj",
")",
":",
"try",
":",
"# backbone sends data in the body in json format",
"# Conditional statement is for backwards compatibility with Django <= 1.3",
"data",
"=",
"json",
".",
"loads",
"(",
"request",
".",
... | Updates an object. | [
"Updates",
"an",
"object",
"."
] | train | https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L149-L169 |
zmathew/django-backbone | backbone/views.py | BackboneAPIView.get_form_instance | def get_form_instance(self, request, data=None, instance=None):
"""
Returns an instantiated form to be used for adding or editing an object.
The `instance` argument is the model instance (passed only if this form
is going to be used for editing an existing object).
"""
d... | python | def get_form_instance(self, request, data=None, instance=None):
"""
Returns an instantiated form to be used for adding or editing an object.
The `instance` argument is the model instance (passed only if this form
is going to be used for editing an existing object).
"""
d... | [
"def",
"get_form_instance",
"(",
"self",
",",
"request",
",",
"data",
"=",
"None",
",",
"instance",
"=",
"None",
")",
":",
"defaults",
"=",
"{",
"}",
"if",
"self",
".",
"form",
":",
"defaults",
"[",
"'form'",
"]",
"=",
"self",
".",
"form",
"if",
"s... | Returns an instantiated form to be used for adding or editing an object.
The `instance` argument is the model instance (passed only if this form
is going to be used for editing an existing object). | [
"Returns",
"an",
"instantiated",
"form",
"to",
"be",
"used",
"for",
"adding",
"or",
"editing",
"an",
"object",
"."
] | train | https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L171-L183 |
zmathew/django-backbone | backbone/views.py | BackboneAPIView.delete | def delete(self, request, id=None):
"""
Handles delete requests.
"""
if id:
obj = get_object_or_404(self.queryset(request), id=id)
if not self.has_delete_permission(request, obj):
return HttpResponseForbidden(_('You do not have permission to perfor... | python | def delete(self, request, id=None):
"""
Handles delete requests.
"""
if id:
obj = get_object_or_404(self.queryset(request), id=id)
if not self.has_delete_permission(request, obj):
return HttpResponseForbidden(_('You do not have permission to perfor... | [
"def",
"delete",
"(",
"self",
",",
"request",
",",
"id",
"=",
"None",
")",
":",
"if",
"id",
":",
"obj",
"=",
"get_object_or_404",
"(",
"self",
".",
"queryset",
"(",
"request",
")",
",",
"id",
"=",
"id",
")",
"if",
"not",
"self",
".",
"has_delete_pe... | Handles delete requests. | [
"Handles",
"delete",
"requests",
"."
] | train | https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L185-L197 |
zmathew/django-backbone | backbone/views.py | BackboneAPIView.has_add_permission | def has_add_permission(self, request):
"""
Returns True if the requesting user is allowed to add an object, False otherwise.
"""
perm_string = '%s.add_%s' % (self.model._meta.app_label,
self.model._meta.object_name.lower()
)
return request.user.has_perm(perm_s... | python | def has_add_permission(self, request):
"""
Returns True if the requesting user is allowed to add an object, False otherwise.
"""
perm_string = '%s.add_%s' % (self.model._meta.app_label,
self.model._meta.object_name.lower()
)
return request.user.has_perm(perm_s... | [
"def",
"has_add_permission",
"(",
"self",
",",
"request",
")",
":",
"perm_string",
"=",
"'%s.add_%s'",
"%",
"(",
"self",
".",
"model",
".",
"_meta",
".",
"app_label",
",",
"self",
".",
"model",
".",
"_meta",
".",
"object_name",
".",
"lower",
"(",
")",
... | Returns True if the requesting user is allowed to add an object, False otherwise. | [
"Returns",
"True",
"if",
"the",
"requesting",
"user",
"is",
"allowed",
"to",
"add",
"an",
"object",
"False",
"otherwise",
"."
] | train | https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L212-L219 |
zmathew/django-backbone | backbone/views.py | BackboneAPIView.has_update_permission | def has_update_permission(self, request, obj):
"""
Returns True if the requesting user is allowed to update the given object, False otherwise.
"""
perm_string = '%s.change_%s' % (self.model._meta.app_label,
self.model._meta.object_name.lower()
)
return request... | python | def has_update_permission(self, request, obj):
"""
Returns True if the requesting user is allowed to update the given object, False otherwise.
"""
perm_string = '%s.change_%s' % (self.model._meta.app_label,
self.model._meta.object_name.lower()
)
return request... | [
"def",
"has_update_permission",
"(",
"self",
",",
"request",
",",
"obj",
")",
":",
"perm_string",
"=",
"'%s.change_%s'",
"%",
"(",
"self",
".",
"model",
".",
"_meta",
".",
"app_label",
",",
"self",
".",
"model",
".",
"_meta",
".",
"object_name",
".",
"lo... | Returns True if the requesting user is allowed to update the given object, False otherwise. | [
"Returns",
"True",
"if",
"the",
"requesting",
"user",
"is",
"allowed",
"to",
"update",
"the",
"given",
"object",
"False",
"otherwise",
"."
] | train | https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L231-L238 |
zmathew/django-backbone | backbone/views.py | BackboneAPIView.serialize | def serialize(self, obj, fields):
"""
Serializes a single model instance to a Python dict, based on the specified list of fields.
"""
data = {}
remaining_fields = []
for field in fields:
if callable(field): # Callable
data[field.__name__] = f... | python | def serialize(self, obj, fields):
"""
Serializes a single model instance to a Python dict, based on the specified list of fields.
"""
data = {}
remaining_fields = []
for field in fields:
if callable(field): # Callable
data[field.__name__] = f... | [
"def",
"serialize",
"(",
"self",
",",
"obj",
",",
"fields",
")",
":",
"data",
"=",
"{",
"}",
"remaining_fields",
"=",
"[",
"]",
"for",
"field",
"in",
"fields",
":",
"if",
"callable",
"(",
"field",
")",
":",
"# Callable",
"data",
"[",
"field",
".",
... | Serializes a single model instance to a Python dict, based on the specified list of fields. | [
"Serializes",
"a",
"single",
"model",
"instance",
"to",
"a",
"Python",
"dict",
"based",
"on",
"the",
"specified",
"list",
"of",
"fields",
"."
] | train | https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L259-L295 |
zmathew/django-backbone | backbone/views.py | BackboneAPIView.json_dumps | def json_dumps(self, data, **options):
"""
Wrapper around `json.dumps` that uses a special JSON encoder.
"""
params = {'sort_keys': True, 'indent': 2}
params.update(options)
# This code is based off django's built in JSON serializer
if json.__version__.split('.') ... | python | def json_dumps(self, data, **options):
"""
Wrapper around `json.dumps` that uses a special JSON encoder.
"""
params = {'sort_keys': True, 'indent': 2}
params.update(options)
# This code is based off django's built in JSON serializer
if json.__version__.split('.') ... | [
"def",
"json_dumps",
"(",
"self",
",",
"data",
",",
"*",
"*",
"options",
")",
":",
"params",
"=",
"{",
"'sort_keys'",
":",
"True",
",",
"'indent'",
":",
"2",
"}",
"params",
".",
"update",
"(",
"options",
")",
"# This code is based off django's built in JSON ... | Wrapper around `json.dumps` that uses a special JSON encoder. | [
"Wrapper",
"around",
"json",
".",
"dumps",
"that",
"uses",
"a",
"special",
"JSON",
"encoder",
"."
] | train | https://github.com/zmathew/django-backbone/blob/53505a247fb058e64a103c4f11da66993037bd6b/backbone/views.py#L297-L307 |
artefactual-labs/mets-reader-writer | metsrw/fsentry.py | FSEntry.dir | def dir(cls, label, children):
"""Return ``FSEntry`` directory object."""
return FSEntry(label=label, children=children, type=u"Directory", use=None) | python | def dir(cls, label, children):
"""Return ``FSEntry`` directory object."""
return FSEntry(label=label, children=children, type=u"Directory", use=None) | [
"def",
"dir",
"(",
"cls",
",",
"label",
",",
"children",
")",
":",
"return",
"FSEntry",
"(",
"label",
"=",
"label",
",",
"children",
"=",
"children",
",",
"type",
"=",
"u\"Directory\"",
",",
"use",
"=",
"None",
")"
] | Return ``FSEntry`` directory object. | [
"Return",
"FSEntry",
"directory",
"object",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/fsentry.py#L170-L172 |
artefactual-labs/mets-reader-writer | metsrw/fsentry.py | FSEntry.from_fptr | def from_fptr(cls, label, type_, fptr):
"""Return ``FSEntry`` object."""
return FSEntry(
label=label,
type=type_,
path=fptr.path,
use=fptr.use,
file_uuid=fptr.file_uuid,
derived_from=fptr.derived_from,
checksum=fptr.chec... | python | def from_fptr(cls, label, type_, fptr):
"""Return ``FSEntry`` object."""
return FSEntry(
label=label,
type=type_,
path=fptr.path,
use=fptr.use,
file_uuid=fptr.file_uuid,
derived_from=fptr.derived_from,
checksum=fptr.chec... | [
"def",
"from_fptr",
"(",
"cls",
",",
"label",
",",
"type_",
",",
"fptr",
")",
":",
"return",
"FSEntry",
"(",
"label",
"=",
"label",
",",
"type",
"=",
"type_",
",",
"path",
"=",
"fptr",
".",
"path",
",",
"use",
"=",
"fptr",
".",
"use",
",",
"file_... | Return ``FSEntry`` object. | [
"Return",
"FSEntry",
"object",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/fsentry.py#L175-L186 |
artefactual-labs/mets-reader-writer | metsrw/fsentry.py | FSEntry.file_id | def file_id(self):
""" Returns the fptr @FILEID if this is not a Directory. """
if self.type.lower() == "directory":
return None
if self.file_uuid is None:
raise exceptions.MetsError(
"No FILEID: File %s does not have file_uuid set" % self.path
... | python | def file_id(self):
""" Returns the fptr @FILEID if this is not a Directory. """
if self.type.lower() == "directory":
return None
if self.file_uuid is None:
raise exceptions.MetsError(
"No FILEID: File %s does not have file_uuid set" % self.path
... | [
"def",
"file_id",
"(",
"self",
")",
":",
"if",
"self",
".",
"type",
".",
"lower",
"(",
")",
"==",
"\"directory\"",
":",
"return",
"None",
"if",
"self",
".",
"file_uuid",
"is",
"None",
":",
"raise",
"exceptions",
".",
"MetsError",
"(",
"\"No FILEID: File ... | Returns the fptr @FILEID if this is not a Directory. | [
"Returns",
"the",
"fptr"
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/fsentry.py#L198-L208 |
artefactual-labs/mets-reader-writer | metsrw/fsentry.py | FSEntry.group_id | def group_id(self):
"""
Returns the @GROUPID.
If derived_from is set, returns that group_id.
"""
if self.derived_from is not None:
return self.derived_from.group_id()
if self.file_uuid is None:
return None
return utils.GROUP_ID_PREFIX + se... | python | def group_id(self):
"""
Returns the @GROUPID.
If derived_from is set, returns that group_id.
"""
if self.derived_from is not None:
return self.derived_from.group_id()
if self.file_uuid is None:
return None
return utils.GROUP_ID_PREFIX + se... | [
"def",
"group_id",
"(",
"self",
")",
":",
"if",
"self",
".",
"derived_from",
"is",
"not",
"None",
":",
"return",
"self",
".",
"derived_from",
".",
"group_id",
"(",
")",
"if",
"self",
".",
"file_uuid",
"is",
"None",
":",
"return",
"None",
"return",
"uti... | Returns the @GROUPID.
If derived_from is set, returns that group_id. | [
"Returns",
"the",
"@GROUPID",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/fsentry.py#L210-L220 |
artefactual-labs/mets-reader-writer | metsrw/fsentry.py | FSEntry._add_metadata_element | def _add_metadata_element(self, md, subsection, mdtype, mode="mdwrap", **kwargs):
"""
:param md: Value to pass to the MDWrap/MDRef
:param str subsection: Metadata tag to create. See :const:`SubSection.ALLOWED_SUBSECTIONS`
:param str mdtype: Value for mdWrap/mdRef @MDTYPE
:param ... | python | def _add_metadata_element(self, md, subsection, mdtype, mode="mdwrap", **kwargs):
"""
:param md: Value to pass to the MDWrap/MDRef
:param str subsection: Metadata tag to create. See :const:`SubSection.ALLOWED_SUBSECTIONS`
:param str mdtype: Value for mdWrap/mdRef @MDTYPE
:param ... | [
"def",
"_add_metadata_element",
"(",
"self",
",",
"md",
",",
"subsection",
",",
"mdtype",
",",
"mode",
"=",
"\"mdwrap\"",
",",
"*",
"*",
"kwargs",
")",
":",
"# HELP how handle multiple amdSecs?",
"# When adding *MD which amdSec to add to?",
"if",
"mode",
".",
"lower... | :param md: Value to pass to the MDWrap/MDRef
:param str subsection: Metadata tag to create. See :const:`SubSection.ALLOWED_SUBSECTIONS`
:param str mdtype: Value for mdWrap/mdRef @MDTYPE
:param str mode: 'mdwrap' or 'mdref'
:param str loctype: Required if mode is 'mdref'. LOCTYPE of a md... | [
":",
"param",
"md",
":",
"Value",
"to",
"pass",
"to",
"the",
"MDWrap",
"/",
"MDRef",
":",
"param",
"str",
"subsection",
":",
"Metadata",
"tag",
"to",
"create",
".",
"See",
":",
"const",
":",
"SubSection",
".",
"ALLOWED_SUBSECTIONS",
":",
"param",
"str",
... | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/fsentry.py#L243-L275 |
artefactual-labs/mets-reader-writer | metsrw/fsentry.py | FSEntry.serialize_md_inst | def serialize_md_inst(self, md_inst, md_class):
"""Serialize object ``md_inst`` by transforming it into an
``lxml.etree._ElementTree``. If it already is such, return it. If not,
make sure it is the correct type and return the output of calling
``seriaize()`` on it.
"""
va... | python | def serialize_md_inst(self, md_inst, md_class):
"""Serialize object ``md_inst`` by transforming it into an
``lxml.etree._ElementTree``. If it already is such, return it. If not,
make sure it is the correct type and return the output of calling
``seriaize()`` on it.
"""
va... | [
"def",
"serialize_md_inst",
"(",
"self",
",",
"md_inst",
",",
"md_class",
")",
":",
"valid_insts",
"=",
"tuple",
"(",
"chain",
"(",
"(",
"etree",
".",
"_ElementTree",
",",
"etree",
".",
"_Element",
")",
",",
"six",
".",
"string_types",
")",
")",
"if",
... | Serialize object ``md_inst`` by transforming it into an
``lxml.etree._ElementTree``. If it already is such, return it. If not,
make sure it is the correct type and return the output of calling
``seriaize()`` on it. | [
"Serialize",
"object",
"md_inst",
"by",
"transforming",
"it",
"into",
"an",
"lxml",
".",
"etree",
".",
"_ElementTree",
".",
"If",
"it",
"already",
"is",
"such",
"return",
"it",
".",
"If",
"not",
"make",
"sure",
"it",
"is",
"the",
"correct",
"type",
"and"... | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/fsentry.py#L289-L304 |
artefactual-labs/mets-reader-writer | metsrw/fsentry.py | FSEntry.add_child | def add_child(self, child):
"""Add a child FSEntry to this FSEntry.
Only FSEntrys with a type of 'directory' can have children.
This does not detect cyclic parent/child relationships, but that will
cause problems.
:param metsrw.fsentry.FSEntry child: FSEntry to add as a child
... | python | def add_child(self, child):
"""Add a child FSEntry to this FSEntry.
Only FSEntrys with a type of 'directory' can have children.
This does not detect cyclic parent/child relationships, but that will
cause problems.
:param metsrw.fsentry.FSEntry child: FSEntry to add as a child
... | [
"def",
"add_child",
"(",
"self",
",",
"child",
")",
":",
"if",
"self",
".",
"type",
".",
"lower",
"(",
")",
"!=",
"\"directory\"",
":",
"raise",
"ValueError",
"(",
"\"Only directory objects can have children\"",
")",
"if",
"child",
"is",
"self",
":",
"raise"... | Add a child FSEntry to this FSEntry.
Only FSEntrys with a type of 'directory' can have children.
This does not detect cyclic parent/child relationships, but that will
cause problems.
:param metsrw.fsentry.FSEntry child: FSEntry to add as a child
:return: The newly added child
... | [
"Add",
"a",
"child",
"FSEntry",
"to",
"this",
"FSEntry",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/fsentry.py#L337-L357 |
artefactual-labs/mets-reader-writer | metsrw/fsentry.py | FSEntry.remove_child | def remove_child(self, child):
"""
Remove a child from this FSEntry
If `child` is not actually a child of this entry, nothing happens.
:param child: Child to remove
"""
try:
self._children.remove(child)
except ValueError: # Child may not be in list
... | python | def remove_child(self, child):
"""
Remove a child from this FSEntry
If `child` is not actually a child of this entry, nothing happens.
:param child: Child to remove
"""
try:
self._children.remove(child)
except ValueError: # Child may not be in list
... | [
"def",
"remove_child",
"(",
"self",
",",
"child",
")",
":",
"try",
":",
"self",
".",
"_children",
".",
"remove",
"(",
"child",
")",
"except",
"ValueError",
":",
"# Child may not be in list",
"pass",
"else",
":",
"child",
".",
"parent",
"=",
"None"
] | Remove a child from this FSEntry
If `child` is not actually a child of this entry, nothing happens.
:param child: Child to remove | [
"Remove",
"a",
"child",
"from",
"this",
"FSEntry"
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/fsentry.py#L359-L372 |
artefactual-labs/mets-reader-writer | metsrw/fsentry.py | FSEntry.serialize_filesec | def serialize_filesec(self):
"""
Return the file Element for this file, appropriate for use in a fileSec.
If this is not an Item or has no use, return None.
:return: fileSec element for this FSEntry
"""
if (
self.type.lower() not in ("item", "archival inform... | python | def serialize_filesec(self):
"""
Return the file Element for this file, appropriate for use in a fileSec.
If this is not an Item or has no use, return None.
:return: fileSec element for this FSEntry
"""
if (
self.type.lower() not in ("item", "archival inform... | [
"def",
"serialize_filesec",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"type",
".",
"lower",
"(",
")",
"not",
"in",
"(",
"\"item\"",
",",
"\"archival information package\"",
")",
"or",
"self",
".",
"use",
"is",
"None",
")",
":",
"return",
"None",
"... | Return the file Element for this file, appropriate for use in a fileSec.
If this is not an Item or has no use, return None.
:return: fileSec element for this FSEntry | [
"Return",
"the",
"file",
"Element",
"for",
"this",
"file",
"appropriate",
"for",
"use",
"in",
"a",
"fileSec",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/fsentry.py#L376-L416 |
artefactual-labs/mets-reader-writer | metsrw/fsentry.py | FSEntry.is_empty_dir | def is_empty_dir(self):
"""Returns ``True`` if this fs item is a directory with no children or
a directory with only other empty directories as children.
"""
if self.mets_div_type == "Directory":
children = self._children
if children:
if all(child.... | python | def is_empty_dir(self):
"""Returns ``True`` if this fs item is a directory with no children or
a directory with only other empty directories as children.
"""
if self.mets_div_type == "Directory":
children = self._children
if children:
if all(child.... | [
"def",
"is_empty_dir",
"(",
"self",
")",
":",
"if",
"self",
".",
"mets_div_type",
"==",
"\"Directory\"",
":",
"children",
"=",
"self",
".",
"_children",
"if",
"children",
":",
"if",
"all",
"(",
"child",
".",
"is_empty_dir",
"for",
"child",
"in",
"children"... | Returns ``True`` if this fs item is a directory with no children or
a directory with only other empty directories as children. | [
"Returns",
"True",
"if",
"this",
"fs",
"item",
"is",
"a",
"directory",
"with",
"no",
"children",
"or",
"a",
"directory",
"with",
"only",
"other",
"empty",
"directories",
"as",
"children",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/fsentry.py#L419-L433 |
artefactual-labs/mets-reader-writer | metsrw/fsentry.py | FSEntry.serialize_structmap | def serialize_structmap(self, recurse=True, normative=False):
"""Return the div Element for this file, appropriate for use in a
structMap.
If this FSEntry represents a directory, its children will be
recursively appended to itself. If this FSEntry represents a file, it
will cont... | python | def serialize_structmap(self, recurse=True, normative=False):
"""Return the div Element for this file, appropriate for use in a
structMap.
If this FSEntry represents a directory, its children will be
recursively appended to itself. If this FSEntry represents a file, it
will cont... | [
"def",
"serialize_structmap",
"(",
"self",
",",
"recurse",
"=",
"True",
",",
"normative",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"label",
":",
"return",
"None",
"# Empty directories are not included in the physical structmap.",
"if",
"self",
".",
"is_em... | Return the div Element for this file, appropriate for use in a
structMap.
If this FSEntry represents a directory, its children will be
recursively appended to itself. If this FSEntry represents a file, it
will contain a <fptr> element.
:param bool recurse: If true, serialize an... | [
"Return",
"the",
"div",
"Element",
"for",
"this",
"file",
"appropriate",
"for",
"use",
"in",
"a",
"structMap",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/fsentry.py#L435-L469 |
icgood/pysasl | pysasl/__init__.py | AuthenticationCredentials.check_secret | def check_secret(self, secret):
"""Checks if the secret string used in the authentication attempt
matches the "known" secret string. Some mechanisms will override this
method to control how this comparison is made.
Args:
secret: The secret string to compare against what was ... | python | def check_secret(self, secret):
"""Checks if the secret string used in the authentication attempt
matches the "known" secret string. Some mechanisms will override this
method to control how this comparison is made.
Args:
secret: The secret string to compare against what was ... | [
"def",
"check_secret",
"(",
"self",
",",
"secret",
")",
":",
"try",
":",
"return",
"hmac",
".",
"compare_digest",
"(",
"secret",
",",
"self",
".",
"secret",
")",
"except",
"AttributeError",
":",
"# pragma: no cover",
"return",
"secret",
"==",
"self",
".",
... | Checks if the secret string used in the authentication attempt
matches the "known" secret string. Some mechanisms will override this
method to control how this comparison is made.
Args:
secret: The secret string to compare against what was used in the
authentication ... | [
"Checks",
"if",
"the",
"secret",
"string",
"used",
"in",
"the",
"authentication",
"attempt",
"matches",
"the",
"known",
"secret",
"string",
".",
"Some",
"mechanisms",
"will",
"override",
"this",
"method",
"to",
"control",
"how",
"this",
"comparison",
"is",
"ma... | train | https://github.com/icgood/pysasl/blob/241bdd349577cc99f05c4239755c307e6a46018c/pysasl/__init__.py#L107-L123 |
icgood/pysasl | pysasl/__init__.py | SASLAuth.secure | def secure(cls):
"""Uses only authentication mechanisms that are secure for use in
non-encrypted sessions.
Returns:
A new :class:`SASLAuth` object.
"""
builtin_mechs = cls._get_builtin_mechanisms()
secure_mechs = [mech for _, mech in builtin_mechs.items()
... | python | def secure(cls):
"""Uses only authentication mechanisms that are secure for use in
non-encrypted sessions.
Returns:
A new :class:`SASLAuth` object.
"""
builtin_mechs = cls._get_builtin_mechanisms()
secure_mechs = [mech for _, mech in builtin_mechs.items()
... | [
"def",
"secure",
"(",
"cls",
")",
":",
"builtin_mechs",
"=",
"cls",
".",
"_get_builtin_mechanisms",
"(",
")",
"secure_mechs",
"=",
"[",
"mech",
"for",
"_",
",",
"mech",
"in",
"builtin_mechs",
".",
"items",
"(",
")",
"if",
"not",
"mech",
".",
"insecure",
... | Uses only authentication mechanisms that are secure for use in
non-encrypted sessions.
Returns:
A new :class:`SASLAuth` object. | [
"Uses",
"only",
"authentication",
"mechanisms",
"that",
"are",
"secure",
"for",
"use",
"in",
"non",
"-",
"encrypted",
"sessions",
"."
] | train | https://github.com/icgood/pysasl/blob/241bdd349577cc99f05c4239755c307e6a46018c/pysasl/__init__.py#L312-L323 |
icgood/pysasl | pysasl/__init__.py | SASLAuth.plaintext | def plaintext(cls):
"""Uses only authentication mechanisms that provide the credentials in
un-hashed form, typically meaning
:attr:`~pysasl.AuthenticationCredentials.has_secret` is True.
Returns:
A new :class:`SASLAuth` object.
"""
builtin_mechs = cls._get_b... | python | def plaintext(cls):
"""Uses only authentication mechanisms that provide the credentials in
un-hashed form, typically meaning
:attr:`~pysasl.AuthenticationCredentials.has_secret` is True.
Returns:
A new :class:`SASLAuth` object.
"""
builtin_mechs = cls._get_b... | [
"def",
"plaintext",
"(",
"cls",
")",
":",
"builtin_mechs",
"=",
"cls",
".",
"_get_builtin_mechanisms",
"(",
")",
"plaintext_mechs",
"=",
"[",
"mech",
"for",
"_",
",",
"mech",
"in",
"builtin_mechs",
".",
"items",
"(",
")",
"if",
"mech",
".",
"insecure",
"... | Uses only authentication mechanisms that provide the credentials in
un-hashed form, typically meaning
:attr:`~pysasl.AuthenticationCredentials.has_secret` is True.
Returns:
A new :class:`SASLAuth` object. | [
"Uses",
"only",
"authentication",
"mechanisms",
"that",
"provide",
"the",
"credentials",
"in",
"un",
"-",
"hashed",
"form",
"typically",
"meaning",
":",
"attr",
":",
"~pysasl",
".",
"AuthenticationCredentials",
".",
"has_secret",
"is",
"True",
"."
] | train | https://github.com/icgood/pysasl/blob/241bdd349577cc99f05c4239755c307e6a46018c/pysasl/__init__.py#L326-L338 |
icgood/pysasl | pysasl/__init__.py | SASLAuth.server_mechanisms | def server_mechanisms(self):
"""List of available :class:`ServerMechanism` objects."""
return [mech for mech in self.mechs.values()
if isinstance(mech, ServerMechanism)] | python | def server_mechanisms(self):
"""List of available :class:`ServerMechanism` objects."""
return [mech for mech in self.mechs.values()
if isinstance(mech, ServerMechanism)] | [
"def",
"server_mechanisms",
"(",
"self",
")",
":",
"return",
"[",
"mech",
"for",
"mech",
"in",
"self",
".",
"mechs",
".",
"values",
"(",
")",
"if",
"isinstance",
"(",
"mech",
",",
"ServerMechanism",
")",
"]"
] | List of available :class:`ServerMechanism` objects. | [
"List",
"of",
"available",
":",
"class",
":",
"ServerMechanism",
"objects",
"."
] | train | https://github.com/icgood/pysasl/blob/241bdd349577cc99f05c4239755c307e6a46018c/pysasl/__init__.py#L355-L358 |
icgood/pysasl | pysasl/__init__.py | SASLAuth.client_mechanisms | def client_mechanisms(self):
"""List of available :class:`ClientMechanism` objects."""
return [mech for mech in self.mechs.values()
if isinstance(mech, ClientMechanism)] | python | def client_mechanisms(self):
"""List of available :class:`ClientMechanism` objects."""
return [mech for mech in self.mechs.values()
if isinstance(mech, ClientMechanism)] | [
"def",
"client_mechanisms",
"(",
"self",
")",
":",
"return",
"[",
"mech",
"for",
"mech",
"in",
"self",
".",
"mechs",
".",
"values",
"(",
")",
"if",
"isinstance",
"(",
"mech",
",",
"ClientMechanism",
")",
"]"
] | List of available :class:`ClientMechanism` objects. | [
"List",
"of",
"available",
":",
"class",
":",
"ClientMechanism",
"objects",
"."
] | train | https://github.com/icgood/pysasl/blob/241bdd349577cc99f05c4239755c307e6a46018c/pysasl/__init__.py#L361-L364 |
icgood/pysasl | pysasl/__init__.py | SASLAuth.get_server | def get_server(self, name):
"""Like :meth:`.get`, but only mechanisms inheriting
:class:`ServerMechanism` will be returned.
Args:
name: The SASL mechanism name.
Returns:
The mechanism object or ``None``
"""
mech = self.get(name)
return m... | python | def get_server(self, name):
"""Like :meth:`.get`, but only mechanisms inheriting
:class:`ServerMechanism` will be returned.
Args:
name: The SASL mechanism name.
Returns:
The mechanism object or ``None``
"""
mech = self.get(name)
return m... | [
"def",
"get_server",
"(",
"self",
",",
"name",
")",
":",
"mech",
"=",
"self",
".",
"get",
"(",
"name",
")",
"return",
"mech",
"if",
"isinstance",
"(",
"mech",
",",
"ServerMechanism",
")",
"else",
"None"
] | Like :meth:`.get`, but only mechanisms inheriting
:class:`ServerMechanism` will be returned.
Args:
name: The SASL mechanism name.
Returns:
The mechanism object or ``None`` | [
"Like",
":",
"meth",
":",
".",
"get",
"but",
"only",
"mechanisms",
"inheriting",
":",
"class",
":",
"ServerMechanism",
"will",
"be",
"returned",
"."
] | train | https://github.com/icgood/pysasl/blob/241bdd349577cc99f05c4239755c307e6a46018c/pysasl/__init__.py#L379-L391 |
icgood/pysasl | pysasl/__init__.py | SASLAuth.get_client | def get_client(self, name):
"""Like :meth:`.get`, but only mechanisms inheriting
:class:`ClientMechanism` will be returned.
Args:
name: The SASL mechanism name.
Returns:
The mechanism object or ``None``
"""
mech = self.get(name)
return m... | python | def get_client(self, name):
"""Like :meth:`.get`, but only mechanisms inheriting
:class:`ClientMechanism` will be returned.
Args:
name: The SASL mechanism name.
Returns:
The mechanism object or ``None``
"""
mech = self.get(name)
return m... | [
"def",
"get_client",
"(",
"self",
",",
"name",
")",
":",
"mech",
"=",
"self",
".",
"get",
"(",
"name",
")",
"return",
"mech",
"if",
"isinstance",
"(",
"mech",
",",
"ClientMechanism",
")",
"else",
"None"
] | Like :meth:`.get`, but only mechanisms inheriting
:class:`ClientMechanism` will be returned.
Args:
name: The SASL mechanism name.
Returns:
The mechanism object or ``None`` | [
"Like",
":",
"meth",
":",
".",
"get",
"but",
"only",
"mechanisms",
"inheriting",
":",
"class",
":",
"ClientMechanism",
"will",
"be",
"returned",
"."
] | train | https://github.com/icgood/pysasl/blob/241bdd349577cc99f05c4239755c307e6a46018c/pysasl/__init__.py#L393-L405 |
artefactual-labs/mets-reader-writer | metsrw/mets.py | METSDocument.read | def read(cls, source):
"""Read ``source`` into a ``METSDocument`` instance. This is an
instance constructor. The ``source`` may be a path to a METS file, a
file-like object, or a string of XML.
"""
if hasattr(source, "read"):
return cls.fromfile(source)
if os.... | python | def read(cls, source):
"""Read ``source`` into a ``METSDocument`` instance. This is an
instance constructor. The ``source`` may be a path to a METS file, a
file-like object, or a string of XML.
"""
if hasattr(source, "read"):
return cls.fromfile(source)
if os.... | [
"def",
"read",
"(",
"cls",
",",
"source",
")",
":",
"if",
"hasattr",
"(",
"source",
",",
"\"read\"",
")",
":",
"return",
"cls",
".",
"fromfile",
"(",
"source",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"source",
")",
":",
"return",
"cls",
... | Read ``source`` into a ``METSDocument`` instance. This is an
instance constructor. The ``source`` may be a path to a METS file, a
file-like object, or a string of XML. | [
"Read",
"source",
"into",
"a",
"METSDocument",
"instance",
".",
"This",
"is",
"an",
"instance",
"constructor",
".",
"The",
"source",
"may",
"be",
"a",
"path",
"to",
"a",
"METS",
"file",
"a",
"file",
"-",
"like",
"object",
"or",
"a",
"string",
"of",
"XM... | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L46-L57 |
artefactual-labs/mets-reader-writer | metsrw/mets.py | METSDocument._collect_all_files | def _collect_all_files(self, files=None):
"""
Collect all FSEntrys into a set, including all descendants.
:param list files: List of :class:`FSEntry` to traverse.
:returns: Set of FSEntry
"""
if files is None:
files = self._root_elements
collected = s... | python | def _collect_all_files(self, files=None):
"""
Collect all FSEntrys into a set, including all descendants.
:param list files: List of :class:`FSEntry` to traverse.
:returns: Set of FSEntry
"""
if files is None:
files = self._root_elements
collected = s... | [
"def",
"_collect_all_files",
"(",
"self",
",",
"files",
"=",
"None",
")",
":",
"if",
"files",
"is",
"None",
":",
"files",
"=",
"self",
".",
"_root_elements",
"collected",
"=",
"set",
"(",
")",
"for",
"entry",
"in",
"files",
":",
"collected",
".",
"add"... | Collect all FSEntrys into a set, including all descendants.
:param list files: List of :class:`FSEntry` to traverse.
:returns: Set of FSEntry | [
"Collect",
"all",
"FSEntrys",
"into",
"a",
"set",
"including",
"all",
"descendants",
"."
] | train | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/mets.py#L61-L74 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.