text
stringlengths
81
112k
Convert a EUC-CN (GB2312) hex to a Python unicode string. def euc_to_python(hexstr): """ Convert a EUC-CN (GB2312) hex to a Python unicode string. """ hi = hexstr[0:2] lo = hexstr[2:4] gb_enc = b'\\x' + hi + b'\\x' + lo return gb_enc.decode("gb2312")
Convert EUC hex (e.g. "d2bb") to UTF8 hex (e.g. "e4 b8 80"). def euc_to_utf8(euchex): """ Convert EUC hex (e.g. "d2bb") to UTF8 hex (e.g. "e4 b8 80"). """ utf8 = euc_to_python(euchex).encode("utf-8") uf8 = utf8.decode('unicode_escape') uf8 = uf8.encode('latin1') uf8 = uf8.decode('euc-jp')...
Convert a Unicode Universal Character Number (e.g. "U+4E00" or "4E00") to Python unicode (u'\\u4e00') def ucn_to_unicode(ucn): """ Convert a Unicode Universal Character Number (e.g. "U+4E00" or "4E00") to Python unicode (u'\\u4e00') """ if isinstance(ucn, string_types): ucn = ucn.strip(...
Return EUC-CN (GB2312) hex to a Python unicode. Parameters ---------- hexstr : bytes Returns ------- unicode : Python unicode e.g. ``u'\\u4e00'`` / '一'. Examples -------- >>> u'\u4e00'.encode('gb2312').decode('utf-8') u'\u04bb' >>> (b'\\x' + b'd2' + b'\\x' + b'b...
Return UCN character from Python Unicode character. Converts a one character Python unicode string (e.g. u'\\u4e00') to the corresponding Unicode UCN ('U+4E00'). def python_to_ucn(uni_char, as_bytes=False): """ Return UCN character from Python Unicode character. Converts a one character Python un...
Return EUC character from a Python Unicode character. Converts a one character Python unicode string (e.g. u'\\u4e00') to the corresponding EUC hex ('d2bb'). def python_to_euc(uni_char, as_bytes=False): """ Return EUC character from a Python Unicode character. Converts a one character Python unic...
Return ucnstring as Unicode. def ucnstring_to_unicode(ucn_string): """Return ucnstring as Unicode.""" ucn_string = ucnstring_to_python(ucn_string).decode('utf-8') assert isinstance(ucn_string, text_type) return ucn_string
Return string with Unicode UCN (e.g. "U+4E00") to native Python Unicode (u'\\u4e00'). def ucnstring_to_python(ucn_string): """ Return string with Unicode UCN (e.g. "U+4E00") to native Python Unicode (u'\\u4e00'). """ res = re.findall("U\+[0-9a-fA-F]*", ucn_string) for r in res: ucn_...
Returns a tuple consisting of a string and a tag, or None, if none is specified. def parse_var(var): """ Returns a tuple consisting of a string and a tag, or None, if none is specified. """ bits = var.split("<", 1) if len(bits) < 2: tag = None else: tag = bits[1] ret...
Create a Cihai instance from a JSON or YAML config. Parameters ---------- config_path : str, optional path to custom config file Returns ------- :class:`Cihai` : application object def from_file(cls, config_path=None, *args, **kwargs): "...
Return True if this locale should be processed. def _process_locale(self, locale): """Return True if this locale should be processed.""" if locale.lower().startswith('en'): return False return (locale in self.enabled_locales or self.reverse_locale_map.get(locale.l...
Return the Desk-style locale for locale. def desk_locale(self, locale): """Return the Desk-style locale for locale.""" locale = locale.lower().replace('-', '_') return self.vendor_locale_map.get(locale, locale)
Push topics to Transifex. def push(self): """Push topics to Transifex.""" tx = Tx(self.tx_project_slug) # asssemble the template catalog template = babel.messages.catalog.Catalog() for topic in self.desk.topics(): if topic.show_in_portal: template.a...
Pull topics from Transifex. def pull(self): """Pull topics from Transifex.""" topic_stats = txlib.api.statistics.Statistics.get( project_slug=self.tx_project_slug, resource_slug=self.TOPIC_STRINGS_SLUG, ) translated = {} # for each language for...
Return a single HTML document containing the title and content. def make_resource_document(self, title, content, tags=[],): """Return a single HTML document containing the title and content.""" assert "<html>" not in content assert "<body>" not in content return """ <html> ...
Return a dict with the keys title, content, tags for content. def parse_resource_document(self, content): """Return a dict with the keys title, content, tags for content.""" content = content.strip() if not content.startswith('<html>'): # this is not a full HTML doc, probably cont...
Push tutorials to Transifex. def push(self): """Push tutorials to Transifex.""" tx = Tx(self.tx_project_slug) if self.options.resources: articles = [ self.desk.articles().by_id(r.strip()) for r in self.options.resources.split(',') ] ...
Gets or creates the Transifex project for the current project prefix and locale :param locale: A locale to which content is to be translated :type locale: string :param source_language_code: The language of the original untranslated content (i.e. Spanish), defaults to DEFAULT_SOURCE...
Return True if the translation exists for this slug. def translation_exists(self, slug, lang): """Return True if the translation exists for this slug.""" try: return translations.Translation.get( project_slug=self.get_project_slug(lang), slug=slug, ...
Return a sequence of resources for a given lang. Each Resource is a dict containing the slug, name, i18n_type, source_language_code and the category. def list_resources(self, lang): """Return a sequence of resources for a given lang. Each Resource is a dict containing the slug, name, ...
Generate a list of Resources in the Project. Yields dicts from the Tx API, with keys including the slug, name, i18n_type, source_language_code, and category. def resources(self, lang, slug): """Generate a list of Resources in the Project. Yields dicts from the Tx API, with keys includ...
Return True if a Resource with the given slug exists in locale. def resource_exists(self, slug, locale, project_slug=None): """Return True if a Resource with the given slug exists in locale.""" try: resource = resources.Resource.get( project_slug=project_slug or self.get_pr...
Do HTTP/S request and return response as a string. def session_request(session, url, **kwargs): """Do HTTP/S request and return response as a string.""" try: response = session(url, **kwargs) response.raise_for_status() return response.text except requests.exceptions.HTTPError as...
Get a dict of supported events from device. def get_event_list(config): """Get a dict of supported events from device.""" eventinstances = session_request( config.session.post, device_event_url.format( proto=config.web_proto, host=config.host, port=config.port), auth=config.session....
Converts event instances to a relevant dictionary. def _prepare_event(eventinstances): """Converts event instances to a relevant dictionary.""" import xml.etree.ElementTree as ET def parse_event(events): """Find all events inside of an topicset list. MessageInstance signals that subsequen...
Represent device base url. def url(self): """Represent device base url.""" return URL.format(http=self.web_proto, host=self.host, port=self.port)
Pre-process raw dict. Prepare parameters to work with APIItems. def process_raw(self, raw: dict) -> None: """Pre-process raw dict. Prepare parameters to work with APIItems. """ raw_ports = {} for param in raw: port_index = REGEX_PORT_INDEX.search(param).gr...
Return name relevant to direction. def name(self) -> str: """Return name relevant to direction.""" if self.direction == DIRECTION_IN: return self.raw.get('Input.Name', '') return self.raw.get('Output.Name', '')
r"""Activate or deactivate an output. Use the <wait> option to activate/deactivate the port for a limited period of time. <Port ID> = Port name. Default: Name from Output.Name <a> = Action character. /=active, \=inactive <wait> = Delay before the next action. Unit: milliseco...
Load device parameters and initialize parameter management. Preload data can be disabled to selectively load params afterwards. def initialize_params(self, preload_data=True) -> None: """Load device parameters and initialize parameter management. Preload data can be disabled to selectively lo...
Load IO port parameters for device. def initialize_ports(self) -> None: """Load IO port parameters for device.""" if not self.params: self.initialize_params(preload_data=False) self.params.update_ports() self.ports = Ports(self.params, self.request)
Load device user data and initialize user management. def initialize_users(self) -> None: """Load device user data and initialize user management.""" users = self.request('get', pwdgrp_url) self.users = Users(users, self.request)
Prepare HTTP request. def request(self, method, path, **kwargs): """Prepare HTTP request.""" if method == 'get': session_method = self.config.session.get elif method == 'post': session_method = self.config.session.post else: raise AxisException ...
New event to process. def new_event(self, event_data: str) -> None: """New event to process.""" event = self.parse_event_xml(event_data) if EVENT_OPERATION in event: self.manage_event(event)
Parse metadata xml. def parse_event_xml(self, event_data) -> dict: """Parse metadata xml.""" event = {} event_xml = event_data.decode() message = MESSAGE.search(event_xml) if not message: return {} event[EVENT_OPERATION] = message.group(EVENT_OPERATION) ...
Received new metadata. Operation initialized means new event, also happens if reconnecting. Operation changed updates existing events state. def manage_event(self, event) -> None: """Received new metadata. Operation initialized means new event, also happens if reconnecting. Op...
Update state of event. def state(self, state: str) -> None: """Update state of event.""" self._state = state for callback in self._callbacks: callback()
Remove callback. def remove_callback(self, callback) -> None: """Remove callback.""" if callback in self._callbacks: self._callbacks.remove(callback)
Enable events for stream. def enable_events(self, event_callback=None) -> None: """Enable events for stream.""" self.event = EventManager(event_callback) self.stream.event = self.event
Update brand group of parameters. def update_brand(self) -> None: """Update brand group of parameters.""" self.update(path=URL_GET + GROUP.format(group=BRAND))
Update port groups of parameters. def update_ports(self) -> None: """Update port groups of parameters.""" self.update(path=URL_GET + GROUP.format(group=INPUT)) self.update(path=URL_GET + GROUP.format(group=IOPORT)) self.update(path=URL_GET + GROUP.format(group=OUTPUT))
Create a smaller dictionary containing all ports. def ports(self) -> dict: """Create a smaller dictionary containing all ports.""" return { param: self[param].raw for param in self if param.startswith(IOPORT) }
Update properties group of parameters. def update_properties(self) -> None: """Update properties group of parameters.""" self.update(path=URL_GET + GROUP.format(group=PROPERTIES))
Pre-process raw string. Prepare parameters to work with APIItems. def process_raw(self, raw: str) -> None: """Pre-process raw string. Prepare parameters to work with APIItems. """ raw_params = dict(group.split('=', 1) for group in raw.splitlines()) super().process_raw...
Create new user. def create(self, user: str, *, pwd: str, sgrp: str, comment: str=None) -> None: """Create new user.""" data = { 'action': 'add', 'user': user, 'pwd': pwd, 'grp': 'users', 'sgrp': sgrp } if comme...
Remove user. def delete(self, user: str) -> None: """Remove user.""" data = { 'action': 'remove', 'user': user } self._request('post', URL, data=data)
Pre-process raw string. Prepare users to work with APIItems. Create booleans with user levels. def process_raw(self, raw: str) -> None: """Pre-process raw string. Prepare users to work with APIItems. Create booleans with user levels. """ raw_dict = dict(group.s...
Start session. def start(self): """Start session.""" conn = self.loop.create_connection( lambda: self, self.session.host, self.session.port) task = self.loop.create_task(conn) task.add_done_callback(self.init_done)
Server ready. If we get OSError during init the device is not available. def init_done(self, fut): """Server ready. If we get OSError during init the device is not available. """ try: if fut.exception(): fut.result() except OSError as err: ...
Stop session. def stop(self): """Stop session.""" if self.transport: self.transport.write(self.method.TEARDOWN().encode()) self.transport.close() self.rtp.stop()
Connect to device is successful. Start configuring RTSP session. Schedule time out handle in case device doesn't respond. def connection_made(self, transport): """Connect to device is successful. Start configuring RTSP session. Schedule time out handle in case device doesn't r...
Got response on RTSP session. Manage time out handle since response came in a reasonable time. Update session parameters with latest response. If state is playing schedule keep-alive. def data_received(self, data): """Got response on RTSP session. Manage time out handle since ...
If we don't get a response within time the RTSP request time out. This usually happens if device isn't available on specified IP. def time_out(self): """If we don't get a response within time the RTSP request time out. This usually happens if device isn't available on specified IP. ""...
Return RTSP method based on sequence number from session. def message(self): """Return RTSP method based on sequence number from session.""" message = self.message_methods[self.session.method]() _LOGGER.debug(message) return message
Request options device supports. def OPTIONS(self, authenticate=True): """Request options device supports.""" message = "OPTIONS " + self.session.url + " RTSP/1.0\r\n" message += self.sequence message += self.authentication if authenticate else '' message += self.user_agent ...
Request description of what services RTSP server make available. def DESCRIBE(self): """Request description of what services RTSP server make available.""" message = "DESCRIBE " + self.session.url + " RTSP/1.0\r\n" message += self.sequence message += self.authentication message ...
Set up stream transport. def SETUP(self): """Set up stream transport.""" message = "SETUP " + self.session.control_url + " RTSP/1.0\r\n" message += self.sequence message += self.authentication message += self.user_agent message += self.transport message += '\r\n'...
RTSP session is ready to send data. def PLAY(self): """RTSP session is ready to send data.""" message = "PLAY " + self.session.url + " RTSP/1.0\r\n" message += self.sequence message += self.authentication message += self.user_agent message += self.session_id mess...
Generate authentication string. def authentication(self): """Generate authentication string.""" if self.session.digest: authentication = self.session.generate_digest() elif self.session.basic: authentication = self.session.generate_basic() else: retur...
Generate transport string. def transport(self): """Generate transport string.""" transport = "Transport: RTP/AVP;unicast;client_port={}-{}\r\n" return transport.format( str(self.session.rtp_port), str(self.session.rtcp_port))
Which state the session is in. Starting - all messages needed to get stream started. Playing - keep-alive messages every self.session_timeout. def state(self): """Which state the session is in. Starting - all messages needed to get stream started. Playing - keep-alive messages...
Update session information from device response. Increment sequence number when starting stream, not when playing. If device requires authentication resend previous message with auth. def update(self, response): """Update session information from device response. Increment sequence nu...
RFC 2617. def generate_digest(self): """RFC 2617.""" from hashlib import md5 ha1 = self.username + ':' + self.realm + ':' + self.password HA1 = md5(ha1.encode('UTF-8')).hexdigest() ha2 = self.method + ':' + self.url HA2 = md5(ha2.encode('UTF-8')).hexdigest() encr...
RFC 2617. def generate_basic(self): """RFC 2617.""" from base64 import b64encode if not self.basic_auth: creds = self.username + ':' + self.password self.basic_auth = 'Basic ' self.basic_auth += b64encode(creds.encode('UTF-8')).decode('UTF-8') return ...
Retry calling the decorated function using an exponential backoff. :param callback_by_exception: callback/method invocation on certain exceptions :type callback_by_exception: None or dict def retry(ExceptionToCheck, tries=10, timeout_secs=1.0, logger=None, callback_by_exception=None): """ Retry calling...
Build url for stream. def stream_url(self): """Build url for stream.""" rtsp_url = RTSP_URL.format( host=self.config.host, video=self.video_query, audio=self.audio_query, event=self.event_query) _LOGGER.debug(rtsp_url) return rtsp_url
Signalling from stream session. Data - new data available for processing. Playing - Connection is healthy. Retry - if there is no connection to device. def session_callback(self, signal): """Signalling from stream session. Data - new data available for processing. Play...
Start stream. def start(self): """Start stream.""" if not self.stream or self.stream.session.state == STATE_STOPPED: self.stream = RTSPClient( self.config.loop, self.stream_url, self.config.host, self.config.username, self.config.password, sel...
Stop stream. def stop(self): """Stop stream.""" if self.stream and self.stream.session.state != STATE_STOPPED: self.stream.stop()
No connection to device, retry connection after 15 seconds. def retry(self): """No connection to device, retry connection after 15 seconds.""" self.stream = None self.config.loop.call_later(RETRY_TIMER, self.start) _LOGGER.debug('Reconnecting to %s', self.config.host)
return an inspector object def connect_mysql(): """ return an inspector object """ MySQLConnection.get_characterset_info = MySQLConnection.get_charset db = create_engine(engine_name) db.echo = True db.connect() return db
Checks whether a user has permission to perform an action. The permission_code parameter should be a permission contained in tPerm. If the user does not have permission to perfom an action, a permission error is thrown. def check_perm(user_id, permission_code): """ Checks whether a...
Decorator applied to functions requiring caller to possess permission Takes args tuple of required perms and raises PermissionsError via check_perm if these are not a subset of user perms def required_perms(*req_perms): """ Decorator applied to functions requiring caller to possess permission ...
Decorator applied to functions requiring caller to possess the specified role def required_role(req_role): """ Decorator applied to functions requiring caller to possess the specified role """ def dec_wrapper(wfunc): @wraps(wfunc) def wrapped(*args, **kwargs): user_id = ...
Given a time period name, fetch the hydra-compatible time abbreviation. def get_time_period(period_name): """ Given a time period name, fetch the hydra-compatible time abbreviation. """ time_abbreviation = time_map.get(period_name.lower()) if time_abbreviation is None: ...
Turn a string timestamp into a date time. First tries to use dateutil. Failing that it tries to guess the time format and converts it manually using stfptime. @returns: A timezone unaware timestamp. def get_datetime(timestamp): """ Turn a string timestamp into a date time. First tr...
Convert a timestamp as defined in the soap interface to the time format stored in the database. def timestamp_to_ordinal(timestamp): """Convert a timestamp as defined in the soap interface to the time format stored in the database. """ if timestamp is None: return None ts_time = get_d...
Convert a date to a standard string used by Hydra. The resulting string looks like this:: '2013-10-03 00:49:17.568-0400' Hydra also accepts seasonal time series (yearly recurring). If the flag ``seasonal`` is set to ``True``, this function will generate a string recognised by Hydra as seasonal...
Try to guess the format a date is written in. The following formats are supported: ================= ============== =============== Format Example Python format ----------------- -------------- --------------- ``YYYY-MM-DD`` 2002-04-21 %Y-%m-%d ``YYYY.MM.DD`` 2002.0...
get data for timesamp :param a JSON string, in pandas-friendly format :param a timestamp or list of timestamps (datetimes) :returns a pandas data frame, reindexed with the supplied timestamos or None if no data is found def reindex_timeseries(ts_string, new_timestamps): """ get dat...
Read in the time step and convert it to seconds. def parse_time_step(time_step, target='s', units_ref=None): """ Read in the time step and convert it to seconds. """ log.info("Parsing time step %s", time_step) # export numerical value from string using regex value = re.findall(r'\d+', time_...
Create a list of datetimes based on an start time, end time and time step. If such a list is already passed in, then this is not necessary. Often either the start_time, end_time, time_step is passed into an app or the time_axis is passed in directly. This function returns a tim...
Get all the complex mode attributes in the network so that they can be used for mapping to resource scenarios later. def _get_all_attributes(network): """ Get all the complex mode attributes in the network so that they can be used for mapping to resource scenarios later. """ attrs =...
Takes an entire network complex model and saves it to the DB. This complex model includes links & scenarios (with resource data). Returns the network's complex model. As links connect two nodes using the node_ids, if the nodes are new they will not yet have node_ids. In this case, use negative ids as...
Get all the attributes for the nodes, links and groups of a network. Return these attributes as a dictionary, keyed on type (NODE, LINK, GROUP) then by ID of the node or link. def _get_all_resource_attributes(network_id, template_id=None): """ Get all the attributes for the nodes, links and...
Get all the templates for the nodes, links and groups of a network. Return these templates as a dictionary, keyed on type (NODE, LINK, GROUP) then by ID of the node or link. def _get_all_templates(network_id, template_id): """ Get all the templates for the nodes, links and groups of a netwo...
Get all the resource group items in the network, across all scenarios returns a dictionary of dict objects, keyed on scenario_id def _get_all_group_items(network_id): """ Get all the resource group items in the network, across all scenarios returns a dictionary of dict objects, keyed on sce...
Get all the resource scenarios in a network, across all scenarios returns a dictionary of dict objects, keyed on scenario_id def _get_all_resourcescenarios(network_id, user_id): """ Get all the resource scenarios in a network, across all scenarios returns a dictionary of dict objects, keyed...
Get all the metadata in a network, across all scenarios returns a dictionary of dict objects, keyed on dataset ID def _get_metadata(network_id, user_id): """ Get all the metadata in a network, across all scenarios returns a dictionary of dict objects, keyed on dataset ID """ log.inf...
Get all the nodes in a network def _get_network_owners(network_id): """ Get all the nodes in a network """ owners_i = db.DBSession.query(NetworkOwner).filter( NetworkOwner.network_id==network_id).options(noload('network')).options(joinedload_all('user')).all() owners = ...
Get all the nodes in a network def _get_nodes(network_id, template_id=None): """ Get all the nodes in a network """ extras = {'types':[], 'attributes':[]} node_qry = db.DBSession.query(Node).filter( Node.network_id==network_id, Node.status=='A')....
Get all the links in a network def _get_links(network_id, template_id=None): """ Get all the links in a network """ extras = {'types':[], 'attributes':[]} link_qry = db.DBSession.query(Link).filter( Link.network_id==network_id, ...
Get all the resource groups in a network def _get_groups(network_id, template_id=None): """ Get all the resource groups in a network """ extras = {'types':[], 'attributes':[]} group_qry = db.DBSession.query(ResourceGroup).filter( ResourceGroup.network_id=...
Get all the scenarios in a network def _get_scenarios(network_id, include_data, user_id, scenario_ids=None): """ Get all the scenarios in a network """ scen_qry = db.DBSession.query(Scenario).filter( Scenario.network_id == network_id).options( noload('net...
Return a whole network as a dictionary. network_id: ID of the network to retrieve include_data: 'Y' or 'N'. Indicate whether scenario data is to be returned. This has a significant speed impact as retrieving large amounts of data can be expensive. scen...
Get all the nodes in a network. args: network_id (int): The network in which to search template_id (int): Only return nodes whose type is in this template. def get_nodes(network_id, template_id=None, **kwargs): """ Get all the nodes in a network. args: ne...
Get all the links in a network. args: network_id (int): The network in which to search template_id (int): Only return links whose type is in this template. def get_links(network_id, template_id=None, **kwargs): """ Get all the links in a network. args: ne...
Get all the resource groups in a network. args: network_id (int): The network in which to search template_id (int): Only return resource groups whose type is in this template. def get_groups(network_id, template_id=None, **kwargs): """ Get all the resource groups in a networ...
Return a whole network as a complex model. def get_network_by_name(project_id, network_name,**kwargs): """ Return a whole network as a complex model. """ try: res = db.DBSession.query(Network.id).filter(func.lower(Network.name).like(network_name.lower()), Network.project_id == project_id).one(...
Return a whole network as a complex model. def network_exists(project_id, network_name,**kwargs): """ Return a whole network as a complex model. """ try: db.DBSession.query(Network.id).filter(func.lower(Network.name).like(network_name.lower()), Network.project_id == project_id).one() re...