Code
stringlengths 103
85.9k
| Summary
listlengths 0
94
|
---|---|
Please provide a description of the function:def mark(request):
notification_id = request.POST.get('id', None)
action = request.POST.get('action', None)
success = True
if notification_id:
try:
notification = Notification.objects.get(pk=notification_id,
recipient=request.user)
if action == 'read':
notification.mark_as_read()
msg = _("Marked as read")
elif action == 'unread':
notification.mark_as_unread()
msg = _("Marked as unread")
else:
success = False
msg = _("Invalid mark action.")
except Notification.DoesNotExist:
success = False
msg = _("Notification does not exists.")
else:
success = False
msg = _("Invalid Notification ID")
ctx = {'msg': msg, 'success': success, 'action': action}
return notification_redirect(request, ctx) | [
"\n Handles marking of individual notifications as read or unread.\n Takes ``notification id`` and mark ``action`` as POST data.\n\n :param request: HTTP request context.\n\n :returns: Response to mark action of supplied notification ID.\n "
] |
Please provide a description of the function:def mark_all(request):
action = request.POST.get('action', None)
success = True
if action == 'read':
request.user.notifications.read_all()
msg = _("Marked all notifications as read")
elif action == 'unread':
request.user.notifications.unread_all()
msg = _("Marked all notifications as unread")
else:
msg = _("Invalid mark action")
success = False
ctx = {'msg': msg, 'success': success, 'action': action}
return notification_redirect(request, ctx) | [
"\n Marks notifications as either read or unread depending of POST parameters.\n Takes ``action`` as POST data, it can either be ``read`` or ``unread``.\n\n :param request: HTTP Request context.\n\n :return: Response to mark_all action.\n "
] |
Please provide a description of the function:def delete(request):
notification_id = request.POST.get('id', None)
success = True
if notification_id:
try:
notification = Notification.objects.get(pk=notification_id,
recipient=request.user)
soft_delete = getattr(settings, 'NOTIFY_SOFT_DELETE', True)
if soft_delete:
notification.deleted = True
notification.save()
else:
notification.delete()
msg = _("Deleted notification successfully")
except Notification.DoesNotExist:
success = False
msg = _("Notification does not exists.")
else:
success = False
msg = _("Invalid Notification ID")
ctx = {'msg': msg, 'success': success, }
return notification_redirect(request, ctx) | [
"\n Deletes notification of supplied notification ID.\n\n Depending on project settings, if ``NOTIFICATIONS_SOFT_DELETE``\n is set to ``False``, the notifications will be deleted from DB.\n If not, a soft delete will be performed.\n\n By default, notifications are deleted softly.\n\n :param request: HTTP request context.\n\n :return: Response to delete action on supplied notification ID.\n "
] |
Please provide a description of the function:def notification_update(request):
flag = request.GET.get('flag', None)
target = request.GET.get('target', 'box')
last_notification = int(flag) if flag.isdigit() else None
if last_notification:
new_notifications = request.user.notifications.filter(
id__gt=last_notification).active().prefetch()
msg = _("Notifications successfully retrieved.") \
if new_notifications else _("No new notifications.")
notification_list = []
for nf in new_notifications:
notification = nf.as_json()
notification_list.append(notification)
notification['html'] = render_notification(
nf, render_target=target, **notification)
ctx = {
"retrieved": len(new_notifications),
"unread_count": request.user.notifications.unread().count(),
"notifications": notification_list,
"success": True,
"msg": msg,
}
return JsonResponse(ctx)
else:
msg = _("Notification flag not sent.")
ctx = {"success": False, "msg": msg}
return JsonResponse(ctx) | [
"\n Handles live updating of notifications, follows ajax-polling approach.\n\n Read more: http://stackoverflow.com/a/12855533/4726598\n\n Required URL parameters: ``flag``.\n\n Explanation:\n\n - The ``flag`` parameter carries the last notification ID \\\n received by the user's browser.\n\n - This ``flag`` is most likely to be generated by using \\\n a simple JS/JQuery DOM. Just grab the first element of \\\n the notification list.\n\n - The element will have a ``data-id`` attribute set to the \\\n corresponding notification.\n - We'll use it's value as the flag parameter.\n\n - The view treats the ``last notification flag`` as a model \\\n ```filter()`` and fetches all notifications greater than \\\n the flag for the user.\n\n - Then the a JSON data is prepared with all necessary \\\n details such as, ``verb``, ``actor``, ``target`` and their \\\n URL etc. The foreignkey are serialized as their \\\n default ``__str__`` value.\n\n - Everything will be HTML escaped by django's ``escape()``.\n\n - Since these notification sent will only serve temporarily \\\n on the notification box and will be generated fresh \\\n using a whole template, to avoid client-side notification \\\n generation using the JSON data, the JSON data will also \\\n contain a rendered HTML string so that you can easily \\\n do a JQuery ``$yourNotificationBox.prepend()`` on the \\\n rendered html string of the notification.\n\n - The template used is expected to be different than the \\\n template used in full page notification as the css \\\n and some other elements are highly likely to be \\\n different than the full page notification list. \\\n\n - The template used will be the ``notification type`` of the \\\n notification suffixed ``_box.html``. So, if your \\\n notification type is ``comment_reply``, the template \\\n will be ``comment_reply_box.html``.\n\n - This template will be stored in ``notifications/includes/`` \\\n of your template directory.\n\n - That makes: ``notifications/includes/comment_reply_box.html``\n\n - The rest is self-explanatory.\n\n :param request: HTTP request context.\n\n :return: Notification updates (if any) in JSON format.\n "
] |
Please provide a description of the function:def read_and_redirect(request, notification_id):
notification_page = reverse('notifications:all')
next_page = request.GET.get('next', notification_page)
if is_safe_url(next_page):
target = next_page
else:
target = notification_page
try:
user_nf = request.user.notifications.get(pk=notification_id)
if not user_nf.read:
user_nf.mark_as_read()
except Notification.DoesNotExist:
pass
return HttpResponseRedirect(target) | [
"\n Marks the supplied notification as read and then redirects\n to the supplied URL from the ``next`` URL parameter.\n\n **IMPORTANT**: This is CSRF - unsafe method.\n Only use it if its okay for you to mark notifications \\\n as read without a robust check.\n\n :param request: HTTP request context.\n :param notification_id: ID of the notification to be marked a read.\n\n :returns: Redirect response to a valid target url.\n "
] |
Please provide a description of the function:def get_motion_detection(self):
url = ('%s/ISAPI/System/Video/inputs/'
'channels/1/motionDetection') % self.root_url
try:
response = self.hik_request.get(url, timeout=CONNECT_TIMEOUT)
except (requests.exceptions.RequestException,
requests.exceptions.ConnectionError) as err:
_LOGGING.error('Unable to fetch MotionDetection, error: %s', err)
self.motion_detection = None
return self.motion_detection
if response.status_code == requests.codes.unauthorized:
_LOGGING.error('Authentication failed')
self.motion_detection = None
return self.motion_detection
if response.status_code != requests.codes.ok:
# If we didn't receive 200, abort
_LOGGING.debug('Unable to fetch motion detection.')
self.motion_detection = None
return self.motion_detection
try:
tree = ET.fromstring(response.text)
ET.register_namespace("", self.namespace)
enabled = tree.find(self.element_query('enabled'))
if enabled is not None:
self._motion_detection_xml = tree
self.motion_detection = {'true': True, 'false': False}[enabled.text]
return self.motion_detection
except AttributeError as err:
_LOGGING.error('Entire response: %s', response.text)
_LOGGING.error('There was a problem: %s', err)
self.motion_detection = None
return self.motion_detection | [
"Fetch current motion state from camera"
] |
Please provide a description of the function:def _set_motion_detection(self, enable):
url = ('%s/ISAPI/System/Video/inputs/'
'channels/1/motionDetection') % self.root_url
enabled = self._motion_detection_xml.find(self.element_query('enabled'))
if enabled is None:
_LOGGING.error("Couldn't find 'enabled' in the xml")
_LOGGING.error('XML: %s', ET.tostring(self._motion_detection_xml))
return
enabled.text = 'true' if enable else 'false'
xml = ET.tostring(self._motion_detection_xml)
try:
response = self.hik_request.put(url, data=xml, timeout=CONNECT_TIMEOUT)
except (requests.exceptions.RequestException,
requests.exceptions.ConnectionError) as err:
_LOGGING.error('Unable to set MotionDetection, error: %s', err)
return
if response.status_code == requests.codes.unauthorized:
_LOGGING.error('Authentication failed')
return
if response.status_code != requests.codes.ok:
# If we didn't receive 200, abort
_LOGGING.error('Unable to set motion detection: %s', response.text)
self.motion_detection = enable | [
"Set desired motion detection state on camera"
] |
Please provide a description of the function:def add_update_callback(self, callback, sensor):
self._updateCallbacks.append([callback, sensor])
_LOGGING.debug('Added update callback to %s on %s', callback, sensor) | [
"Register as callback for when a matching device sensor changes."
] |
Please provide a description of the function:def _do_update_callback(self, msg):
for callback, sensor in self._updateCallbacks:
if sensor == msg:
_LOGGING.debug('Update callback %s for sensor %s',
callback, sensor)
callback(msg) | [
"Call registered callback functions."
] |
Please provide a description of the function:def initialize(self):
device_info = self.get_device_info()
if device_info is None:
self.name = None
self.cam_id = None
self.event_states = None
return
for key in device_info:
if key == 'deviceName':
self.name = device_info[key]
elif key == 'deviceID':
if len(device_info[key]) > 10:
self.cam_id = device_info[key]
else:
self.cam_id = uuid.uuid4()
events_available = self.get_event_triggers()
if events_available:
for event, channel_list in events_available.items():
for channel in channel_list:
try:
self.event_states.setdefault(
SENSOR_MAP[event.lower()], []).append(
[False, channel, 0, datetime.datetime.now()])
except KeyError:
# Sensor type doesn't have a known friendly name
# We can't reliably handle it at this time...
_LOGGING.warning(
'Sensor type "%s" is unsupported.', event)
_LOGGING.debug('Initialized Dictionary: %s', self.event_states)
else:
_LOGGING.debug('No Events available in dictionary.')
self.get_motion_detection() | [
"Initialize deviceInfo and available events."
] |
Please provide a description of the function:def get_device_info(self):
device_info = {}
url = '%s/ISAPI/System/deviceInfo' % self.root_url
using_digest = False
try:
response = self.hik_request.get(url, timeout=CONNECT_TIMEOUT)
if response.status_code == requests.codes.unauthorized:
_LOGGING.debug('Basic authentication failed. Using digest.')
self.hik_request.auth = HTTPDigestAuth(self.usr, self.pwd)
using_digest = True
response = self.hik_request.get(url)
if response.status_code == requests.codes.not_found:
# Try alternate URL for deviceInfo
_LOGGING.debug('Using alternate deviceInfo URL.')
url = '%s/System/deviceInfo' % self.root_url
response = self.hik_request.get(url)
# Seems to be difference between camera and nvr, they can't seem to
# agree if they should 404 or 401 first
if not using_digest and response.status_code == requests.codes.unauthorized:
_LOGGING.debug('Basic authentication failed. Using digest.')
self.hik_request.auth = HTTPDigestAuth(self.usr, self.pwd)
using_digest = True
response = self.hik_request.get(url)
except (requests.exceptions.RequestException,
requests.exceptions.ConnectionError) as err:
_LOGGING.error('Unable to fetch deviceInfo, error: %s', err)
return None
if response.status_code == requests.codes.unauthorized:
_LOGGING.error('Authentication failed')
return None
if response.status_code != requests.codes.ok:
# If we didn't receive 200, abort
_LOGGING.debug('Unable to fetch device info.')
return None
try:
tree = ET.fromstring(response.text)
# Try to fetch namespace from XML
nmsp = tree.tag.split('}')[0].strip('{')
self.namespace = nmsp if nmsp.startswith('http') else XML_NAMESPACE
_LOGGING.debug('Using Namespace: %s', self.namespace)
for item in tree:
tag = item.tag.split('}')[1]
device_info[tag] = item.text
return device_info
except AttributeError as err:
_LOGGING.error('Entire response: %s', response.text)
_LOGGING.error('There was a problem: %s', err)
return None | [
"Parse deviceInfo into dictionary."
] |
Please provide a description of the function:def watchdog_handler(self):
_LOGGING.debug('%s Watchdog expired. Resetting connection.', self.name)
self.watchdog.stop()
self.reset_thrd.set() | [
"Take care of threads if wachdog expires."
] |
Please provide a description of the function:def disconnect(self):
_LOGGING.debug('Disconnecting from stream: %s', self.name)
self.kill_thrd.set()
self.thrd.join()
_LOGGING.debug('Event stream thread for %s is stopped', self.name)
self.kill_thrd.clear() | [
"Disconnect from event stream."
] |
Please provide a description of the function:def alert_stream(self, reset_event, kill_event):
_LOGGING.debug('Stream Thread Started: %s, %s', self.name, self.cam_id)
start_event = False
parse_string = ""
fail_count = 0
url = '%s/ISAPI/Event/notification/alertStream' % self.root_url
# pylint: disable=too-many-nested-blocks
while True:
try:
stream = self.hik_request.get(url, stream=True,
timeout=(CONNECT_TIMEOUT,
READ_TIMEOUT))
if stream.status_code == requests.codes.not_found:
# Try alternate URL for stream
url = '%s/Event/notification/alertStream' % self.root_url
stream = self.hik_request.get(url, stream=True)
if stream.status_code != requests.codes.ok:
raise ValueError('Connection unsucessful.')
else:
_LOGGING.debug('%s Connection Successful.', self.name)
fail_count = 0
self.watchdog.start()
for line in stream.iter_lines():
# _LOGGING.debug('Processing line from %s', self.name)
# filter out keep-alive new lines
if line:
str_line = line.decode("utf-8", "ignore")
# New events start with --boundry
if str_line.find('<EventNotificationAlert') != -1:
# Start of event message
start_event = True
parse_string += str_line
elif str_line.find('</EventNotificationAlert>') != -1:
# Message end found found
parse_string += str_line
start_event = False
if parse_string:
tree = ET.fromstring(parse_string)
self.process_stream(tree)
self.update_stale()
parse_string = ""
else:
if start_event:
parse_string += str_line
if kill_event.is_set():
# We were asked to stop the thread so lets do so.
break
elif reset_event.is_set():
# We need to reset the connection.
raise ValueError('Watchdog failed.')
if kill_event.is_set():
# We were asked to stop the thread so lets do so.
_LOGGING.debug('Stopping event stream thread for %s',
self.name)
self.watchdog.stop()
self.hik_request.close()
return
elif reset_event.is_set():
# We need to reset the connection.
raise ValueError('Watchdog failed.')
except (ValueError,
requests.exceptions.ConnectionError,
requests.exceptions.ChunkedEncodingError) as err:
fail_count += 1
reset_event.clear()
_LOGGING.warning('%s Connection Failed (count=%d). Waiting %ss. Err: %s',
self.name, fail_count, (fail_count * 5) + 5, err)
parse_string = ""
self.watchdog.stop()
self.hik_request.close()
time.sleep(5)
self.update_stale()
time.sleep(fail_count * 5)
continue | [
"Open event stream."
] |
Please provide a description of the function:def process_stream(self, tree):
try:
etype = SENSOR_MAP[tree.find(
self.element_query('eventType')).text.lower()]
estate = tree.find(
self.element_query('eventState')).text
echid = tree.find(
self.element_query('channelID'))
if echid is None:
# Some devices use a different key
echid = tree.find(
self.element_query('dynChannelID'))
echid = int(echid.text)
ecount = tree.find(
self.element_query('activePostCount')).text
except (AttributeError, KeyError, IndexError) as err:
_LOGGING.error('Problem finding attribute: %s', err)
return
# Take care of keep-alive
if len(etype) > 0 and etype == 'Video Loss':
self.watchdog.pet()
# Track state if it's in the event list.
if len(etype) > 0:
state = self.fetch_attributes(etype, echid)
if state:
# Determine if state has changed
# If so, publish, otherwise do nothing
estate = (estate == 'active')
old_state = state[0]
attr = [estate, echid, int(ecount),
datetime.datetime.now()]
self.update_attributes(etype, echid, attr)
if estate != old_state:
self.publish_changes(etype, echid)
self.watchdog.pet() | [
"Process incoming event stream packets."
] |
Please provide a description of the function:def update_stale(self):
# Some events don't post an inactive XML, only active.
# If we don't get an active update for 5 seconds we can
# assume the event is no longer active and update accordingly.
for etype, echannels in self.event_states.items():
for eprop in echannels:
if eprop[3] is not None:
sec_elap = ((datetime.datetime.now()-eprop[3])
.total_seconds())
# print('Seconds since last update: {}'.format(sec_elap))
if sec_elap > 5 and eprop[0] is True:
_LOGGING.debug('Updating stale event %s on CH(%s)',
etype, eprop[1])
attr = [False, eprop[1], eprop[2],
datetime.datetime.now()]
self.update_attributes(etype, eprop[1], attr)
self.publish_changes(etype, eprop[1]) | [
"Update stale active statuses"
] |
Please provide a description of the function:def publish_changes(self, etype, echid):
_LOGGING.debug('%s Update: %s, %s',
self.name, etype, self.fetch_attributes(etype, echid))
signal = 'ValueChanged.{}'.format(self.cam_id)
sender = '{}.{}'.format(etype, echid)
if dispatcher:
dispatcher.send(signal=signal, sender=sender)
self._do_update_callback('{}.{}.{}'.format(self.cam_id, etype, echid)) | [
"Post updates for specified event type."
] |
Please provide a description of the function:def fetch_attributes(self, event, channel):
try:
for sensor in self.event_states[event]:
if sensor[1] == int(channel):
return sensor
except KeyError:
return None | [
"Returns attribute list for a given event/channel."
] |
Please provide a description of the function:def update_attributes(self, event, channel, attr):
try:
for i, sensor in enumerate(self.event_states[event]):
if sensor[1] == int(channel):
self.event_states[event][i] = attr
except KeyError:
_LOGGING.debug('Error updating attributes for: (%s, %s)',
event, channel) | [
"Update attribute list for current event/channel."
] |
Please provide a description of the function:def start(self):
self._timer = Timer(self.time, self.handler)
self._timer.daemon = True
self._timer.start()
return | [
" Starts the watchdog timer. "
] |
Please provide a description of the function:def main():
cam = HikCamObject('http://XXX.XXX.XXX.XXX', 80, 'user', 'password')
entities = []
for sensor, channel_list in cam.sensors.items():
for channel in channel_list:
entities.append(HikSensor(sensor, channel[1], cam)) | [
"Main function"
] |
Please provide a description of the function:def flip_motion(self, value):
if value:
self.cam.enable_motion_detection()
else:
self.cam.disable_motion_detection() | [
"Toggle motion detection"
] |
Please provide a description of the function:def update_callback(self, msg):
print('Callback: {}'.format(msg))
print('{}:{} @ {}'.format(self.name, self._sensor_state(), self._sensor_last_update())) | [
" get updates. "
] |
Please provide a description of the function:def render(self, renderer=None, **kwargs):
return Markup(get_renderer(current_app, renderer)(**kwargs).visit(
self)) | [
"Render the navigational item using a renderer.\n\n :param renderer: An object implementing the :class:`~.Renderer`\n interface.\n :return: A markupsafe string with the rendered result.\n "
] |
Please provide a description of the function:def visit_object(self, node):
if current_app.debug:
return tags.comment('no implementation in {} to render {}'.format(
self.__class__.__name__,
node.__class__.__name__, ))
return '' | [
"Fallback rendering for objects.\n\n If the current application is in debug-mode\n (``flask.current_app.debug`` is ``True``), an ``<!-- HTML comment\n -->`` will be rendered, indicating which class is missing a visitation\n function.\n\n Outside of debug-mode, returns an empty string.\n "
] |
Please provide a description of the function:def register_renderer(app, id, renderer, force=True):
renderers = app.extensions.setdefault('nav_renderers', {})
if force:
renderers[id] = renderer
else:
renderers.setdefault(id, renderer) | [
"Registers a renderer on the application.\n\n :param app: The :class:`~flask.Flask` application to register the renderer\n on\n :param id: Internal id-string for the renderer\n :param renderer: Renderer to register\n :param force: Whether or not to overwrite the renderer if a different one\n is already registered for ``id``\n "
] |
Please provide a description of the function:def get_renderer(app, id):
renderer = app.extensions.get('nav_renderers', {})[id]
if isinstance(renderer, tuple):
mod_name, cls_name = renderer
mod = import_module(mod_name)
cls = mod
for name in cls_name.split('.'):
cls = getattr(cls, name)
return cls
return renderer | [
"Retrieve a renderer.\n\n :param app: :class:`~flask.Flask` application to look ``id`` up on\n :param id: Internal renderer id-string to look up\n "
] |
Please provide a description of the function:def init_app(self, app):
if not hasattr(app, 'extensions'):
app.extensions = {}
app.extensions['nav'] = self
app.add_template_global(self.elems, 'nav')
# register some renderers
for args in self._renderers:
register_renderer(app, *args) | [
"Initialize an application.\n\n :param app: A :class:`~flask.Flask` app.\n "
] |
Please provide a description of the function:def navigation(self, id=None):
def wrapper(f):
self.register_element(id or f.__name__, f)
return f
return wrapper | [
"Function decorator for navbar registration.\n\n Convenience function, calls :meth:`.register_element` with ``id`` and\n the decorated function as ``elem``.\n\n :param id: ID to pass on. If ``None``, uses the decorated functions\n name.\n "
] |
Please provide a description of the function:def renderer(self, id=None, force=True):
def _(cls):
name = cls.__name__
sn = name[0] + re.sub(r'([A-Z])', r'_\1', name[1:])
self._renderers.append((id or sn.lower(), cls, force))
return cls
return _ | [
"Class decorator for Renderers.\n\n The decorated class will be added to the list of renderers kept by this\n instance that will be registered on the app upon app initialization.\n\n :param id: Id for the renderer, defaults to the class name in snake\n case.\n :param force: Whether or not to overwrite existing renderers.\n "
] |
Please provide a description of the function:def parse_time(time):
if isinstance(time, datetime.datetime):
return time
return datetime.datetime.strptime(time, DATETIME_FORMAT_OPENVPN) | [
"Parses date and time from input string in OpenVPN logging format."
] |
Please provide a description of the function:def decrypt(self, key, dev_addr):
sequence_counter = int(self.FCntUp)
return loramac_decrypt(self.payload_hex, sequence_counter, key, dev_addr) | [
"\n Decrypt the actual payload in this LoraPayload.\n\n key: 16-byte hex-encoded AES key. (i.e. AABBCCDDEEFFAABBCCDDEEFFAABBCCDD)\n dev_addr: 4-byte hex-encoded DevAddr (i.e. AABBCCDD)\n "
] |
Please provide a description of the function:def Lrr_location(self):
return WKT_POINT_FMT.format(lng=float(self.LrrLON), lat=float(self.LrrLAT)) | [
"\n Return the location of the LRR (Wireless base station/Gateway)\n "
] |
Please provide a description of the function:def to_bytes(s):
if sys.version_info < (3,):
return "".join(map(chr, s))
else:
return bytes(s) | [
"\n PY2/PY3 compatible way to convert to something cryptography understands\n "
] |
Please provide a description of the function:def loramac_decrypt(payload_hex, sequence_counter, key, dev_addr, direction=UP_LINK):
key = unhexlify(key)
dev_addr = unhexlify(dev_addr)
buffer = bytearray(unhexlify(payload_hex))
size = len(buffer)
bufferIndex = 0
# block counter
ctr = 1
# output buffer, initialize to input buffer size.
encBuffer = [0x00] * size
cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=default_backend())
def aes_encrypt_block(aBlock):
encryptor = cipher.encryptor()
return bytearray(encryptor.update(to_bytes(aBlock)) + encryptor.finalize())
# For the exact definition of this block refer to
# 'chapter 4.3.3.1 Encryption in LoRaWAN' in the LoRaWAN specification
aBlock = bytearray(
[
0x01, # 0 always 0x01
0x00, # 1 always 0x00
0x00, # 2 always 0x00
0x00, # 3 always 0x00
0x00, # 4 always 0x00
direction, # 5 dir, 0 for uplink, 1 for downlink
dev_addr[3], # 6 devaddr, lsb
dev_addr[2], # 7 devaddr
dev_addr[1], # 8 devaddr
dev_addr[0], # 9 devaddr, msb
sequence_counter & 0xFF, # 10 sequence counter (FCntUp) lsb
(sequence_counter >> 8) & 0xFF, # 11 sequence counter
(sequence_counter >> 16) & 0xFF, # 12 sequence counter
(sequence_counter >> 24) & 0xFF, # 13 sequence counter (FCntUp) msb
0x00, # 14 always 0x01
0x00, # 15 block counter
]
)
# complete blocks
while size >= 16:
aBlock[15] = ctr & 0xFF
ctr += 1
sBlock = aes_encrypt_block(aBlock)
for i in range(16):
encBuffer[bufferIndex + i] = buffer[bufferIndex + i] ^ sBlock[i]
size -= 16
bufferIndex += 16
# partial blocks
if size > 0:
aBlock[15] = ctr & 0xFF
sBlock = aes_encrypt_block(aBlock)
for i in range(size):
encBuffer[bufferIndex + i] = buffer[bufferIndex + i] ^ sBlock[i]
return encBuffer | [
"\n LoraMac decrypt\n\n Which is actually encrypting a predefined 16-byte block (ref LoraWAN\n specification 4.3.3.1) and XORing that with each block of data.\n\n payload_hex: hex-encoded payload (FRMPayload)\n sequence_counter: integer, sequence counter (FCntUp)\n key: 16-byte hex-encoded AES key. (i.e. AABBCCDDEEFFAABBCCDDEEFFAABBCCDD)\n dev_addr: 4-byte hex-encoded DevAddr (i.e. AABBCCDD)\n direction: 0 for uplink packets, 1 for downlink packets\n\n returns an array of byte values.\n\n This method is based on `void LoRaMacPayloadEncrypt()` in\n https://github.com/Lora-net/LoRaMac-node/blob/master/src/mac/LoRaMacCrypto.c#L108\n ",
"\n AES encrypt a block.\n aes.encrypt expects a string, so we convert the input to string and\n the return value to bytes again.\n "
] |
Please provide a description of the function:def parse(self):
status = Status()
self.expect_line(Status.client_list.label)
status.updated_at = self.expect_tuple(Status.updated_at.label)
status.client_list.update({
text_type(c.real_address): c
for c in self._parse_fields(Client, Status.routing_table.label)})
status.routing_table.update({
text_type(r.virtual_address): r
for r in self._parse_fields(Routing, Status.global_stats.label)})
status.global_stats = GlobalStats()
status.global_stats.max_bcast_mcast_queue_len = self.expect_tuple(
GlobalStats.max_bcast_mcast_queue_len.label)
self.expect_line(self.terminator)
return status | [
"Parses the status log.\n\n :raises ParsingError: if syntax error found in the log.\n :return: The :class:`.models.Status` with filled data.\n "
] |
Please provide a description of the function:def parse_status(status_log, encoding='utf-8'):
if isinstance(status_log, bytes):
status_log = status_log.decode(encoding)
parser = LogParser.fromstring(status_log)
return parser.parse() | [
"Parses the status log of OpenVPN.\n\n :param status_log: The content of status log.\n :type status_log: :class:`str`\n :param encoding: Optional. The encoding of status log.\n :type encoding: :class:`str`\n :return: The instance of :class:`.models.Status`\n "
] |
Please provide a description of the function:def version(self):
res = self.client.service.Version()
return '.'.join([ustr(x) for x in res[0]]) | [
"Return version of the TR DWE."
] |
Please provide a description of the function:def system_info(self):
res = self.client.service.SystemInfo()
res = {ustr(x[0]): x[1] for x in res[0]}
to_str = lambda arr: '.'.join([ustr(x) for x in arr[0]])
res['OSVersion'] = to_str(res['OSVersion'])
res['RuntimeVersion'] = to_str(res['RuntimeVersion'])
res['Version'] = to_str(res['Version'])
res['Name'] = ustr(res['Name'])
res['Server'] = ustr(res['Server'])
res['LocalNameCheck'] = ustr(res['LocalNameCheck'])
res['UserHostAddress'] = ustr(res['UserHostAddress'])
return res | [
"Return system information."
] |
Please provide a description of the function:def sources(self):
res = self.client.service.Sources(self.userdata, 0)
return [ustr(x[0]) for x in res[0]] | [
"Return available sources of data."
] |
Please provide a description of the function:def request(self, query, source='Datastream',
fields=None, options=None, symbol_set=None, tag=None):
if self.show_request:
try:
print('Request:' + query)
except UnicodeEncodeError:
print('Request:' + query.encode('utf-8'))
rd = self.client.factory.create('RequestData')
rd.Source = source
rd.Instrument = query
if fields is not None:
rd.Fields = self.client.factory.create('ArrayOfString')
rd.Fields.string = fields
rd.SymbolSet = symbol_set
rd.Options = options
rd.Tag = tag
self.last_response = self.client.service.RequestRecord(self.userdata, rd, 0)
return self.last_response | [
"General function to retrieve one record in raw format.\n\n query - query string for DWE system. This may be a simple instrument name\n or more complicated request. Refer to the documentation for the\n format.\n source - The name of datasource (default: \"Datastream\")\n fields - Fields to be retrieved (used when the requester does not want all\n fields to be delivered).\n options - Options for specific data source. Many of datasources do not require\n opptions string. Refer to the documentation of the specific\n datasource for allowed syntax.\n symbol_set - The symbol set used inside the instrument (used for mapping\n identifiers within the request. Refer to the documentation for\n the details.\n tag - User-defined cookie that can be used to match up requests and response.\n It will be returned back in the response. The string should not be\n longer than 256 characters.\n "
] |
Please provide a description of the function:def request_many(self, queries, source='Datastream',
fields=None, options=None, symbol_set=None, tag=None):
if self.show_request:
print(('Requests:', queries))
if not isinstance(queries, list):
queries = [queries]
req = self.client.factory.create('ArrayOfRequestData')
req.RequestData = []
for q in queries:
rd = self.client.factory.create('RequestData')
rd.Source = source
rd.Instrument = q
if fields is not None:
rd.Fields = self.client.factory.create('ArrayOfString')
rd.Fields.string = fields
rd.SymbolSet = symbol_set
rd.Options = options
rd.Tag = tag
req.RequestData.append(rd)
return self.client.service.RequestRecords(self.userdata, req, 0)[0] | [
"General function to retrieve one record in raw format.\n\n query - list of query strings for DWE system.\n source - The name of datasource (default: \"Datastream\")\n fields - Fields to be retrieved (used when the requester does not want all\n fields to be delivered).\n options - Options for specific data source. Many of datasources do not require\n opptions string. Refer to the documentation of the specific\n datasource for allowed syntax.\n symbol_set - The symbol set used inside the instrument (used for mapping\n identifiers within the request. Refer to the documentation for\n the details.\n tag - User-defined cookie that can be used to match up requests and response.\n It will be returned back in the response. The string should not be\n longer than 256 characters.\n NB! source, options, symbol_set and tag are assumed to be identical for all\n requests in the list\n "
] |
Please provide a description of the function:def status(self, record=None):
if record is not None:
self.last_status = {'Source': ustr(record['Source']),
'StatusType': ustr(record['StatusType']),
'StatusCode': record['StatusCode'],
'StatusMessage': ustr(record['StatusMessage']),
'Request': ustr(record['Instrument'])}
return self.last_status | [
"Extract status from the retrieved data and save it as a property of an object.\n If record with data is not specified then the status of previous operation is\n returned.\n\n status - dictionary with data source, string with request and status type,\n code and message.\n\n status['StatusType']: 'Connected' - the data is fine\n 'Stale' - the source is unavailable. It may be\n worthwhile to try again later\n 'Failure' - data could not be obtained (e.g. the\n instrument is incorrect)\n 'Pending' - for internal use only\n status['StatusCode']: 0 - 'No Error'\n 1 - 'Disconnected'\n 2 - 'Source Fault'\n 3 - 'Network Fault'\n 4 - 'Access Denied' (user does not have permissions)\n 5 - 'No Such Item' (no instrument with given name)\n 11 - 'Blocking Timeout'\n 12 - 'Internal'\n "
] |
Please provide a description of the function:def parse_record(self, raw, indx=0):
suffix = '' if indx == 0 else '_%i' % (indx + 1)
# Parsing status
status = self.status(raw)
# Testing if no errors
if status['StatusType'] != 'Connected':
if self.raise_on_error:
raise DatastreamException('%s (error %i): %s --> "%s"' %
(status['StatusType'], status['StatusCode'],
status['StatusMessage'], status['Request']))
else:
self._test_status_and_warn()
return pd.DataFrame(), {}
record = self.extract_data(raw)
get_field = lambda fldname: record[fldname + suffix]
try:
error = get_field('INSTERROR')
if self.raise_on_error:
raise DatastreamException('Error: %s --> "%s"' %
(error, status['Request']))
else:
self.last_status['StatusMessage'] = error
self.last_status['StatusType'] = 'INSTERROR'
self._test_status_and_warn()
metadata = {'Frequency': '', 'Currency': '', 'DisplayName': '',
'Symbol': '', 'Status': error}
except KeyError:
# Parsing metadata of the symbol
# NB! currency might be returned as symbol thus "unicode" should be used
metadata = {'Frequency': ustr(get_field('FREQUENCY')),
'Currency': ustr(get_field('CCY')),
'DisplayName': ustr(get_field('DISPNAME')),
'Symbol': ustr(get_field('SYMBOL')),
'Status': 'OK'}
# Fields with data
if suffix == '':
fields = [ustr(x) for x in record if '_' not in x]
else:
fields = [ustr(x) for x in record if suffix in x]
# Filter metadata
meta_fields = ['CCY', 'DISPNAME', 'FREQUENCY', 'SYMBOL', 'DATE', 'INSTERROR']
fields = [x.replace(suffix, '') for x in fields
if not any([y in x for y in meta_fields])]
if 'DATE' + suffix in record:
date = record['DATE' + suffix]
elif 'DATE' in record:
date = record['DATE']
else:
date = None
if len(fields) > 0 and date is not None:
# Check if we have a single value or a series
if isinstance(date, dt.datetime):
data = pd.DataFrame({x: [get_field(x)] for x in fields},
index=[date])
else:
data = pd.DataFrame({x: get_field(x)[0] for x in fields},
index=date[0])
else:
data = pd.DataFrame()
metadata = pd.DataFrame(metadata, index=[indx])
metadata = metadata[['Symbol', 'DisplayName', 'Currency', 'Frequency', 'Status']]
return data, metadata | [
"Parse raw data (that is retrieved by \"request\") and return pandas.DataFrame.\n Returns tuple (data, metadata)\n\n data - pandas.DataFrame with retrieved data.\n metadata - pandas.DataFrame with info about symbol, currency, frequency,\n displayname and status of given request\n "
] |
Please provide a description of the function:def parse_record_static(self, raw):
# Parsing status
status = self.status(raw)
# Testing if no errors
if status['StatusType'] != 'Connected':
if self.raise_on_error:
raise DatastreamException('%s (error %i): %s --> "%s"' %
(status['StatusType'], status['StatusCode'],
status['StatusMessage'], status['Request']))
else:
self._test_status_and_warn()
return pd.DataFrame(), {}
# Convert record to dict
record = self.extract_data(raw)
try:
error = record['INSTERROR']
if self.raise_on_error:
raise DatastreamException('Error: %s --> "%s"' %
(error, status['Request']))
else:
self.last_status['StatusMessage'] = error
self.last_status['StatusType'] = 'INSTERROR'
self._test_status_and_warn()
return pd.DataFrame(), {'Status': error, 'Date': None}
except KeyError:
metadata = {'Status': 'OK', 'Date': ''}
# All fields that are available
fields = [x for x in record if '_' not in x]
metadata['Date'] = record['DATE']
fields.remove('DATE')
# Number of elements
num = len([x[0] for x in record if 'SYMBOL' in x])
# field naming 'CCY', 'CCY_2', 'CCY_3', ...
fld_name = lambda field, indx: field if indx == 0 else field + '_%i' % (indx + 1)
# Construct pd.DataFrame
res = pd.DataFrame({fld: [record[fld_name(fld, ind)]
if fld_name(fld, ind) in record else ''
for ind in range(num)]
for fld in fields})
return res, metadata | [
"Parse raw data (that is retrieved by static request) and return pandas.DataFrame.\n Returns tuple (data, metadata)\n\n data - pandas.DataFrame with retrieved data.\n metadata - pandas.DataFrame with info about symbol, currency, frequency,\n displayname and status of given request\n "
] |
Please provide a description of the function:def construct_request(ticker, fields=None, date=None,
date_from=None, date_to=None, freq=None):
if isinstance(ticker, basestring):
request = ticker
elif hasattr(ticker, '__len__'):
request = ','.join(ticker)
else:
raise ValueError('ticker should be either string or list/array of strings')
if fields is not None:
if isinstance(fields, basestring):
request += '~=' + fields
elif isinstance(fields, list) and len(fields) > 0:
request += '~=' + ','.join(fields)
if date is not None:
request += '~@' + pd.to_datetime(date).strftime('%Y-%m-%d')
else:
if date_from is not None:
request += '~' + pd.to_datetime(date_from).strftime('%Y-%m-%d')
if date_to is not None:
request += '~:' + pd.to_datetime(date_to).strftime('%Y-%m-%d')
if freq is not None:
request += '~' + freq
return request | [
"Construct a request string for querying TR DWE.\n\n tickers - ticker or symbol\n fields - list of fields.\n date - date for a single-date query\n date_from, date_to - date range (used only if \"date\" is not specified)\n freq - frequency of data: daily('D'), weekly('W') or monthly('M')\n Use here 'REP' for static requests\n\n Some of available fields:\n P - adjusted closing price\n PO - opening price\n PH - high price\n PL - low price\n VO - volume, which is expressed in 1000's of shares.\n UP - unadjusted price\n OI - open interest\n\n MV - market value\n EPS - earnings per share\n DI - dividend index\n MTVB - market to book value\n PTVB - price to book value\n ...\n\n The full list of data fields is available at http://dtg.tfn.com/.\n "
] |
Please provide a description of the function:def fetch(self, tickers, fields=None, date=None, date_from=None, date_to=None,
freq='D', only_data=True, static=False):
if static:
query = self.construct_request(tickers, fields, date, freq='REP')
else:
query = self.construct_request(tickers, fields, date, date_from, date_to, freq)
raw = self.request(query)
if static:
data, metadata = self.parse_record_static(raw)
elif isinstance(tickers, basestring) or len(tickers) == 1:
data, metadata = self.parse_record(raw)
elif hasattr(tickers, '__len__'):
metadata = pd.DataFrame()
data = {}
for indx in range(len(tickers)):
dat, meta = self.parse_record(raw, indx)
data[tickers[indx]] = dat
metadata = metadata.append(meta, ignore_index=False)
data = pd.concat(data)
else:
raise DatastreamException(('First argument should be either ticker or '
'list of tickers'))
if only_data:
return data
else:
return data, metadata | [
"Fetch data from TR DWE.\n\n tickers - ticker or list of tickers\n fields - list of fields.\n date - date for a single-date query\n date_from, date_to - date range (used only if \"date\" is not specified)\n freq - frequency of data: daily('D'), weekly('W') or monthly('M')\n only_data - if True then metadata will not be returned\n static - if True \"static\" request is created (i.e. not a series).\n In this case 'date_from', 'date_to' and 'freq' are ignored\n\n In case list of tickers is requested, a MultiIndex-dataframe is returned.\n\n Some of available fields:\n P - adjusted closing price\n PO - opening price\n PH - high price\n PL - low price\n VO - volume, which is expressed in 1000's of shares.\n UP - unadjusted price\n OI - open interest\n\n MV - market value\n EPS - earnings per share\n DI - dividend index\n MTVB - market to book value\n PTVB - price to book value\n ...\n\n The full list of data fields is available at http://dtg.tfn.com/.\n "
] |
Please provide a description of the function:def get_OHLCV(self, ticker, date=None, date_from=None, date_to=None):
data, meta = self.fetch(ticker + "~OHLCV", None, date,
date_from, date_to, 'D', only_data=False)
return data | [
"Get Open, High, Low, Close prices and daily Volume for a given ticker.\n\n ticker - ticker or symbol\n date - date for a single-date query\n date_from, date_to - date range (used only if \"date\" is not specified)\n\n Returns pandas.Dataframe with data. If error occurs, then it is printed as\n a warning.\n "
] |
Please provide a description of the function:def get_constituents(self, index_ticker, date=None, only_list=False):
if date is not None:
str_date = pd.to_datetime(date).strftime('%m%y')
else:
str_date = ''
# Note: ~XREF is equal to the following large request
# ~REP~=DSCD,EXMNEM,GEOG,GEOGC,IBTKR,INDC,INDG,INDM,INDX,INDXEG,INDXFS,INDXL,
# INDXS,ISIN,ISINID,LOC,MNEM,NAME,SECD,TYPE
fields = '~REP~=NAME' if only_list else '~XREF'
query = 'L' + index_ticker + str_date + fields
raw = self.request(query)
res, metadata = self.parse_record_static(raw)
return res | [
" Get a list of all constituents of a given index.\n\n index_ticker - Datastream ticker for index\n date - date for which list should be retrieved (if None then\n list of present constituents is retrieved)\n only_list - request only list of symbols. By default the method\n retrieves many extra fields with information (various\n mnemonics and codes). This might pose some problems\n for large indices like Russel-3000. If only_list=True,\n then only the list of symbols and names are retrieved.\n "
] |
Please provide a description of the function:def get_epit_vintage_matrix(self, mnemonic, date_from='1951-01-01', date_to=None):
# Get first available date from the REL1 series
rel1 = self.fetch(mnemonic, 'REL1', date_from=date_from, date_to=date_to)
date_0 = rel1.dropna().index[0]
# All release dates
reld123 = self.fetch(mnemonic, ['RELD1', 'RELD2', 'RELD3'],
date_from=date_0, date_to=date_to).dropna(how='all')
# Fetch all vintages
res = {}
for date in reld123.index:
try:
_tmp = self.fetch(mnemonic, 'RELV', date_from=date_0, date_to=date).dropna()
except DatastreamException:
continue
res[date] = _tmp
return pd.concat(res).RELV.unstack() | [
" Construct the vintage matrix for a given economic series.\n Requires subscription to Thomson Reuters Economic Point-in-Time (EPiT).\n\n Vintage matrix represents a DataFrame where columns correspond to a\n particular period (quarter or month) for the reported statistic and\n index represents timestamps at which these values were released by\n the respective official agency. I.e. every line corresponds to all\n available reported values by the given date.\n\n For example:\n\n >> DWE.get_epit_vintage_matrix('USGDP...D', date_from='2015-01-01')\n\n 2015-02-15 2015-05-15 2015-08-15 2015-11-15 \\\n 2015-04-29 16304.80 NaN NaN NaN\n 2015-05-29 16264.10 NaN NaN NaN\n 2015-06-24 16287.70 NaN NaN NaN\n 2015-07-30 16177.30 16270.400 NaN NaN\n 2015-08-27 16177.30 16324.300 NaN NaN\n 2015-09-25 16177.30 16333.600 NaN NaN\n 2015-10-29 16177.30 16333.600 16394.200 NaN\n 2015-11-24 16177.30 16333.600 16417.800 NaN\n\n From the matrix it is seen for example, that the advance GDP estimate\n for 2015-Q1 (corresponding to 2015-02-15) was released on 2015-04-29\n and was equal to 16304.80 (B USD). The first revision (16264.10) has\n happened on 2015-05-29 and the second (16287.70) - on 2015-06-24.\n On 2015-07-30 the advance GDP figure for 2015-Q2 was released\n (16270.400) together with update on the 2015-Q1 value (16177.30)\n and so on.\n "
] |
Please provide a description of the function:def get_epit_revisions(self, mnemonic, period, relh50=False):
if relh50:
data = self.fetch(mnemonic, 'RELH50', date=period, static=True)
else:
data = self.fetch(mnemonic, 'RELH', date=period, static=True)
data = data.iloc[0]
# Parse the response
res = {data.loc['RELHD%02d' % i]: data.loc['RELHV%02d' % i]
for i in range(1, 51 if relh50 else 21)
if data.loc['RELHD%02d' % i] != ''}
res = pd.Series(res, name=data.loc['RELHP ']).sort_index()
return res | [
" Return initial estimate and first revisions of a given economic time\n series and a given period.\n Requires subscription to Thomson Reuters Economic Point-in-Time (EPiT).\n\n \"Period\" parameter should represent a date which falls within a time\n period of interest, e.g. 2016 Q4 could be requested with the\n period='2016-11-15' for example.\n\n By default up to 20 values is returned unless argument \"relh50\" is\n set to True (in which case up to 50 values is returned).\n "
] |
Please provide a description of the function:def check_validation_level(validation_level):
if validation_level not in (VALIDATION_LEVEL.QUIET, VALIDATION_LEVEL.STRICT, VALIDATION_LEVEL.TOLERANT):
raise UnknownValidationLevel | [
"\n Validate the given validation level\n\n :type validation_level: ``int``\n :param validation_level: validation level (see :class:`hl7apy.consts.VALIDATION_LEVEL`)\n :raises: :exc:`hl7apy.exceptions.UnknownValidationLevel` if the given validation level is unsupported\n "
] |
Please provide a description of the function:def load_library(version):
check_version(version)
module_name = SUPPORTED_LIBRARIES[version]
lib = sys.modules.get(module_name)
if lib is None:
lib = importlib.import_module(module_name)
return lib | [
"\n Load the correct module according to the version\n\n :type version: ``str``\n :param version: the version of the library to be loaded (e.g. '2.6')\n :rtype: module object\n "
] |
Please provide a description of the function:def load_reference(name, element_type, version):
lib = load_library(version)
ref = lib.get(name, element_type)
return ref | [
"\n Look for an element of the given type, name and version and return its reference structure\n\n :type element_type: ``str``\n :param element_type: the element type to look for (e.g. 'Segment')\n :type name: ``str``\n :param name: the element name to look for (e.g. 'MSH')\n :type version: ``str``\n :param version: the version of the library where to search the element (e.g. '2.6')\n :rtype: ``dict``\n :return: a dictionary describing the element structure\n :raise: ``KeyError`` if the element has not been found\n\n The returned dictionary will contain the following keys:\n\n +--------------+--------------------------------------------+\n |Key |Value |\n +==============+============================================+\n |cls |an :class:`hl7apy.core.Element` subclass |\n +--------------+--------------------------------------------+\n |name |the Element name (e.g. PID) |\n +--------------+--------------------------------------------+\n |ref |a tuple of one of the following format: |\n | | |\n | |('leaf', <datatype>, <longName>, <table>) |\n | |('sequence', (<child>, (<min>, <max>), ...))|\n +--------------+--------------------------------------------+\n\n >>> load_reference('UNKNOWN', 'Segment', '2.5') # doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n ...\n ChildNotFound: No child named UNKNOWN\n >>> r = load_reference('ADT_A01', 'Message', '2.5')\n >>> print(r[0])\n sequence\n >>> r = load_reference('MSH_3', 'Field', '2.5')\n >>> print(r[0])\n sequence\n "
] |
Please provide a description of the function:def find_reference(name, element_types, version):
lib = load_library(version)
ref = lib.find(name, element_types)
return ref | [
"\n Look for an element of the given name and version into the given types and return its reference structure\n\n :type name: ``str``\n :param name: the element name to look for (e.g. 'MSH')\n :type types: ``list`` or ``tuple``\n :param types: the element classes where to look for the element (e.g. (Group, Segment))\n :type version: ``str``\n :param version: the version of the library where to search the element (e.g. '2.6')\n :rtype: ``dict``\n :return: a dictionary describing the element structure\n :raise: :class:`hl7apy.exceptions.ChildNotFound` if the element has not been found\n\n >>> from hl7apy.core import Message, Segment\n >>> find_reference('UNKNOWN', (Segment, ), '2.5') # doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n ...\n ChildNotFound: No child named UNKNOWN\n >>> find_reference('ADT_A01', (Segment,), '2.5') # doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n ...\n ChildNotFound: No child named ADT_A01\n >>> r = find_reference('ADT_A01', (Message,), '2.5')\n >>> print('%s %s' % (r['name'], r['cls']))\n ADT_A01 <class 'hl7apy.core.Message'>\n "
] |
Please provide a description of the function:def find(name, where):
for cls in where:
try:
return {'ref': get(name, cls.__name__), 'name': name, 'cls': cls}
except ChildNotFound:
pass
raise ChildNotFound(name) | [
"\n >>> from hl7apy.core import Segment\n >>> from hl7apy import find_reference\n >>> find_reference('UNKNOWN', (Segment, ), '2.3.1') # doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n ...\n ChildNotFound: No child named UNKNOWN\n "
] |
Please provide a description of the function:def get_date_info(value):
fmt = _get_date_format(value)
dt_value = _datetime_obj_factory(value, fmt)
return dt_value, fmt | [
"\n Returns the datetime object and the format of the date in input\n\n :type value: `str`\n "
] |
Please provide a description of the function:def get_timestamp_info(value):
value, offset = _split_offset(value)
fmt, microsec = _get_timestamp_format(value)
dt_value = _datetime_obj_factory(value, fmt)
return dt_value, fmt, offset, microsec | [
"\n Returns the datetime object, the format, the offset and the microsecond of the timestamp in input\n\n :type value: `str`\n "
] |
Please provide a description of the function:def get_datetime_info(value):
date_value, offset = _split_offset(value)
date_format = _get_date_format(date_value[:8])
try:
timestamp_form, microsec = _get_timestamp_format(date_value[8:])
except ValueError:
if not date_value[8:]: # if it's empty
timestamp_form, microsec = '', 4
else:
raise ValueError('{0} is not an HL7 valid date value'.format(value))
fmt = '{0}{1}'.format(date_format, timestamp_form)
dt_value = _datetime_obj_factory(date_value, fmt)
return dt_value, fmt, offset, microsec | [
"\n Returns the datetime object, the format, the offset and the microsecond of the datetime in input\n\n :type value: `str`\n "
] |
Please provide a description of the function:def is_base_datatype(datatype, version=None):
if version is None:
version = get_default_version()
lib = load_library(version)
return lib.is_base_datatype(datatype) | [
"\n Check if the given datatype is a base datatype of the specified version\n\n :type datatype: ``str``\n :param datatype: the datatype (e.g. ST)\n\n :type version: ``str``\n :param version: the HL7 version (e.g. 2.5)\n\n :return: ``True`` if it is a base datatype, ``False`` otherwise\n\n >>> is_base_datatype('ST')\n True\n >>> is_base_datatype('CE')\n False\n "
] |
Please provide a description of the function:def get_ordered_children(self):
ordered_keys = self.element.ordered_children if self.element.ordered_children is not None else []
children = [self.indexes.get(k, None) for k in ordered_keys]
return children | [
"\n Return the list of children ordered according to the element structure\n\n :return: a list of :class:`Element <hl7apy.core.Element>`\n "
] |
Please provide a description of the function:def insert(self, index, child, by_name_index=-1):
if self._can_add_child(child):
try:
if by_name_index == -1:
self.indexes[child.name].append(child)
else:
self.indexes[child.name].insert(by_name_index, child)
except KeyError:
self.indexes[child.name] = [child]
self.list.insert(index, child) | [
"\n Add the child at the given index\n\n :type index: ``int``\n :param index: child position\n\n :type child: :class:`Element <hl7apy.core.Element>`\n :param child: an instance of an :class:`Element <hl7apy.core.Element>` subclass\n "
] |
Please provide a description of the function:def append(self, child):
if self._can_add_child(child):
if self.element == child.parent:
self._remove_from_traversal_index(child)
self.list.append(child)
try:
self.indexes[child.name].append(child)
except KeyError:
self.indexes[child.name] = [child]
elif self.element == child.traversal_parent:
try:
self.traversal_indexes[child.name].append(child)
except KeyError:
self.traversal_indexes[child.name] = [child] | [
"\n Append the given child\n\n :class:`Element <hl7apy.core.Element>`\n :param child: an instance of an :class:`Element <hl7apy.core.Element>` subclass\n "
] |
Please provide a description of the function:def set(self, name, value, index=-1):
# just copy the first element of the ElementProxy (e.g. message.pid = message2.pid)
if isinstance(value, ElementProxy):
value = value[0].to_er7()
name = name.upper()
reference = None if name is None else self.element.find_child_reference(name)
child_ref, child_name = (None, None) if reference is None else (reference['ref'], reference['name'])
if isinstance(value, basestring): # if the value is a basestring, parse it
child = self.element.parse_child(value, child_name=child_name, reference=child_ref)
elif isinstance(value, Element): # it is already an instance of Element
child = value
elif isinstance(value, BaseDataType):
child = self.create_element(name, False, reference)
child.value = value
else:
raise ChildNotValid(value, child_name)
if child.name != child_name: # e.g. message.pid = Segment('SPM') is forbidden
raise ChildNotValid(value, child_name)
child_to_remove = self.child_at_index(child_name, index)
if child_to_remove is None:
self.append(child)
else:
self.replace_child(child_to_remove, child)
# a set has been called, change the temporary parent to be the actual one
self.element.set_parent_to_traversal() | [
"\n Assign the ``value`` to the child having the given ``name`` at the ``index`` position\n\n :type name: ``str``\n :param name: the child name (e.g. PID)\n\n :type value: an instance of :class:`Element <hl7apy.core.Element>`, a `str` or an instance of\n :class:`ElementProxy <hl7apy.core.ElementProxy>`\n :param value: the child value\n\n :type index: ``int``\n :param index: the child position (e.g. 1)\n "
] |
Please provide a description of the function:def remove(self, child):
try:
if self.element == child.traversal_parent:
self._remove_from_traversal_index(child)
else:
self._remove_from_index(child)
self.list.remove(child)
except:
raise | [
"\n Remove the given child from both child list and child indexes\n\n :type child: :class:`Element <hl7apy.core.Element>`\n :param child: an instance of :class:`Element <hl7apy.core.Element>` subclass\n "
] |
Please provide a description of the function:def remove_by_name(self, name, index=0):
child = self.child_at_index(name, index)
self.remove(child)
return child | [
"\n Remove the child having the given name at the given position\n\n :type name: ``str``\n :param name: child name (e.g. PID)\n\n :type index: ``int``\n :param index: child index\n\n :return: an instance of :class:`Element <hl7apy.core.Element>` subclass\n "
] |
Please provide a description of the function:def child_at_index(self, name, index):
def _finder(n, i):
try:
return self.indexes[n][i]
except (KeyError, IndexError):
try:
return self.traversal_indexes[n][i]
except (KeyError, IndexError):
return None
child = _finder(name, index)
child_name = None if name is None else self._find_name(name)
if child_name != name:
child = _finder(child_name, index)
return child | [
"\n Return the child named `name` at the given index\n\n :type name: ``str``\n :param name: child name (e.g. PID)\n\n :type index: ``int``\n :param index: child index\n\n :return: an instance of :class:`Element <hl7apy.core.Element>` subclass\n "
] |
Please provide a description of the function:def create_element(self, name, traversal_parent=False, reference=None):
if reference is None:
reference = self.element.find_child_reference(name)
if reference is not None:
cls = reference['cls']
element_name = reference['name']
kwargs = {'reference': reference['ref'],
'validation_level': self.element.validation_level,
'version': self.element.version}
if not traversal_parent:
kwargs['parent'] = self.element
else:
kwargs['traversal_parent'] = self.element
return cls(element_name, **kwargs)
else:
raise ChildNotFound(name) | [
"\n Create an element having the given name\n\n :type name: ``str``\n :param name: the name of the element to be created (e.g. PID)\n\n :type traversal_parent: ``bool``\n :param traversal_parent: if ``True``, the parent will be set as temporary for traversal purposes\n\n :param reference: the new element structure (see :func:`load_reference <hl7apy.load_reference>`)\n\n :return: an instance of an :class:`hl7apy.core.Element` subclass\n\n :raises: :exc:`ChildNotFound <hl7apy.exceptions.ChildNotFound>` if the element does not exist\n "
] |
Please provide a description of the function:def _find_name(self, name):
name = name.upper()
element = self.element.find_child_reference(name)
return element['name'] if element is not None else None | [
"\n Find the reference of a child having the given name\n\n :type name: ``str``\n :param name: the child name (e.g. PID)\n\n :return: the element structure (see :func:`load_reference <hl7apy.load_reference>`) or ``None`` if the\n element has not been found\n "
] |
Please provide a description of the function:def _default_child_lookup(self, name):
if name in self.indexes or name in self.traversal_indexes:
try:
return self.proxies[name]
except KeyError:
self.proxies[name] = ElementProxy(self, name)
return self.proxies[name]
else: # child not found in the indexes dictionary (e.g. msh_9.message_code, msh_9.msh_9_1)
child_name = self._find_name(name)
if child_name is not None:
try:
return self.proxies[child_name]
except KeyError:
self.proxies[child_name] = ElementProxy(self, child_name)
return self.proxies[child_name] | [
"\n Return an instance of :class:`ElementProxy <hl7apy.core.ElementProxy>` containing the children found\n having the given name\n\n :type name: ``str``\n :param name: the name of the children (e.g. PID)\n\n :return: an instance of :class:`ElementProxy <hl7apy.core.ElementProxy>` containing the results\n "
] |
Please provide a description of the function:def get_structure(element, reference=None):
if reference is None:
try:
reference = load_reference(element.name, element.classname, element.version)
except (ChildNotFound, KeyError):
raise InvalidName(element.classname, element.name)
if not isinstance(reference, collections.Sequence):
raise Exception
return ElementFinder._parse_structure(element, reference) | [
"\n Get the element structure\n\n :type element: :class:`Element <hl7apy.core.Element>`\n :param element: element having the given reference structure\n\n :param reference: the element structure from :func:`load_reference <hl7apy.load_reference>` or from a\n message profile\n\n :return: a dictionary containing the structure data\n "
] |
Please provide a description of the function:def _parse_structure(element, reference):
data = {
'reference': reference
}
content_type = reference[0] # content type can be sequence, choice or leaf
if content_type in ('sequence', 'choice'):
children = reference[1]
ordered_children = []
structure = {}
structure_by_longname = {}
repetitions = {}
counters = collections.defaultdict(int)
for c in children:
child_name, child_ref, cardinality, cls = c
k = child_name if child_name not in structure \
else '{0}_{1}'.format(child_name, counters[child_name])
structure[k] = {"ref": child_ref, "name": k, "cls": element.child_classes[cls]}
try:
structure_by_longname[child_ref[3]] = structure[k]
except IndexError:
pass
counters[child_name] += 1
repetitions[k] = cardinality
ordered_children.append(k)
data['repetitions'] = repetitions
data['ordered_children'] = ordered_children
data['structure_by_name'] = structure
data['structure_by_longname'] = structure_by_longname
if len(reference) > 5:
datatype, long_name, table, max_length = reference[2:]
data['datatype'] = datatype
data['table'] = table
data['long_name'] = long_name
return data | [
"\n Parse the given reference\n\n :type element: :class:`Element <hl7apy.core.Element>`\n :param element: element having the given reference structure\n\n :param reference: the element structure from :func:`load_reference <hl7apy.load_reference>` or from a\n message profile\n\n :return: a dictionary containing the structure data\n "
] |
Please provide a description of the function:def to_er7(self, encoding_chars=None, trailing_children=False):
if encoding_chars is None:
encoding_chars = self.encoding_chars
child_class = list(self.child_classes.values())[0]
separator = encoding_chars.get(child_class.__name__.upper(), '')
s = []
for child in self._get_children(trailing_children):
if child:
s.extend(repetition.to_er7(encoding_chars, trailing_children) for repetition in child)
else:
try:
s.append(self._handle_empty_children(encoding_chars))
except NotImplementedError:
pass
return separator.join(s) | [
"\n Returns the HL7 representation of the :class:`Element <hl7apy.core.Element>`. It adds the appropriate\n separator at the end if needed\n\n :type encoding_chars: ``dict``\n :param encoding_chars: The encoding chars to use.\n If it is ``None`` it uses :attr:`self.encoding_chars`,\n which by default is the ones return by\n :func:`get_default_encoding_chars <hl7apy.get_default_encoding_chars>` values\n :rtype: ``str``\n :return: the HL7 representation of the :class:`Element <hl7apy.core.Element>`\n "
] |
Please provide a description of the function:def validate(self, report_file=None):
return Validator.validate(self, reference=self.reference, report_file=report_file) | [
"\n Validate the HL7 element using the :attr:`STRICT <hl7apy.consts.VALIDATION_LEVEL.STRICT>` validation\n level. It calls the :func:`Validator.validate <hl7apy.validation.Validator.validate>` method passing\n the reference used in the instantiation of the element.\n\n :param: report_file: the report file to pass to the validator\n "
] |
Please provide a description of the function:def encoding_chars(self):
if self.parent is not None:
return self.parent.encoding_chars
return get_default_encoding_chars(self.version) | [
"\n A ``dict`` with the encoding chars of the :class:`Element <hl7apy.core.Element>`.\n If the :class:`Element <hl7apy.core.Element>` has a parent it is the parent's\n ``encoding_chars`` otherwise the ones returned by\n :func:`get_default_encoding_chars <hl7apy.get_default_encoding_chars>`\n The structure of the ``dict`` is:\n\n .. code-block:: python\n\n {'SEGMENT' : '\\\\r',\n 'GROUP': '\\\\r',\n 'FIELD' : '|',\n 'COMPONENT' : '^',\n 'SUBCOMPONENT' : '&',\n 'REPETITION' : '~',\n 'ESCAPE' : '\\\\'}\n\n "
] |
Please provide a description of the function:def to_er7(self, encoding_chars=None, trailing_children=False):
if encoding_chars is None:
encoding_chars = self.encoding_chars
try:
return self.value.to_er7(encoding_chars)
except AttributeError:
return self.value | [
"\n Return the ER7-encoded string\n\n :type encoding_chars: ``dict``\n :param encoding_chars: a dictionary containing the encoding chars or None to use the default\n (see :func:`get_default_encoding_chars <hl7apy.get_default_encoding_chars>`)\n\n :type trailing_children: ``bool``\n :param trailing_children: if ``True``, trailing children will be added even if their value is None\n\n :return: the ER7-encoded string\n\n >>> s = SubComponent(\"CE_1\")\n >>> s.value = \"IDENTIFIER\"\n >>> print(s.to_er7())\n IDENTIFIER\n "
] |
Please provide a description of the function:def add_subcomponent(self, name):
if self.is_unknown() and is_base_datatype(self.datatype):
# An unknown component can't have a child
raise ChildNotValid(name, self)
return self.children.create_element(name) | [
"\n Create an instance of :class:`SubComponent <hl7apy.core.SubComponent>` having the given name\n\n :param name: the name of the subcomponent to be created (e.g. CE_1)\n :return: an instance of :class:`SubComponent <hl7apy.core.SubComponent>`\n\n >>> c = Component(datatype='CE')\n >>> ce_1 = c.add_subcomponent('CE_1')\n >>> print(ce_1)\n <SubComponent CE_1>\n >>> print(ce_1 in c.children)\n True\n "
] |
Please provide a description of the function:def add(self, obj):
# base datatype components can't have more than one child
if self.name and is_base_datatype(self.datatype, self.version) and \
len(self.children) >= 1:
raise MaxChildLimitReached(self, obj, 1)
# the name is different from the datatype (i.e. the name has been forced to be equal to the datatype)
try:
if obj.name and obj.name != obj.datatype:
try:
if not _valid_child_name(obj.name, self.datatype):
raise ChildNotValid(obj.name, self)
except AttributeError:
pass
except ChildNotFound: # obj.datatype causes ChildNotFound for some Elements (Message, Groups etc)
raise ChildNotValid(obj, self)
return super(Component, self).add(obj) | [
"\n Add an instance of :class:`SubComponent <hl7apy.core.SubComponent>` to the list of children\n\n :param obj: an instance of :class:`SubComponent <hl7apy.core.SubComponent>`\n\n >>> c = Component('CX_10')\n >>> s = SubComponent(name='CWE_1', value='EXAMPLE_ID')\n >>> s2 = SubComponent(name='CWE_4', value='ALT_ID')\n >>> c.add(s)\n >>> c.add(s2)\n >>> print(c.to_er7())\n EXAMPLE_ID&&&ALT_ID\n "
] |
Please provide a description of the function:def add(self, obj):
# base datatype components can't have more than one child
if self.name and is_base_datatype(self.datatype, self.version) and \
len(self.children) >= 1:
raise MaxChildLimitReached(self, obj, 1)
return super(Field, self).add(obj) | [
"\n Add an instance of :class:`Component <hl7apy.core.Component>` to the list of children\n\n :param obj: an instance of :class:`Component <hl7apy.core.Component>`\n\n >>> f = Field('PID_5')\n >>> f.xpn_1 = 'EVERYMAN'\n >>> c = Component('XPN_2')\n >>> c.value = 'ADAM'\n >>> f.add(c)\n >>> print(f.to_er7())\n EVERYMAN^ADAM\n "
] |
Please provide a description of the function:def to_er7(self, encoding_chars=None, trailing_children=False):
if encoding_chars is None:
encoding_chars = self.encoding_chars
if self.is_named('MSH_1'):
try:
return self.msh_1_1.children[0].value.value
except IndexError:
return self.msh_1_1.children[0].value
elif self.is_named('MSH_2'):
try:
return self.msh_2_1.children[0].value.value
except IndexError:
return self.msh_2_1.children[0].value
return super(Field, self).to_er7(encoding_chars, trailing_children) | [
"\n Return the ER7-encoded string\n\n :type encoding_chars: ``dict``\n :param encoding_chars: a dictionary containing the encoding chars or None to use the default\n (see :func:`get_default_encoding <hl7apy.get_default_encoding_chars>`)\n\n :type trailing_children: ``bool``\n :param trailing_children: if ``True``, trailing children will be added even if their value is None\n\n :return: the ER7-encoded string\n\n >>> msh_9 = Field(\"MSH_9\")\n >>> msh_9.value = \"ADT^A01^ADT_A01\"\n >>> print(msh_9.to_er7())\n ADT^A01^ADT_A01\n "
] |
Please provide a description of the function:def _get_traversal_children(self, name):
name = name.upper()
parts = name.split('_')
try:
assert 3 <= len(parts) <= 4
prefix = "{0}_{1}".format(parts[0], parts[1])
component = int(parts[2])
subcomponent = int(parts[3]) if len(parts) == 4 else None
except (AssertionError, ValueError):
return None, None
else:
if prefix != self.name:
return None, None
return component, subcomponent | [
"\n Retrieve component and subcomponent indexes from the given traversal path\n (e.g. PID_1_2 -> component=2, subcomponent=None)\n "
] |
Please provide a description of the function:def find_child_reference(self, name):
name = name.upper()
element = self.structure_by_name.get(name, None) or self.structure_by_longname.get(name, None)
if element is None: # not found in self.structure
if self.allow_infinite_children and _valid_child_name(name, self.name):
if _valid_z_field_name(name):
datatype = 'ST'
else:
datatype = 'varies'
element = {'cls': Field, 'name': name, 'ref': ('leaf', None, datatype, None, None, -1)}
else:
element = find_reference(name, self.child_classes.values(), self.version)
if element:
raise ChildNotValid(name, self)
else:
raise ChildNotFound(name)
return element | [
"\n Override the corresponding :class`Element <hl7apy.core.Element>`'s method. This is done for segments\n that allow children other than the ones expected in the HL7 structure: the ones with the last known\n field of type `varies` and the Z-Segments.\n The :class:`Field <hl7apy.core.Field>` will be created although it is not found in the HL7 structures,\n but only if its match the pattern `<SegmentName>_<index>`.\n In this case the method returns a reference for a :class:`Field <hl7apy.core.Field>` of type `None`\n in case of Z-Segment and `varies` otherwise.\n\n An example of a segment with the last field of type ``varies`` is the `QPD` in the version 2.5,\n whose last field is QPD_3.\n That means that it allows fields with name QPD_4, QPD_5,...QPD_n.\n "
] |
Please provide a description of the function:def to_er7(self, encoding_chars=None, trailing_children=False):
if encoding_chars is None:
encoding_chars = self.encoding_chars
separator = encoding_chars.get('FIELD')
repetition = encoding_chars.get('REPETITION')
s = [self.name]
for child in self._get_children(trailing_children):
if child is not None:
s.append(repetition.join(item.to_er7(encoding_chars, trailing_children) for item in child))
else:
try:
s.append(self._handle_empty_children(encoding_chars))
except NotImplementedError:
pass
if self.name == 'MSH' and len(s) > 1:
s.pop(1)
return separator.join(s) | [
"\n Return the ER7-encoded string\n\n :type encoding_chars: ``dict``\n :param encoding_chars: a dictionary containing the encoding chars or None to use the default\n (see :func:`get_default_encoding_chars <hl7apy.get_default_encoding_chars>`)\n\n :type trailing_children: ``bool``\n :param trailing_children: if ``True``, trailing children will be added even if their value is None\n\n :return: the ER7-encoded string\n\n >>> pid = Segment(\"PID\")\n >>> pid.pid_1 = '1'\n >>> pid.pid_5 = \"EVERYMAN^ADAM\"\n >>> print(pid.to_er7())\n PID|1||||EVERYMAN^ADAM\n "
] |
Please provide a description of the function:def to_mllp(self, encoding_chars=None, trailing_children=False):
if encoding_chars is None:
encoding_chars = self.encoding_chars
return "{0}{1}{2}{3}{2}".format(MLLP_ENCODING_CHARS.SB,
self.to_er7(encoding_chars, trailing_children),
MLLP_ENCODING_CHARS.CR,
MLLP_ENCODING_CHARS.EB) | [
"\n Returns the er7 representation of the message wrapped with mllp encoding characters\n\n :type encoding_chars: ``dict``\n :param encoding_chars: a dictionary containing the encoding chars or None to use the default\n (see :func:`get_default_encoding_chars <hl7apy.get_default_encoding_chars>`)\n\n :type trailing_children: ``bool``\n :param trailing_children: if ``True``, trailing children will be added even if their value is ``None``\n\n :return: the ER7-encoded string wrapped with the mllp encoding characters\n "
] |
Please provide a description of the function:def validate(element, reference=None, report_file=None):
from hl7apy.core import is_base_datatype
def _check_z_element(el, errs, warns):
if el.classname == 'Field':
if is_base_datatype(el.datatype, el.version) or \
el.datatype == 'varies':
return True
elif el.datatype is not None:
# if the datatype the is a complex datatype, the z element must follow the correct
# structure of that datatype
# Component just to search in the datatypes....
dt_struct = load_reference(el.datatype, 'Datatypes_Structs', el.version)
ref = ('sequence', dt_struct, el.datatype, None, None, -1)
_check_known_element(el, ref, errs, warns)
for c in el.children:
_is_valid(c, None, errs, warns)
return True
def _check_repetitions(el, children, cardinality, child_name, errs):
children_num = len(children)
min_repetitions, max_repetitions = cardinality
if max_repetitions != -1:
if children_num < min_repetitions:
errs.append(ValidationError("Missing required child {}.{}".format(el.name,
child_name)))
elif children_num > max_repetitions:
errs.append(ValidationError("Child limit exceeded {}.{}".format(child_name,
el.name)))
else:
if children_num < min_repetitions:
errs.append(ValidationError("Missing required child {}.{}".format(el.name,
child_name)))
def _check_table_compliance(el, ref, warns):
table = ref[4]
if table is not None:
try:
table_ref = load_reference(table, 'Table', el.version)
except ChildNotFound:
pass
else:
table_children = table_ref[1]
if el.to_er7() not in table_children:
warns.append(ValidationWarning("Value {} not in table {} in element {}.{}".
format(el.to_er7(), table, el.parent.name,
el.name)))
def _check_length(el, ref, warns):
max_length = ref[5]
if -1 < max_length < len(el.to_er7()):
warns.append(ValidationWarning("Exceeded max length ({}) of {}.{}".
format(max_length, el.parent.name, el.name)))
def _check_datatype(el, ref, errs):
ref_datatype = ref[2]
if el.datatype != ref_datatype:
errs.append(ValidationError("Datatype {} is not correct for {}.{} (it must be {})".
format(el.datatype, el.parent.name, el.name, ref[1])))
def _get_valid_children_info(ref):
valid_children = {c[0] for c in ref[1]}
children_refs = ref[1]
return valid_children, children_refs
def _get_child_reference_info(ref):
child_name, cardinality = ref[0], ref[2]
return child_name, cardinality
def _check_known_element(el, ref, errs, warns):
if ref is None:
try:
ref = load_reference(el.name, el.classname, el.version)
except ChildNotFound:
errs.append(ValidationError("Invalid element found: {}".format(el)))
if ref[0] in ('sequence', 'choice'):
element_children = {c.name for c in el.children if not c.is_z_element()}
valid_children, valid_children_refs = _get_valid_children_info(ref)
# check that the children are all allowed children
if not element_children <= valid_children:
errs.append(ValidationError("Invalid children detected for {}: {}".
format(el, list(element_children - valid_children))))
# iterates the valid children
for child_ref in valid_children_refs:
# it gets the structure of the children to check
child_name, cardinality = _get_child_reference_info(child_ref)
try:
# it gets all the occurrences of the children of a type
children = el.children.get(child_name)
except Exception:
# TODO: it is due to the lack of element in the official reference files... should
# we raise an exception here?
pass
else:
_check_repetitions(el, children, cardinality, child_name, errs)
# calls validation for every children
for c in children:
_is_valid(c, child_ref[1], errs, warns)
# finally calls validation for z_elements
z_children = [c for c in el.children if c.is_z_element()]
for c in z_children:
_is_valid(c, None, errs, warns)
else:
_check_table_compliance(el, ref, warns)
_check_length(el, ref, warns)
if el.datatype == 'varies': # TODO: it should check the real rule
return True
_check_datatype(el, ref, errs)
# For complex datatypes element, the reference is the one of the datatype
if not is_base_datatype(el.datatype, el.version):
# Component just to search in the datatypes....
ref = load_reference(el.datatype, 'Datatypes_Structs', el.version)
_is_valid(el, ref, errs, warns)
def _is_valid(el, ref, errs, warns):
if el.is_unknown():
errs.append(ValidationError("Unknown element found: {}.{}".format(el.parent, el)))
return
if el.is_z_element():
return _check_z_element(el, errs, warns)
return _check_known_element(el, ref, errs, warns)
errors = []
warnings = []
_is_valid(element, reference, errors, warnings)
if report_file is not None:
with open(report_file, "w") as f:
for e in errors:
f.write("Error: {}\n".format(e))
for w in warnings:
f.write("Warning: {}\n".format(w))
if errors:
raise errors[0]
return True | [
"\n Checks if the :class:`Element <hl7apy.core.Element>` is a valid HL7 message according to the reference\n specified. If the reference is not specified, it will be used the official HL7 structures for the\n elements.\n In particular it checks:\n\n * the maximum and minimum number of occurrences for every child\n * that children are all allowed\n * the datatype of fields, components and subcomponents\n * the values, in particular the length and the adherence with the HL7 table, if one is specified\n\n It raises the first exception that it finds.\n\n If :attr:`report_file` is specified, it will create a file with all the errors that occur.\n\n :param element: :class:`Element <hl7apy.core.Element>`: The element to validate\n :param reference: the reference to use. Usually is None or a message profile object\n :param report_file: the name of the report file to create\n\n :return: The True if everything is ok\n :raises: :exc:`ValidationError <hl7apy.exceptions.ValidationError>`: when errors occur\n :raises: :exc:`ValidationWarning <hl7apy.exceptions.ValidationWarning>`: errors concerning the values\n "
] |
Please provide a description of the function:def parse_message(message, validation_level=None, find_groups=True, message_profile=None, report_file=None,
force_validation=False):
message = message.lstrip()
encoding_chars, message_structure, version = get_message_info(message)
validation_level = _get_validation_level(validation_level)
try:
reference = message_profile[message_structure] if message_profile else None
except KeyError:
raise MessageProfileNotFound()
try:
m = Message(name=message_structure, reference=reference, version=version,
validation_level=validation_level, encoding_chars=encoding_chars)
except InvalidName:
m = Message(version=version, validation_level=validation_level,
encoding_chars=encoding_chars)
try:
children = parse_segments(message, m.version, encoding_chars, validation_level, m.reference, find_groups)
except AttributeError: # m.reference can raise i
children = parse_segments(message, m.version, encoding_chars, validation_level, find_groups=False)
m.children = children
if force_validation:
if message_profile is None:
Validator.validate(m, report_file=report_file)
else:
Validator.validate(m, message_profile[message_structure], report_file=report_file)
return m | [
"\n Parse the given ER7-encoded message and return an instance of :class:`Message <hl7apy.core.Message>`.\n\n :type message: ``str``\n :param message: the ER7-encoded message to be parsed\n\n :type validation_level: ``int``\n :param validation_level: the validation level. Possible values are those defined in\n :class:`VALIDATION_LEVEL <hl7apy.consts.VALIDATION_LEVEL>` class or ``None`` to use the default\n validation level (see :func:`set_default_validation_level <hl7apy.set_default_validation_level>`)\n\n :type find_groups: ``bool``\n :param find_groups: if ``True``, automatically assign the segments found to the appropriate\n :class:`Groups <hl7apy.core.Group>` instances. If ``False``, the segments found are assigned as\n children of the :class:`Message <hl7apy.core.Message>` instance\n \n :type force_validation: ``bool``\n :type force_validation: if ``True``, automatically forces the message validation after the end of the parsing\n\n :return: an instance of :class:`Message <hl7apy.core.Message>`\n\n >>> message = \"MSH|^~\\&|GHH_ADT||||20080115153000||OML^O33^OML_O33|0123456789|P|2.5||||AL\\\\rPID|1||\" \\\n \"566-554-3423^^^GHH^MR||EVERYMAN^ADAM^A|||M|||2222 HOME STREET^^ANN ARBOR^MI^^USA||555-555-2004|||M\\\\r\"\n >>> m = parse_message(message)\n >>> print(m)\n <Message OML_O33>\n >>> print(m.msh.sending_application.to_er7())\n GHH_ADT\n >>> print(m.children)\n [<Segment MSH>, <Group OML_O33_PATIENT>]\n "
] |
Please provide a description of the function:def parse_segments(text, version=None, encoding_chars=None, validation_level=None, references=None, find_groups=False):
version = _get_version(version)
encoding_chars = _get_encoding_chars(encoding_chars, version)
validation_level = _get_validation_level(validation_level)
segment_sep = encoding_chars['SEGMENT']
segments = []
parents_refs = [(None, references)]
current_parent = None
for s in text.split(segment_sep):
if len(s) > 0:
segment_name = s[:3]
for x in xrange(len(parents_refs)):
if not find_groups:
segment = parse_segment(s.strip(), version, encoding_chars, validation_level)
segments.append(segment)
else:
ref, parents_refs = _get_segment_reference(segment_name, parents_refs)
if ref is None:
# group not found at the current level, go back to the previous level
if current_parent is not None:
parents_refs.pop()
current_parent = current_parent.parent
else:
if current_parent is None and parents_refs[-1][0] is not None or \
current_parent is not None and parents_refs[-1][0] != current_parent.name:
# create the parents group of the segment
if current_parent is not None:
cur_idx = parents_refs.index((current_parent.name, current_parent.reference))
else:
cur_idx = parents_refs.index((None, references))
for p_ref in parents_refs[cur_idx+1:]:
group = Group(p_ref[0], version=version, reference=p_ref[1],
validation_level=validation_level)
if current_parent is None:
segments.append(group)
else:
current_parent.add(group)
current_parent = group
elif current_parent is not None and segment_name in [c.name for c in current_parent.children] \
and current_parent.repetitions[segment_name][1] == 1:
# The number of instances allowed is reached so we create another instance of the same
group = Group(current_parent.name, version=version, reference=current_parent.reference,
validation_level=validation_level)
if current_parent.parent is None:
segments.append(group)
else:
current_parent.parent.add(group)
current_parent = group
segment = parse_segment(s.strip(), version, encoding_chars, validation_level, ref)
if current_parent is None:
segments.append(segment)
else:
current_parent.add(segment)
break
return segments | [
"\n Parse the given ER7-encoded segments and return a list of :class:`hl7apy.core.Segment` instances.\n\n :type text: ``str``\n :param text: the ER7-encoded string containing the segments to be parsed\n\n :type version: ``str``\n :param version: the HL7 version (e.g. \"2.5\"), or ``None`` to use the default\n (see :func:`set_default_version <hl7apy.set_default_version>`)\n\n :type encoding_chars: ``dict``\n :param encoding_chars: a dictionary containing the encoding chars or None to use the default\n (see :func:`set_default_encoding_chars <hl7apy.set_default_encoding_chars>`)\n\n :type validation_level: ``int``\n :param validation_level: the validation level. Possible values are those defined in\n :class:`VALIDATION_LEVEL <hl7apy.consts.VALIDATION_LEVEL>` class or ``None`` to use the default\n validation level (see :func:`validation_level <hl7apy.set_default_validation_level>`)\n\n :type references: ``list``\n :param references: A list of the references of the :class:`Segment <hl7apy.core.Segment>`'s children\n\n :type find_groups: ``bool``\n :param find_groups: if ``True``, automatically assign the segments found to the appropriate\n :class:`Groups <hl7apy.core.Group>` instances. If ``False``, the segments found are assigned as\n children of the :class:`Message <hl7apy.core.Message>` instance\n\n :return: a list of :class:`Segment <hl7apy.core.Segment>` instances\n\n >>> segments = \"EVN||20080115153000||||20080114003000\\\\rPID|1||566-554-3423^^^GHH^MR||EVERYMAN^ADAM^A|||M|||\" \\\n \"2222 HOME STREET^^ANN ARBOR^MI^^USA||555-555-2004|||M\\\\r\"\n >>> print(parse_segments(segments))\n [<Segment EVN>, <Segment PID>]\n "
] |
Please provide a description of the function:def parse_segment(text, version=None, encoding_chars=None, validation_level=None, reference=None):
version = _get_version(version)
encoding_chars = _get_encoding_chars(encoding_chars, version)
validation_level = _get_validation_level(validation_level)
segment_name = text[:3]
text = text[4:] if segment_name != 'MSH' else text[3:]
segment = Segment(segment_name, version=version, validation_level=validation_level,
reference=reference)
segment.children = parse_fields(text, segment_name, version, encoding_chars, validation_level,
segment.structure_by_name, segment.allow_infinite_children)
return segment | [
"\n Parse the given ER7-encoded segment and return an instance of :class:`Segment <hl7apy.core.Segment>`.\n\n :type text: ``str``\n :param text: the ER7-encoded string containing the segment to be parsed\n\n :type version: ``str``\n :param version: the HL7 version (e.g. \"2.5\"), or ``None`` to use the default\n (see :func:`set_default_version <hl7apy.set_default_version>`)\n\n :type encoding_chars: ``dict``\n :param encoding_chars: a dictionary containing the encoding chars or None to use the default\n (see :func:`set_default_encoding_chars <hl7apy.set_default_encoding_chars>`)\n\n :type validation_level: ``int``\n :param validation_level: the validation level. Possible values are those defined in\n :class:`VALIDATION_LEVEL <hl7apy.consts.VALIDATION_LEVEL>` class or ``None`` to use the default\n validation level (see :func:`set_default_validation_level <hl7apy.set_default_validation_level>`)\n\n :type reference: ``dict``\n :param reference: a dictionary containing the element structure returned by\n :func:`load_reference <hl7apy.load_reference>`, :func:`find_reference <hl7apy.find_reference>` or\n belonging to a message profile\n\n :return: an instance of :class:`Segment <hl7apy.core.Segment>`\n\n >>> segment = \"EVN||20080115153000||||20080114003000\"\n >>> s = parse_segment(segment)\n >>> print(s)\n <Segment EVN>\n >>> print(s.to_er7())\n EVN||20080115153000||||20080114003000\n "
] |
Please provide a description of the function:def parse_fields(text, name_prefix=None, version=None, encoding_chars=None, validation_level=None,
references=None, force_varies=False):
version = _get_version(version)
encoding_chars = _get_encoding_chars(encoding_chars, version)
validation_level = _get_validation_level(validation_level)
text = text.strip("\r")
field_sep = encoding_chars['FIELD']
repetition_sep = encoding_chars['REPETITION']
splitted_fields = text.split(field_sep)
fields = []
for index, field in enumerate(splitted_fields):
name = "{0}_{1}".format(name_prefix, index+1) if name_prefix is not None else None
try:
reference = references[name]['ref'] if references is not None else None
except KeyError:
reference = None
if field.strip() or name is None:
if name == 'MSH_2':
fields.append(parse_field(field, name, version, encoding_chars, validation_level,
reference))
else:
for rep in field.split(repetition_sep):
fields.append(parse_field(rep, name, version, encoding_chars, validation_level,
reference, force_varies))
elif name == "MSH_1":
fields.append(parse_field(field_sep, name, version, encoding_chars, validation_level,
reference))
return fields | [
"\n Parse the given ER7-encoded fields and return a list of :class:`hl7apy.core.Field`.\n\n :type text: ``str``\n :param text: the ER7-encoded string containing the fields to be parsed\n\n :type name_prefix: ``str``\n :param name_prefix: the field prefix (e.g. MSH)\n\n :type version: ``str``\n :param version: the HL7 version (e.g. \"2.5\"), or ``None`` to use the default\n (see :func:`set_default_version <hl7apy.set_default_version>`)\n\n :type encoding_chars: ``dict``\n :param encoding_chars: a dictionary containing the encoding chars or None to use the default\n (see :func:`set_default_encoding_chars <hl7apy.set_default_encoding_chars>`)\n\n :type validation_level: ``int``\n :param validation_level: the validation level. Possible values are those defined in\n :class:`VALIDATION_LEVEL <hl7apy.consts.VALIDATION_LEVEL>` class or ``None`` to use the default\n validation level (see :func:`set_default_validation_level <hl7apy.set_default_validation_level>`)\n\n :type references: ``list``\n :param references: A list of the references of the :class:`Field <hl7apy.core.Field>`'s children\n\n :type force_varies: ``bool``\n :param force_varies: flag that force the fields to use a varies structure when no reference is found.\n It is used when a segment ends with a field of type varies that thus support infinite children\n\n :return: a list of :class:`Field <hl7apy.core.Field>` instances\n\n >>> fields = \"1|NUCLEAR^NELDA^W|SPO|2222 HOME STREET^^ANN ARBOR^MI^^USA\"\n >>> nk1_fields = parse_fields(fields, name_prefix=\"NK1\")\n >>> print(nk1_fields)\n [<Field NK1_1 (SET_ID_NK1) of type SI>, <Field NK1_2 (NAME) of type XPN>, <Field NK1_3 (RELATIONSHIP) of type CE>, \\\n<Field NK1_4 (ADDRESS) of type XAD>]\n >>> s = Segment(\"NK1\")\n >>> s.children = nk1_fields\n >>> print(s.to_er7())\n NK1|1|NUCLEAR^NELDA^W|SPO|2222 HOME STREET^^ANN ARBOR^MI^^USA\n >>> unknown_fields = parse_fields(fields)\n >>> s.children = unknown_fields\n >>> print(s.to_er7())\n NK1||||||||||||||||||||||||||||||||||||||||1|NUCLEAR^NELDA^W|SPO|2222 HOME STREET^^ANN ARBOR^MI^^USA\n "
] |
Please provide a description of the function:def parse_field(text, name=None, version=None, encoding_chars=None, validation_level=None,
reference=None, force_varies=False):
version = _get_version(version)
encoding_chars = _get_encoding_chars(encoding_chars, version)
validation_level = _get_validation_level(validation_level)
try:
field = Field(name, version=version, validation_level=validation_level, reference=reference)
except InvalidName:
if force_varies:
reference = ('leaf', None, 'varies', None, None, -1)
field = Field(name, version=version, validation_level=validation_level, reference=reference)
else:
field = Field(version=version, validation_level=validation_level, reference=reference)
if name in ('MSH_1', 'MSH_2'):
s = SubComponent(datatype='ST', value=text, validation_level=validation_level, version=version)
c = Component(datatype='ST', validation_level=validation_level, version=version)
c.add(s)
field.add(c)
else:
children = parse_components(text, field.datatype, version, encoding_chars, validation_level,
field.structure_by_name)
if Validator.is_tolerant(validation_level) and is_base_datatype(field.datatype, version) and \
len(children) > 1:
field.datatype = None
field.children = children
return field | [
"\n Parse the given ER7-encoded field and return an instance of :class:`Field <hl7apy.core.Field>`.\n\n :type text: ``str``\n :param text: the ER7-encoded string containing the fields to be parsed\n\n :type name: ``str``\n :param name: the field name (e.g. MSH_7)\n\n :type version: ``str``\n :param version: the HL7 version (e.g. \"2.5\"), or ``None`` to use the default\n (see :func:`set_default_version <hl7apy.set_default_version>`)\n\n :type encoding_chars: ``dict``\n :param encoding_chars: a dictionary containing the encoding chars or None to use the default\n (see :func:`set_default_encoding_chars <hl7apy.set_default_encoding_chars>`)\n\n :type validation_level: ``int``\n :param validation_level: the validation level. Possible values are those defined in\n :class:`VALIDATION_LEVEL <hl7apy.consts.VALIDATION_LEVEL>` class or ``None`` to use the default\n validation level (see :func:`set_default_validation_level <hl7apy.set_default_validation_level>`)\n\n :type reference: ``dict``\n :param reference: a dictionary containing the element structure returned by\n :func:`load_reference <hl7apy.load_reference>` or :func:`find_reference <hl7apy.find_reference>`\n or belonging to a message profile\n\n :type force_varies: ``boolean``\n :param force_varies: flag that force the fields to use a varies structure when no reference is found.\n It is used when a segment ends with a field of type varies that thus support infinite children\n\n :return: an instance of :class:`Field <hl7apy.core.Field>`\n\n >>> field = \"NUCLEAR^NELDA^W\"\n >>> nk1_2 = parse_field(field, name=\"NK1_2\")\n >>> print(nk1_2)\n <Field NK1_2 (NAME) of type XPN>\n >>> print(nk1_2.to_er7())\n NUCLEAR^NELDA^W\n >>> unknown = parse_field(field)\n >>> print(unknown)\n <Field of type None>\n >>> print(unknown.to_er7())\n NUCLEAR^NELDA^W\n "
] |
Please provide a description of the function:def parse_components(text, field_datatype='ST', version=None, encoding_chars=None,
validation_level=None, references=None):
version = _get_version(version)
encoding_chars = _get_encoding_chars(encoding_chars, version)
validation_level = _get_validation_level(validation_level)
component_sep = encoding_chars['COMPONENT']
components = []
for index, component in enumerate(text.split(component_sep)):
if is_base_datatype(field_datatype, version):
component_datatype = field_datatype
component_name = None
elif field_datatype is None or field_datatype == 'varies':
component_datatype = None
component_name = 'VARIES_{0}'.format(index+1)
else:
component_name = "{0}_{1}".format(field_datatype, index+1)
component_datatype = None
try:
reference = references[component_name]['ref'] \
if None not in (references, component_name) else None
except KeyError:
reference = None
if component.strip() or component_name is None or component_name.startswith("VARIES_"):
components.append(parse_component(component, component_name, component_datatype,
version, encoding_chars, validation_level, reference))
return components | [
"\n Parse the given ER7-encoded components and return a list of :class:`Component <hl7apy.core.Component>`\n instances.\n\n :type text: ``str``\n :param text: the ER7-encoded string containing the components to be parsed\n\n :type field_datatype: ``str``\n :param field_datatype: the datatype of the components (e.g. ST)\n\n :type version: ``str``\n :param version: the HL7 version (e.g. \"2.5\"), or ``None`` to use the default\n (see :func:`set_default_version <hl7apy.set_default_version>`)\n\n :type encoding_chars: ``dict``\n :param encoding_chars: a dictionary containing the encoding chars or None to use the default\n (see :func:`set_default_encoding_chars <hl7apy.set_default_encoding_chars>`)\n\n :type validation_level: ``int``\n :param validation_level: the validation level. Possible values are those defined in\n :class:`VALIDATION_LEVEL <hl7apy.consts.VALIDATION_LEVEL>` class or ``None`` to use the default\n validation level (see :func:`set_default_validation_level <hl7apy.set_default_validation_level>`)\n\n :type references: ``list``\n :param references: A list of the references of the :class:`Component <hl7apy.core.Component>`'s children\n\n :return: a list of :class:`Component <hl7apy.core.Component>` instances\n\n >>> components = \"NUCLEAR^NELDA^W^^TEST\"\n >>> xpn = parse_components(components, field_datatype=\"XPN\")\n >>> print(xpn)\n [<Component XPN_1 (FAMILY_NAME) of type FN>, <Component XPN_2 (GIVEN_NAME) of type ST>, \\\n<Component XPN_3 (SECOND_AND_FURTHER_GIVEN_NAMES_OR_INITIALS_THEREOF) of type ST>, \\\n<Component XPN_5 (PREFIX_E_G_DR) of type ST>]\n >>> print(parse_components(components))\n [<Component ST (None) of type ST>, <Component ST (None) of type ST>, <Component ST (None) of type ST>, \\\n<Component ST (None) of type ST>, <Component ST (None) of type ST>]\n "
] |
Please provide a description of the function:def parse_component(text, name=None, datatype='ST', version=None, encoding_chars=None,
validation_level=None, reference=None):
version = _get_version(version)
encoding_chars = _get_encoding_chars(encoding_chars, version)
validation_level = _get_validation_level(validation_level)
try:
component = Component(name, datatype, version=version, validation_level=validation_level,
reference=reference)
except InvalidName as e:
if Validator.is_strict(validation_level):
raise e
component = Component(datatype, version=version, validation_level=validation_level,
reference=reference)
children = parse_subcomponents(text, component.datatype, version, encoding_chars, validation_level)
if Validator.is_tolerant(component.validation_level) and is_base_datatype(component.datatype, version) and \
len(children) > 1:
component.datatype = None
component.children = children
return component | [
"\n Parse the given ER7-encoded component and return an instance of\n :class:`Component <hl7apy.core.Component>`.\n\n :type text: ``str``\n :param text: the ER7-encoded string containing the components to be parsed\n\n :type name: ``str``\n :param name: the component's name (e.g. XPN_2)\n\n :type datatype: ``str``\n :param datatype: the datatype of the component (e.g. ST)\n\n :type version: ``str``\n :param version: the HL7 version (e.g. \"2.5\"), or ``None`` to use the default\n (see :func:`set_default_version <hl7apy.set_default_version>`)\n\n :type encoding_chars: ``dict``\n :param encoding_chars: a dictionary containing the encoding chars or None to use the default\n (see :func:`set_default_encoding_chars <hl7apy.set_default_encoding_chars>`)\n\n :type validation_level: ``int``\n :param validation_level: the validation level. Possible values are those defined in\n :class:`VALIDATION_LEVEL <hl7apy.consts.VALIDATION_LEVEL>` class or ``None`` to use the default\n validation level (see :func:`set_default_validation_level <hl7apy.set_default_validation_level>`)\n\n :type reference: ``dict``\n :param reference: a dictionary containing the element structure returned by\n :func:`load_reference <hl7apy.load_reference>` or :func:`find_reference <hl7apy.find_reference>`\n or belonging to a message profile\n\n :return: an instance of :class:`Component <hl7apy.core.Component>`\n\n >>> component = \"GATEWAY&1.3.6.1.4.1.21367.2011.2.5.17\"\n >>> cx_4 = parse_component(component, name=\"CX_4\")\n >>> print(cx_4)\n <Component CX_4 (ASSIGNING_AUTHORITY) of type None>\n >>> print(cx_4.to_er7())\n GATEWAY&1.3.6.1.4.1.21367.2011.2.5.17\n >>> print(parse_component(component))\n <Component ST (None) of type None>\n "
] |
Please provide a description of the function:def parse_subcomponents(text, component_datatype='ST', version=None, encoding_chars=None,
validation_level=None):
version = _get_version(version)
encoding_chars = _get_encoding_chars(encoding_chars, version)
validation_level = _get_validation_level(validation_level)
subcomp_sep = encoding_chars['SUBCOMPONENT']
subcomponents = []
for index, subcomponent in enumerate(text.split(subcomp_sep)):
if is_base_datatype(component_datatype, version) or component_datatype is None:
subcomponent_name = None
subcomponent_datatype = component_datatype if component_datatype is not None else 'ST'
else:
subcomponent_name = "{0}_{1}".format(component_datatype, index+1)
subcomponent_datatype = None
if subcomponent.strip() or subcomponent_name is None:
subcomponents.append(parse_subcomponent(subcomponent, subcomponent_name, subcomponent_datatype,
version, validation_level))
return subcomponents | [
"\n Parse the given ER7-encoded subcomponents and return a list of\n :class:`SubComponent <hl7apy.core.SubComponent>` instances.\n\n :type text: ``str``\n :param text: the ER7-encoded string containing the components to be parsed\n\n :type component_datatype: ``str``\n :param component_datatype: the datatype of the subcomponents (e.g. ST)\n\n :type version: ``str``\n :param version: the HL7 version (e.g. \"2.5\"), or ``None`` to use the default\n (see :func:`set_default_version <hl7apy.set_default_version>`)\n\n :type encoding_chars: ``dict``\n :param encoding_chars: a dictionary containing the encoding chars or None to use the default\n (see :func:`set_default_encoding_chars <hl7apy.set_default_encoding_chars>`)\n\n :type validation_level: ``int``\n :param validation_level: the validation level. Possible values are those defined in\n :class:`VALIDATION_LEVEL <hl7apy.consts.VALIDATION_LEVEL>` class or ``None`` to use the default\n validation level (see :func:`set_default_validation_level <hl7apy.set_default_validation_level>`)\n\n :return: a list of :class:`SubComponent <hl7apy.core.SubComponent>` instances\n\n >>> subcomponents= \"ID&TEST&&AHAH\"\n >>> cwe = parse_subcomponents(subcomponents, component_datatype=\"CWE\")\n >>> print(cwe)\n [<SubComponent CWE_1>, <SubComponent CWE_2>, <SubComponent CWE_4>]\n >>> c = Component(datatype='CWE')\n >>> c.children = cwe\n >>> print(c.to_er7())\n ID&TEST&&AHAH\n >>> subs = parse_subcomponents(subcomponents)\n >>> print(subs)\n [<SubComponent ST>, <SubComponent ST>, <SubComponent ST>, <SubComponent ST>]\n >>> c.children = subs\n >>> print(c.to_er7())\n &&&&&&&&&ID&TEST&&AHAH\n "
] |
Please provide a description of the function:def parse_subcomponent(text, name=None, datatype='ST', version=None, validation_level=None):
version = _get_version(version)
validation_level = _get_validation_level(validation_level)
return SubComponent(name=name, datatype=datatype, value=text, version=version,
validation_level=validation_level) | [
"\n Parse the given ER7-encoded component and return an instance of\n :class:`SubComponent <hl7apy.core.SubComponent>`.\n\n :type text: ``str``\n :param text: the ER7-encoded string containing the subcomponent data\n\n :type name: ``str``\n :param name: the subcomponent's name (e.g. XPN_2)\n\n :type datatype: ``str``\n :param datatype: the datatype of the subcomponent (e.g. ST)\n\n :type version: ``str``\n :param version: the HL7 version (e.g. \"2.5\"), or ``None`` to use the default\n (see :func:`set_default_version <hl7apy.set_default_version>`)\n\n :type validation_level: ``int``\n :param validation_level: the validation level. Possible values are those defined in\n :class:`VALIDATION_LEVEL <hl7apy.consts.VALIDATION_LEVEL>` class or ``None`` to use the default\n validation level (see :func:`set_default_validation_level <hl7apy.set_default_validation_level>`)\n\n :return: an instance of :class:`SubComponent <hl7apy.core.SubComponent>`\n "
] |
Please provide a description of the function:def datatype_factory(datatype, value, version=None, validation_level=None):
from hl7apy.validation import Validator
if validation_level is None:
validation_level = get_default_validation_level()
if version is None:
version = get_default_version()
lib = load_library(version)
base_datatypes = lib.get_base_datatypes()
factories = base_datatypes.copy()
if 'DT' in factories:
factories['DT'] = date_factory
if 'TM' in factories:
factories['TM'] = timestamp_factory
if 'DTM' in factories:
factories['DTM'] = datetime_factory
if 'NM' in factories:
factories['NM'] = numeric_factory
if 'SI' in factories:
factories['SI'] = sequence_id_factory
try:
factory = factories[datatype]
if isinstance(factory, FunctionType):
return factory(value, base_datatypes[datatype], validation_level=validation_level)
return factory(value, validation_level=validation_level)
except KeyError:
raise InvalidDataType(datatype)
except ValueError as e:
if Validator.is_strict(validation_level):
raise e
# TODO: Do we really want this? In that case the parent's datatype must be changed accordingly
return factories['ST'](value) | [
"\n Factory function for both base and complex datatypes. It generates the correct object according\n to the datatype in input.\n It should be noted that if you use the factory it is not possible to specify\n some parameters for the datatype (e.g. the format for datetime base datatypes)\n If the value is not valid for the datatype specified if the ``validation_level`` is\n :attr:`hl7apy.consts.VALIDATION_LEVEL.TOLERANT` it generates an :class:`hl7apy.base_datatypes.ST` object\n\n :type datatype: ``str``\n :param datatype: The datatype to be generated\n\n :param value: The value of the datatype\n\n :type version: ``str``\n :param version: A valid HL7 version. It must be one of\n :attr:`SUPPRTED_LIBRARIES <hl7apy.SUPPORTED_LIBRARIES>`\n\n :type validation_level: ``int``\n :param validation_level: It must be a value from class :attr:`validation_level`\n :class:`VALIDATION_LEVEL hl7apy.consts.VALIDATION_LEVEL` or ``None`` to use the default value\n\n :rtype: The type specified in datatype\n\n :raises :exc:`ValueError`: If the ``validation_level`` is\n :attr:`VALIDATION_LEVEL.STRICT <hl7apy.consts.VALIDATION_LEVEL.STRICT>`\n and the value is not valid for the specified datatype\n\n :raises :exc:`InvalidDatatype <hl7apy.exceptions.InvalidDatatype>`: If the ``datatype`` specified is not\n valid for the given ``version``\n\n "
] |
Please provide a description of the function:def date_factory(value, datatype_cls, validation_level=None):
dt_value, fmt = get_date_info(value)
return datatype_cls(dt_value, fmt) | [
"\n Creates a :class:`DT <hl7apy.base_datatypes.DT>` object\n\n The value in input must be a string parsable with :meth:`datetime.strptime`.\n The date format is chosen according to the length of the value as stated in this table:\n\n +-------+-----------+\n |Length |Format |\n +=======+===========+\n |4 |``%Y`` |\n | | |\n +-------+-----------+\n |6 |``%Y%m`` |\n | | |\n +-------+-----------+\n |8 |``%Y%m%d`` |\n | | |\n +-------+-----------+\n\n Some examples that work are:\n\n >>> from hl7apy.base_datatypes import DT\n >>> date_factory(\"1974\", DT) #doctest: +ELLIPSIS\n <hl7apy.base_datatypes.DT object at 0x...>\n >>> date_factory(\"198302\", DT) #doctest: +ELLIPSIS\n <hl7apy.base_datatypes.DT object at 0x...>\n >>> date_factory(\"19880312\", DT) #doctest: +ELLIPSIS\n <hl7apy.base_datatypes.DT object at 0x...>\n\n If the value does not match one of the valid format it raises :exc:`ValueError`\n\n :type value: ``str``\n :param value: the value to assign the date object\n\n :type datatype_cls: `class`\n :param value: the :class:`DT <hl7apy.base_datatypes.DT>` class to use. It has to be one implementation of\n the different version modules\n\n :type validation_level: ``int``\n :param validation_level: It must be a value from class :attr:`validation_level`\n :class:`VALIDATION_LEVEL hl7apy.consts.VALIDATION_LEVEL` or ``None`` to use the default value\n\n :rtype: :class:`hl7apy.base_datatypes.DT`\n "
] |
Please provide a description of the function:def timestamp_factory(value, datatype_cls, validation_level=None):
dt_value, fmt, offset, microsec = get_timestamp_info(value)
return datatype_cls(dt_value, fmt, offset, microsec) | [
"\n Creates a :class:`TM <hl7apy.base_datatypes.TM>` object\n\n The value in input must be a string parsable with :meth:`datetime.strptime`.\n It can also have an offset part specified with the format +/-HHMM.\n The offset can be added with all the allowed format\n The date format is chosen according to the length of the value as stated in this table:\n\n +-------+-----------------+\n |Length |Format |\n +=======+=================+\n |2 |``%H`` |\n +-------+-----------------+\n |4 |``%H%M`` |\n +-------+-----------------+\n |6 |``%H%M%S`` |\n +-------+-----------------+\n |10-13 |``%H%M%S.%f`` |\n +-------+-----------------+\n\n Some examples that work are:\n\n\n >>> from hl7apy.base_datatypes import TM\n >>> timestamp_factory(\"12\", TM) #doctest: +ELLIPSIS\n <hl7apy.base_datatypes.TM object at 0x...>\n >>> timestamp_factory(\"12+0300\", TM) #doctest: +ELLIPSIS\n <hl7apy.base_datatypes.TM object at 0x...>\n >>> timestamp_factory(\"1204\", TM) #doctest: +ELLIPSIS\n <hl7apy.base_datatypes.TM object at 0x...>\n >>> timestamp_factory(\"120434\", TM) #doctest: +ELLIPSIS\n <hl7apy.base_datatypes.TM object at 0x...>\n >>> timestamp_factory(\"120434-0400\", TM) #doctest: +ELLIPSIS\n <hl7apy.base_datatypes.TM object at 0x...>\n\n If the value does not match one of the valid format it raises :exc:ValueError`\n\n :type value: ``str``\n :param value: the value to assign the date object\n\n :type datatype_cls: `class`\n :param value: the :class:`TM <hl7apy.base_datatypes.TM>` class to use. It has to be one implementation\n of the different version modules\n\n :type validation_level: ``int``\n :param validation_level: It must be a value from class :attr:`validation_level`\n :class:`VALIDATION_LEVEL hl7apy.consts.VALIDATION_LEVEL` or ``None`` to use the default value\n\n :rtype: :class:`TM <hl7apy.base_datatypes.TM>`\n "
] |
Please provide a description of the function:def datetime_factory(value, datatype_cls, validation_level=None):
dt_value, fmt, offset, microsec = get_datetime_info(value)
return datatype_cls(dt_value, fmt, offset, microsec) | [
"\n Creates a :class:`hl7apy.base_datatypes.DTM` object\n\n The value in input must be a string parsable with :meth:`datetime.strptime`.\n It can also have an offset part specified with the format +HHMM -HHMM.\n The offset can be added with all the allowed format.\n The date format is chosen according to the length of the value as stated in this table:\n\n +-------+-----------------------+\n |Length |Format |\n +=======+=======================+\n |4 |``%Y`` |\n +-------+-----------------------+\n |6 |``%Y%m`` |\n +-------+-----------------------+\n |8 |``%Y%m%d`` |\n +-------+-----------------------+\n |10 |``%Y%m%d%H`` |\n +-------+-----------------------+\n |12 |``%Y%m%d%H%M`` |\n +-------+-----------------------+\n |14 |``%Y%m%d%H%M%S`` |\n +-------+-----------------------+\n |18-21 |``%Y%m%d%H%M%S.%f`` |\n +-------+-----------------------+\n\n Some examples that work are:\n\n\n >>> from hl7apy.base_datatypes import DTM\n >>> datetime_factory(\"1924\", DTM) #doctest: +ELLIPSIS\n <hl7apy.base_datatypes.DTM object at 0x...>\n >>> datetime_factory(\"1924+0300\", DTM) #doctest: +ELLIPSIS\n <hl7apy.base_datatypes.DTM object at 0x...>\n >>> datetime_factory(\"19220430\", DTM) #doctest: +ELLIPSIS\n <hl7apy.base_datatypes.DTM object at 0x...>\n >>> datetime_factory(\"19220430-0400\", DTM) #doctest: +ELLIPSIS\n <hl7apy.base_datatypes.DTM object at 0x...>\n\n If the value does not match one of the valid format it raises :exc:`ValueError`\n\n :type value: ``str``\n :param value: the value to assign the date object\n\n :type datatype_cls: `class`\n :param value: the :class:`DTM <hl7apy.base_datatypes.DTM>` class to use. It has to be one implementation\n of the different version modules\n\n :type validation_level: ``int``\n :param validation_level: It must be a value from class :attr:`validation_level`\n :class:`VALIDATION_LEVEL hl7apy.consts.VALIDATION_LEVEL` or ``None`` to use the default value\n\n :rtype: :class:`DTM <hl7apy.base_datatypes.DTM>`\n "
] |
Please provide a description of the function:def numeric_factory(value, datatype_cls, validation_level=None):
if not value:
return datatype_cls(validation_level=validation_level)
try:
return datatype_cls(Decimal(value), validation_level=validation_level)
except InvalidOperation:
raise ValueError('{0} is not an HL7 valid NM value'.format(value)) | [
"\n Creates a :class:`NM <hl7apy.base_datatypes.NM>` object\n\n The value in input can be a string representing a decimal number or a ``float``.\n (i.e. a string valid for :class:`decimal.Decimal()`).\n If it's not, a :exc:`ValueError` is raised\n Also an empty string or ``None`` are allowed\n\n :type value: ``str`` or ``None``\n :param value: the value to assign the numeric object\n\n :type datatype_cls: :class:`class`\n :param value: the :class:`NM <hl7apy.base_datatypes.NM>` class to use. It has to be one implementation\n of the different version modules\n\n :type validation_level: ``int``\n :param validation_level: It must be a value from class\n :class:`VALIDATION_LEVEL hl7apy.consts.VALIDATION_LEVEL` or ``None`` to use the default value\n\n :rtype: :class:`NM <hl7apy.base_datatypes.NM>`\n "
] |
Please provide a description of the function:def sequence_id_factory(value, datatype_cls, validation_level=None):
if not value:
return datatype_cls(validation_level=validation_level)
try:
return datatype_cls(int(value), validation_level=validation_level)
except ValueError:
raise ValueError('{0} is not an HL7 valid SI value'.format(value)) | [
"\n Creates a :class:`SI <hl7apy.base_datatypes.SI>` object\n\n The value in input can be a string representing an integer number or an ``int``.\n (i.e. a string valid for ``int()`` ).\n If it's not, a :exc:`ValueError` is raised\n Also an empty string or ``None`` are allowed\n\n :type value: ``str`` or ``None``\n :param value: the value to assign the date object\n\n :type datatype_cls: `class`\n :param value: the SI class to use. It has to be loaded from one implementation of the different version\n modules\n\n :type validation_level: ``int``\n :param validation_level: It must be a value from class\n :class:`VALIDATION_LEVEL hl7apy.consts.VALIDATION_LEVEL` or ``None`` to use the default value\n\n :rtype: :class:`SI <hl7apy.base_datatypes.SI>`\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.