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, ...
[ "\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.notifica...
[ "\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...
[ "\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 reques...
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.filt...
[ "\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...
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 t...
[ "\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 conte...
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.Re...
[ "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: ...
[ "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 ke...
[ "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 ==...
[ "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' % s...
[ "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...
[ "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_s...
[ "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) ...
[ "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: ...
[ "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 str...
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 on...
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('.'): ...
[ "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: ...
[ "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 fo...
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 ...
[ "\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...
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 se...
[ "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']...
[ "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...
[ "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: \"Data...
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 = ...
[ "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...
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...
[ "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 messa...
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_err...
[ "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 ...
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...
[ "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 ...
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(...
[ "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'),...
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 = s...
[ "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...
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, ...
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 ...
[ " 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 symbo...
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] ...
[ " 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 ...
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.i...
[ " 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...
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`...
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. (...
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 ...
[ "\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 >>> i...
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....
[ "\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....
[ "\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...
[ "\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 <...
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) exc...
[ "\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] exce...
[ "\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 = refe...
[ "\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 :p...
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) ...
[ "\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>` ...
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(el...
[ "\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\...
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 = ref...
[ "\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\...
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_...
[ "\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_ch...
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_fil...
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...
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 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: ``boo...
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 ...
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) ...
[ "\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 = SubCom...
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) ...
[ "\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 ...
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 ...
[ "\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 ...
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]) subc...
[ "\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_ch...
[ "\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.Fie...
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 = [se...
[ "\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: ``boo...
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(...
[ "\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_encod...
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 \ ...
[ "\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 numbe...
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) validatio...
[ "\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 de...
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(val...
[ "\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 ...
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) s...
[ "\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 t...
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...
[ "\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 ...
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 = _...
[ "\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 :p...
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 = ...
[ "\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 th...
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 ...
[ "\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 :ty...
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_va...
[ "\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: t...
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=ver...
[ "\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 ...
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_ve...
[ "\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 valu...
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 +=======+======...
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...
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 accordin...
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: ...
[ "\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 :...
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...
[ "\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: ``s...