sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def bed_occupied(self):
"""
bed_occupied: None -> boolean
Determines whether the bed is currently occupied by requesting
data from the remote XBee and comparing the analog value with
a threshold.
"""
# Receive samples from the remote device
self._set_sen... | bed_occupied: None -> boolean
Determines whether the bed is currently occupied by requesting
data from the remote XBee and comparing the analog value with
a threshold. | entailment |
def checksum(self):
"""
checksum: None -> single checksum byte
checksum adds all bytes of the binary, unescaped data in the
frame, saves the last byte of the result, and subtracts it from
0xFF. The final result is the checksum
"""
total = 0
# Add togethe... | checksum: None -> single checksum byte
checksum adds all bytes of the binary, unescaped data in the
frame, saves the last byte of the result, and subtracts it from
0xFF. The final result is the checksum | entailment |
def verify(self, chksum):
"""
verify: 1 byte -> boolean
verify checksums the frame, adds the expected checksum, and
determines whether the result is correct. The result should
be 0xFF.
"""
total = 0
# Add together all bytes
for byte in self.data:... | verify: 1 byte -> boolean
verify checksums the frame, adds the expected checksum, and
determines whether the result is correct. The result should
be 0xFF. | entailment |
def output(self):
"""
output: None -> valid API frame (binary data)
output will produce a valid API frame for transmission to an
XBee module.
"""
# start is one byte long, length is two bytes
# data is n bytes long (indicated by length)
# chksum is one by... | output: None -> valid API frame (binary data)
output will produce a valid API frame for transmission to an
XBee module. | entailment |
def escape(data):
"""
escape: byte string -> byte string
When a 'special' byte is encountered in the given data string,
it is preceded by an escape byte and XORed with 0x20.
"""
escaped_data = b""
for byte in data:
if intToByte(byteToInt(byte)) in AP... | escape: byte string -> byte string
When a 'special' byte is encountered in the given data string,
it is preceded by an escape byte and XORed with 0x20. | entailment |
def fill(self, byte):
"""
fill: byte -> None
Adds the given raw byte to this APIFrame. If this APIFrame is marked
as escaped and this byte is an escape byte, the next byte in a call
to fill() will be unescaped.
"""
if self._unescape_next_byte:
byte =... | fill: byte -> None
Adds the given raw byte to this APIFrame. If this APIFrame is marked
as escaped and this byte is an escape byte, the next byte in a call
to fill() will be unescaped. | entailment |
def parse(self):
"""
parse: None -> None
Given a valid API frame, parse extracts the data contained
inside it and verifies it against its checksum
"""
if len(self.raw_data) < 3:
ValueError("parse() may only be called on a frame containing at "
... | parse: None -> None
Given a valid API frame, parse extracts the data contained
inside it and verifies it against its checksum | entailment |
def _parse_IS_at_response(self, packet_info):
"""
If the given packet is a successful remote AT response for an IS
command, parse the parameter field as IO data.
"""
if packet_info['id'] in ('at_response', 'remote_at_response') and \
packet_info['command'].lower()... | If the given packet is a successful remote AT response for an IS
command, parse the parameter field as IO data. | entailment |
def _parse_ND_at_response(self, packet_info):
"""
If the given packet is a successful AT response for an ND
command, parse the parameter field.
"""
if packet_info['id'] == 'at_response' and \
packet_info['command'].lower() == b'nd' and \
packet_inf... | If the given packet is a successful AT response for an ND
command, parse the parameter field. | entailment |
def halt(self):
"""
halt: None -> None
If this instance has a separate thread running, it will be
halted. This method will wait until the thread has cleaned
up before returning.
"""
if self._callback:
self._thread_continue = False
self._th... | halt: None -> None
If this instance has a separate thread running, it will be
halted. This method will wait until the thread has cleaned
up before returning. | entailment |
def run(self):
"""
run: None -> None
This method overrides threading.Thread.run() and is automatically
called when an instance is created with threading enabled.
"""
while True:
try:
self._callback(self.wait_read_frame())
except Th... | run: None -> None
This method overrides threading.Thread.run() and is automatically
called when an instance is created with threading enabled. | entailment |
def wait_read_frame(self, timeout=None):
"""
wait_read_frame: None -> frame info dictionary
wait_read_frame calls XBee._wait_for_frame() and waits until a
valid frame appears on the serial port. Once it receives a frame,
wait_read_frame attempts to parse the data contained withi... | wait_read_frame: None -> frame info dictionary
wait_read_frame calls XBee._wait_for_frame() and waits until a
valid frame appears on the serial port. Once it receives a frame,
wait_read_frame attempts to parse the data contained within it
and returns the resulting dictionary | entailment |
def _wait_for_frame(self, timeout=None):
"""
_wait_for_frame: None -> binary data
_wait_for_frame will read from the serial port until a valid
API frame arrives. It will then return the binary data
contained within the frame.
If this method is called as a separate threa... | _wait_for_frame: None -> binary data
_wait_for_frame will read from the serial port until a valid
API frame arrives. It will then return the binary data
contained within the frame.
If this method is called as a separate thread
and self.thread_continue is set to False, the threa... | entailment |
def main():
"""
Sends an API AT command to read the lower-order address bits from
an XBee Series 1 and looks for a response
"""
try:
# Open serial port
ser = serial.Serial('/dev/ttyUSB0', 9600)
# Create XBee Series 1 object
xbee = XBee(ser)
# Send AT packe... | Sends an API AT command to read the lower-order address bits from
an XBee Series 1 and looks for a response | entailment |
def halt(self):
"""
halt: None -> None
Stop the event, and remove the FD from the loop handler
"""
if self._callback:
self._running.clear()
self._ioloop.remove_handler(self.serial.fd)
if self._frame_future is not None:
self._f... | halt: None -> None
Stop the event, and remove the FD from the loop handler | entailment |
def process_frames(self):
"""
process_frames: None -> None
Wait for a frame to become available, when resolved call the callback
"""
while self._running.is_set():
try:
frame = yield self._get_frame()
info = self._split_response(frame.d... | process_frames: None -> None
Wait for a frame to become available, when resolved call the callback | entailment |
def _process_input(self, data, events):
"""
_process_input:
_process_input will be notified when there is data ready on the
serial connection to be read. It will read and process the data
into an API Frame and then either resolve a frame future, or push
the frame into t... | _process_input:
_process_input will be notified when there is data ready on the
serial connection to be read. It will read and process the data
into an API Frame and then either resolve a frame future, or push
the frame into the queue of frames needing to be processed | entailment |
def do_serial(self, p):
"""Set the serial port, e.g.: /dev/tty.usbserial-A4001ib8"""
try:
self.serial.port = p
self.serial.open()
print 'Opening serial port: %s' % p
except Exception, e:
print 'Unable to open serial port: %s' % p | Set the serial port, e.g.: /dev/tty.usbserial-A4001ib8 | entailment |
def register(self, name, callback, filter):
"""
register: string, function: string, data -> None,
function: data -> boolean -> None
Register will save the given name, callback, and filter function
for use when a packet arrives. When one arrives, the filter
function will ... | register: string, function: string, data -> None,
function: data -> boolean -> None
Register will save the given name, callback, and filter function
for use when a packet arrives. When one arrives, the filter
function will be called to determine whether to call its associated
ca... | entailment |
def run(self, oneshot=False):
"""
run: boolean -> None
run will read and dispatch any packet which arrives from the
XBee device
"""
if not self.xbee:
raise ValueError("Either a serial port or an XBee must be provided \
to __init__... | run: boolean -> None
run will read and dispatch any packet which arrives from the
XBee device | entailment |
def dispatch(self, packet):
"""
dispatch: XBee data dict -> None
When called, dispatch checks the given packet against each
registered callback method and calls each callback whose filter
function returns true.
"""
for handler in self.handlers:
if han... | dispatch: XBee data dict -> None
When called, dispatch checks the given packet against each
registered callback method and calls each callback whose filter
function returns true. | entailment |
def byteToInt(byte):
"""
byte -> int
Determines whether to use ord() or not to get a byte's value.
"""
if hasattr(byte, 'bit_length'):
# This is already an int
return byte
return ord(byte) if hasattr(byte, 'encode') else byte[0] | byte -> int
Determines whether to use ord() or not to get a byte's value. | entailment |
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... | Download data from talosintelligence.com for the given IP
Return tabbed data text | entailment |
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... | 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.
... | entailment |
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... | 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 ... | entailment |
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,
... | Build API request | entailment |
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 ... | 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... | entailment |
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... | 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 ... | entailment |
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... | 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 ... | entailment |
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 ... | 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_... | entailment |
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... | 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 | entailment |
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... | 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 ... | entailment |
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... | 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... | entailment |
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... | 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... | entailment |
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... | 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... | entailment |
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.
... | 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... | entailment |
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)
"""
... | 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) | entailment |
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.
... | 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... | entailment |
def text(self):
"""Text received from self.source."""
if isinstance(self.source, str):
return self.source
else:
return self.source() | Text received from self.source. | entailment |
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... | Write morphed text in Image object. | entailment |
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)... | Draw morphed line in Image object. | entailment |
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))
... | Generate white noise and merge it with given Image object. | entailment |
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)... | Randomly morph a single character. | entailment |
def _rndPointDisposition(dx, dy):
"""Return random disposition point."""
x = int(random.uniform(-dx, dx))
y = int(random.uniform(-dy, dy))
return (x, y) | Return random disposition point. | entailment |
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
) | Return points for QUAD transformation. | entailment |
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... | Path helper that allows passing a bottle view function. | entailment |
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... | Path helper that allows passing a Flask view function. | entailment |
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)
... | Generator of operations described in handler's http methods
:param handler_class:
:type handler_class: RequestHandler descendant | entailment |
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... | Convert Tornado URLSpec to OpenAPI-compliant path.
:param urlspec:
:type urlspec: URLSpec
:param method: Handler http method
:type method: function | entailment |
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... | Path helper that allows passing a Tornado URLSpec or tuple. | entailment |
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... | 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.
... | entailment |
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... | Convert camelCase to snake_case. | entailment |
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
... | Register a manually assigned id as used, to avoid collisions. | entailment |
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... | Create a new AMDSec by parsing root.
:param root: Element or ElementTree to be parsed into an object. | entailment |
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... | 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 | entailment |
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... | 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. | entailment |
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(
... | 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. | entailment |
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... | Returns the STATUS when serializing.
Calculates based on the subsection type and if it's replacing anything.
:returns: None or the STATUS string. | entailment |
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... | 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` | entailment |
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... | 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. | entailment |
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 ... | 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 | entailment |
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... | Create a new MDWrap by parsing root.
:param root: Element or ElementTree to be parsed into a MDWrap. | entailment |
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... | 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 | entailment |
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 ... | 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... | entailment |
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... | 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'
... | entailment |
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... | 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. | entailment |
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... | Convert an ``lxml._Element`` instance to a Python tuple. | entailment |
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... | 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'),
... | entailment |
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) | Transform a PREMIS ``lxml._Element`` instance to a Python tuple. | entailment |
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]
... | Find and return the first element-as-tuple in tuple ``data`` using simplified
XPath ``path``. | entailment |
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:
... | 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. | entailment |
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... | Dynamically create a sub-class of PREMISElement given
``tuple_instance``, which is a tuple representing an XML data structure. | entailment |
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] =... | Find and return all element-as-tuples in tuple ``data`` using simplified
XPath ``path``. | entailment |
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... | Return the text value of the element-as-tuple in tuple ``data`` using
simplified XPath ``path``. | entailment |
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... | 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. | entailment |
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... | Return ``True`` if tuple ``el`` represents an empty XML element. | entailment |
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',
... | 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... | entailment |
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")
... | 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. | entailment |
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... | 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'} | entailment |
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(
'... | Return as a 3-tuple, this PREMIS compression event's program,
version, and algorithm used to perform the compression. | entailment |
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 ... | 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'. | entailment |
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... | Return as a 3-tuple, this PREMIS encryption event's program,
version, and key used to perform the encryption. | entailment |
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):
... | 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. | entailment |
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... | 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... | entailment |
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... | Provide a feature named ``feature_name`` using the provider object
``provider`` and any arguments (``args``, ``kwargs``) needed by the
provider if it is callable. | entailment |
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) | Encode or decode ``url`` by applying ``func`` to all of its
URL-encodable parts. | entailment |
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:
... | Auto-discover INSTALLED_APPS backbone_api.py modules. | entailment |
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) | Registers the given backbone view class. | entailment |
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 | Returns the queryset (along with ordering) to be used when retrieving object(s). | entailment |
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... | Handles get requests for either the collection or an object detail. | entailment |
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... | Handles get requests for the details of the given object. | entailment |
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... | Handles get requests for the list of objects. | entailment |
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(_... | Handles post requests. | entailment |
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... | Adds an object. | entailment |
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... | Handles put requests. | entailment |
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... | Updates an object. | entailment |
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... | 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). | entailment |
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... | Handles delete requests. | entailment |
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... | Returns True if the requesting user is allowed to add an object, False otherwise. | entailment |
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... | Returns True if the requesting user is allowed to update the given object, False otherwise. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.