code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
# scalarmult(B, l) is the identity
e %= L
P = IDENT
for i in range(253):
if e & 1:
P = edwards_add(P=P, Q=Bpow[i])
e //= 2
assert e == 0, e
return P | def scalarmult_B(e) | Implements scalarmult(B, e) more efficiently. | 7.669298 | 7.495495 | 1.023188 |
p = (y*y - 1) * inverse(D*y*y + 1)
x = powmod(p, (PRIME+3) // 8, PRIME)
if (x*x - p) % PRIME != 0:
i = powmod(2, (PRIME-1) // 4, PRIME)
x = (x*i) % PRIME
if x % 2 != 0:
x = PRIME - x
return x | def recover(y) | given a value y, recover the preimage x | 3.923301 | 3.59703 | 1.090706 |
'''Execute rubberband
Parameters
----------
y : np.ndarray [shape=(n,) or (n, c)]
Audio time series, either single or multichannel
sr : int > 0
sampling rate of y
**kwargs
keyword arguments to rubberband
Returns
-------
y_mod : np.ndarray [shape=(n,) or (n... | def __rubberband(y, sr, **kwargs) | Execute rubberband
Parameters
----------
y : np.ndarray [shape=(n,) or (n, c)]
Audio time series, either single or multichannel
sr : int > 0
sampling rate of y
**kwargs
keyword arguments to rubberband
Returns
-------
y_mod : np.ndarray [shape=(n,) or (n, c)]
... | 2.905316 | 2.340509 | 1.241318 |
'''Apply a time stretch of `rate` to an audio time series.
This uses the `tempo` form for rubberband, so the
higher the rate, the faster the playback.
Parameters
----------
y : np.ndarray [shape=(n,) or (n, c)]
Audio time series, either single or multichannel
sr : int > 0
... | def time_stretch(y, sr, rate, rbargs=None) | Apply a time stretch of `rate` to an audio time series.
This uses the `tempo` form for rubberband, so the
higher the rate, the faster the playback.
Parameters
----------
y : np.ndarray [shape=(n,) or (n, c)]
Audio time series, either single or multichannel
sr : int > 0
Sampli... | 3.602484 | 1.511047 | 2.384098 |
'''Apply a timemap stretch to an audio time series.
A timemap stretch allows non-linear time-stretching by mapping source to
target sample frame numbers for fixed time points within the audio data.
This uses the `time` and `timemap` form for rubberband.
Parameters
----------
y : np.ndarra... | def timemap_stretch(y, sr, time_map, rbargs=None) | Apply a timemap stretch to an audio time series.
A timemap stretch allows non-linear time-stretching by mapping source to
target sample frame numbers for fixed time points within the audio data.
This uses the `time` and `timemap` form for rubberband.
Parameters
----------
y : np.ndarray [shap... | 3.020539 | 1.527488 | 1.977456 |
'''Apply a pitch shift to an audio time series.
Parameters
----------
y : np.ndarray [shape=(n,) or (n, c)]
Audio time series, either single or multichannel
sr : int > 0
Sampling rate of `y`
n_steps : float
Shift by `n_steps` semitones.
rbargs
Additional k... | def pitch_shift(y, sr, n_steps, rbargs=None) | Apply a pitch shift to an audio time series.
Parameters
----------
y : np.ndarray [shape=(n,) or (n, c)]
Audio time series, either single or multichannel
sr : int > 0
Sampling rate of `y`
n_steps : float
Shift by `n_steps` semitones.
rbargs
Additional keyword ... | 3.252832 | 1.652604 | 1.968306 |
zone, point = int(kuten[:2]), int(kuten[2:])
hi, lo = hexd(zone + 0x20), hexd(point + 0x20)
gb2312 = "%s%s" % (hi, lo)
assert isinstance(gb2312, bytes)
return gb2312 | def kuten_to_gb2312(kuten) | Convert GB kuten / quwei form (94 zones * 94 points) to GB2312-1980 /
ISO-2022-CN hex (internal representation) | 4.037923 | 3.49741 | 1.154547 |
hi, lo = int(gb2312hex[:2], 16), int(gb2312hex[2:], 16)
hi, lo = hexd(hi + 0x80), hexd(lo + 0x80)
euc = "%s%s" % (hi, lo)
assert isinstance(euc, bytes)
return euc | def gb2312_to_euc(gb2312hex) | Convert GB2312-1980 hex (internal representation) to EUC-CN hex (the
"external encoding") | 2.565975 | 2.544647 | 1.008382 |
hi = hexstr[0:2]
lo = hexstr[2:4]
gb_enc = b'\\x' + hi + b'\\x' + lo
return gb_enc.decode("gb2312") | def euc_to_python(hexstr) | Convert a EUC-CN (GB2312) hex to a Python unicode string. | 3.456846 | 3.299322 | 1.047744 |
utf8 = euc_to_python(euchex).encode("utf-8")
uf8 = utf8.decode('unicode_escape')
uf8 = uf8.encode('latin1')
uf8 = uf8.decode('euc-jp')
return uf8 | def euc_to_utf8(euchex) | Convert EUC hex (e.g. "d2bb") to UTF8 hex (e.g. "e4 b8 80"). | 3.86948 | 4.083813 | 0.947516 |
if isinstance(ucn, string_types):
ucn = ucn.strip("U+")
if len(ucn) > int(4):
char = b'\U' + format(int(ucn, 16), '08x').encode('latin1')
char = char.decode('unicode_escape')
else:
char = unichr(int(ucn, 16))
else:
char = unichr(ucn)
... | def ucn_to_unicode(ucn) | Convert a Unicode Universal Character Number (e.g. "U+4E00" or "4E00") to
Python unicode (u'\\u4e00') | 3.010956 | 2.853465 | 1.055193 |
hi = hexstr[0:2]
lo = hexstr[2:4]
# hi and lo are only 2 characters long, no risk with eval-ing them
gb_enc = b'\\x' + hi + b'\\x' + lo
assert isinstance(gb_enc, bytes)
# Requires coercing back to text_type in 2.7
gb_enc = gb_enc.decode('unicode_escape')
gb_enc = gb_enc.encode('l... | def euc_to_unicode(hexstr) | 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... | 4.501326 | 5.05155 | 0.891078 |
ucn = uni_char.encode('unicode_escape').decode('latin1')
ucn = text_type(ucn).replace('\\', '').upper().lstrip('U')
if len(ucn) > int(4):
# get rid of the zeroes that Python uses to pad 32 byte UCNs
ucn = ucn.lstrip("0")
ucn = "U+" + ucn.upper()
if as_bytes:
ucn = ucn.e... | def python_to_ucn(uni_char, as_bytes=False) | 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'). | 4.199055 | 4.227019 | 0.993385 |
euc = repr(uni_char.encode("gb2312"))[1:-1].replace("\\x", "").strip("'")
if as_bytes:
euc = euc.encode('utf-8')
assert isinstance(euc, bytes)
return euc | def python_to_euc(uni_char, as_bytes=False) | 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'). | 3.376311 | 3.718411 | 0.907998 |
ucn_string = ucnstring_to_python(ucn_string).decode('utf-8')
assert isinstance(ucn_string, text_type)
return ucn_string | def ucnstring_to_unicode(ucn_string) | Return ucnstring as Unicode. | 3.251984 | 2.970984 | 1.094581 |
res = re.findall("U\+[0-9a-fA-F]*", ucn_string)
for r in res:
ucn_string = ucn_string.replace(text_type(r), text_type(ucn_to_unicode(r)))
ucn_string = ucn_string.encode('utf-8')
assert isinstance(ucn_string, bytes)
return ucn_string | def ucnstring_to_python(ucn_string) | Return string with Unicode UCN (e.g. "U+4E00") to native Python Unicode
(u'\\u4e00'). | 2.979385 | 2.583168 | 1.153384 |
bits = var.split("<", 1)
if len(bits) < 2:
tag = None
else:
tag = bits[1]
return ucn_to_unicode(bits[0]), tag | def parse_var(var) | Returns a tuple consisting of a string and a tag, or None, if none is
specified. | 5.639766 | 4.405279 | 1.280229 |
config_reader = kaptan.Kaptan()
config = {}
if config_path:
if not os.path.exists(config_path):
raise exc.CihaiException(
'{0} does not exist.'.format(os.path.abspath(config_path))
)
if not any(
... | def from_file(cls, config_path=None, *args, **kwargs) | 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 | 2.956326 | 2.825316 | 1.04637 |
if locale.lower().startswith('en'):
return False
return (locale in self.enabled_locales or
self.reverse_locale_map.get(locale.lower(), None)
in self.enabled_locales or
locale in self.lower_locales or
self.reverse_l... | def _process_locale(self, locale) | Return True if this locale should be processed. | 4.027537 | 3.500936 | 1.150417 |
locale = locale.lower().replace('-', '_')
return self.vendor_locale_map.get(locale, locale) | def desk_locale(self, locale) | Return the Desk-style locale for locale. | 6.617466 | 5.226839 | 1.266055 |
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.add(topic.name)
# serialize the catalog as a PO file
templ... | def push(self) | Push topics to Transifex. | 7.802387 | 6.342746 | 1.230128 |
topic_stats = txlib.api.statistics.Statistics.get(
project_slug=self.tx_project_slug,
resource_slug=self.TOPIC_STRINGS_SLUG,
)
translated = {}
# for each language
for locale in self.enabled_locales:
if not self._process_locale(loca... | def pull(self) | Pull topics from Transifex. | 3.759047 | 3.483137 | 1.079213 |
assert "<html>" not in content
assert "<body>" not in content
return % dict(
title=title,
content=content,
) | def make_resource_document(self, title, content, tags=[],) | Return a single HTML document containing the title and content. | 7.316028 | 7.520569 | 0.972802 |
content = content.strip()
if not content.startswith('<html>'):
# this is not a full HTML doc, probably content w/o title, tags, etc
return dict(body=content)
result = {}
if '<title>' in content and '</title>' in content:
result['subject'] =... | def parse_resource_document(self, content) | Return a dict with the keys title, content, tags for content. | 3.551722 | 3.262521 | 1.088643 |
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(',')
]
else:
articles = self.desk.articles()
for a in articles... | def push(self) | Push tutorials to Transifex. | 4.818524 | 4.295725 | 1.121702 |
try:
locale_project = project.Project.get(slug=self.get_project_slug(locale))
except NotFoundError:
locale_project = project.Project(
slug=self.get_project_slug(locale),
)
defaults = {
'name': 'Help Center (%s)' ... | def get_project(self, locale, source_language_code=DEFAULT_SOURCE_LANGUAGE, **kwargs) | 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... | 3.005261 | 2.91104 | 1.032367 |
try:
return translations.Translation.get(
project_slug=self.get_project_slug(lang),
slug=slug,
lang=lang,
)
except (NotFoundError, RemoteServerError):
pass
return False | def translation_exists(self, slug, lang) | Return True if the translation exists for this slug. | 6.975913 | 6.259967 | 1.114369 |
return registry.registry.http_handler.get(
'/api/2/project/%s/resources/' % (
self.get_project_slug(lang),)
) | def list_resources(self, lang) | 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. | 11.510112 | 10.559641 | 1.09001 |
resource = resources.Resource.get(
project_slug=self.get_project_slug(lang),
slug=slug,
)
return resource | def resources(self, lang, slug) | 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. | 5.837417 | 6.435379 | 0.907082 |
try:
resource = resources.Resource.get(
project_slug=project_slug or self.get_project_slug(locale),
slug=slug,
)
return resource
except NotFoundError:
pass
return None | def resource_exists(self, slug, locale, project_slug=None) | Return True if a Resource with the given slug exists in locale. | 3.864965 | 3.849388 | 1.004047 |
try:
response = session(url, **kwargs)
response.raise_for_status()
return response.text
except requests.exceptions.HTTPError as errh:
_LOGGER.debug("%s, %s", response, errh)
raise_error(response.status_code)
except requests.exceptions.ConnectionError as errc:... | def session_request(session, url, **kwargs) | Do HTTP/S request and return response as a string. | 2.019618 | 1.956173 | 1.032433 |
eventinstances = session_request(
config.session.post, device_event_url.format(
proto=config.web_proto, host=config.host, port=config.port),
auth=config.session.auth, headers=headers, data=request_xml)
raw_event_list = _prepare_event(eventinstances)
event_list = {}
for... | def get_event_list(config) | Get a dict of supported events from device. | 6.614533 | 6.224705 | 1.062626 |
import xml.etree.ElementTree as ET
def parse_event(events):
def clean_attrib(attrib={}):
attributes = {}
for key, value in attrib.items():
attributes[key.split('}')[-1]] = value
return attributes
description = {}
... | def _prepare_event(eventinstances) | Converts event instances to a relevant dictionary. | 3.086252 | 2.97061 | 1.038929 |
return URL.format(http=self.web_proto, host=self.host, port=self.port) | def url(self) | Represent device base url. | 9.039797 | 6.793196 | 1.330713 |
raw_ports = {}
for param in raw:
port_index = REGEX_PORT_INDEX.search(param).group(0)
if port_index not in raw_ports:
raw_ports[port_index] = {}
name = param.replace(IOPORT + '.I' + port_index + '.', '')
raw_ports[port_index][na... | def process_raw(self, raw: dict) -> None | Pre-process raw dict.
Prepare parameters to work with APIItems. | 4.008984 | 3.865016 | 1.037249 |
if self.direction == DIRECTION_IN:
return self.raw.get('Input.Name', '')
return self.raw.get('Output.Name', '') | def name(self) -> str | Return name relevant to direction. | 6.291591 | 4.428294 | 1.420771 |
r
if not self.direction == DIRECTION_OUT:
return
port_action = quote(
'{port}:{action}'.format(port=int(self.id)+1, action=action),
safe=''
)
url = URL + ACTION.format(action=port_action)
self._request('get', url) | def action(self, action) | 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... | 9.418401 | 10.97458 | 0.858201 |
params = ''
if preload_data:
params = self.request('get', param_url)
self.params = Params(params, self.request) | def initialize_params(self, preload_data=True) -> None | Load device parameters and initialize parameter management.
Preload data can be disabled to selectively load params afterwards. | 10.613153 | 7.421647 | 1.430027 |
if not self.params:
self.initialize_params(preload_data=False)
self.params.update_ports()
self.ports = Ports(self.params, self.request) | def initialize_ports(self) -> None | Load IO port parameters for device. | 8.801348 | 6.582379 | 1.337107 |
users = self.request('get', pwdgrp_url)
self.users = Users(users, self.request) | def initialize_users(self) -> None | Load device user data and initialize user management. | 18.251036 | 12.659861 | 1.441646 |
if method == 'get':
session_method = self.config.session.get
elif method == 'post':
session_method = self.config.session.post
else:
raise AxisException
url = self.config.url + path
result = session_request(session_method, url, **kwa... | def request(self, method, path, **kwargs) | Prepare HTTP request. | 3.883215 | 3.747725 | 1.036152 |
event = self.parse_event_xml(event_data)
if EVENT_OPERATION in event:
self.manage_event(event) | def new_event(self, event_data: str) -> None | New event to process. | 9.078524 | 7.13517 | 1.272363 |
event = {}
event_xml = event_data.decode()
message = MESSAGE.search(event_xml)
if not message:
return {}
event[EVENT_OPERATION] = message.group(EVENT_OPERATION)
topic = TOPIC.search(event_xml)
if topic:
event[EVENT_TOPIC] = topi... | def parse_event_xml(self, event_data) -> dict | Parse metadata xml. | 2.289831 | 2.235305 | 1.024393 |
name = EVENT_NAME.format(
topic=event[EVENT_TOPIC], source=event.get(EVENT_SOURCE_IDX))
if event[EVENT_OPERATION] == 'Initialized' and name not in self.events:
for event_class in EVENT_CLASSES:
if event_class.TOPIC in event[EVENT_TOPIC]:
... | def manage_event(self, event) -> None | Received new metadata.
Operation initialized means new event, also happens if reconnecting.
Operation changed updates existing events state. | 4.077664 | 3.641831 | 1.119674 |
self._state = state
for callback in self._callbacks:
callback() | def state(self, state: str) -> None | Update state of event. | 8.460043 | 5.556871 | 1.522447 |
if callback in self._callbacks:
self._callbacks.remove(callback) | def remove_callback(self, callback) -> None | Remove callback. | 4.434748 | 3.01494 | 1.470924 |
self.event = EventManager(event_callback)
self.stream.event = self.event | def enable_events(self, event_callback=None) -> None | Enable events for stream. | 10.003253 | 6.101753 | 1.639406 |
self.update(path=URL_GET + GROUP.format(group=BRAND)) | def update_brand(self) -> None | Update brand group of parameters. | 59.633602 | 24.774042 | 2.4071 |
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)) | def update_ports(self) -> None | Update port groups of parameters. | 7.274033 | 5.709356 | 1.274055 |
return {
param: self[param].raw
for param in self
if param.startswith(IOPORT)
} | def ports(self) -> dict | Create a smaller dictionary containing all ports. | 12.266869 | 8.539768 | 1.43644 |
self.update(path=URL_GET + GROUP.format(group=PROPERTIES)) | def update_properties(self) -> None | Update properties group of parameters. | 96.851166 | 39.928741 | 2.4256 |
raw_params = dict(group.split('=', 1) for group in raw.splitlines())
super().process_raw(raw_params) | def process_raw(self, raw: str) -> None | Pre-process raw string.
Prepare parameters to work with APIItems. | 6.799911 | 5.7842 | 1.175601 |
data = {
'action': 'add',
'user': user,
'pwd': pwd,
'grp': 'users',
'sgrp': sgrp
}
if comment:
data['comment'] = comment
self._request('post', URL, data=data) | def create(self, user: str, *,
pwd: str, sgrp: str, comment: str=None) -> None | Create new user. | 3.496412 | 3.241547 | 1.078625 |
data = {
'action': 'remove',
'user': user
}
self._request('post', URL, data=data) | def delete(self, user: str) -> None | Remove user. | 6.549993 | 4.901221 | 1.3364 |
raw_dict = dict(group.split('=') for group in raw.splitlines())
raw_users = {
user: {
group: user in REGEX_STRING.findall(raw_dict[group])
for group in [ADMIN, OPERATOR, VIEWER, PTZ]
}
for user in REGEX_STRING.findall(raw_dict... | def process_raw(self, raw: str) -> None | Pre-process raw string.
Prepare users to work with APIItems.
Create booleans with user levels. | 6.071265 | 5.77798 | 1.050759 |
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) | def start(self) | Start session. | 3.633397 | 3.245033 | 1.119679 |
try:
if fut.exception():
fut.result()
except OSError as err:
_LOGGER.debug('RTSP got exception %s', err)
self.stop()
self.callback(SIGNAL_FAILED) | def init_done(self, fut) | Server ready.
If we get OSError during init the device is not available. | 7.230395 | 7.248951 | 0.99744 |
if self.transport:
self.transport.write(self.method.TEARDOWN().encode())
self.transport.close()
self.rtp.stop() | def stop(self) | Stop session. | 10.115511 | 9.245708 | 1.094076 |
self.transport = transport
self.transport.write(self.method.message.encode())
self.time_out_handle = self.loop.call_later(
TIME_OUT_LIMIT, self.time_out) | def connection_made(self, transport) | Connect to device is successful.
Start configuring RTSP session.
Schedule time out handle in case device doesn't respond. | 4.72276 | 3.55668 | 1.327856 |
self.time_out_handle.cancel()
self.session.update(data.decode())
if self.session.state == STATE_STARTING:
self.transport.write(self.method.message.encode())
self.time_out_handle = self.loop.call_later(
TIME_OUT_LIMIT, self.time_out)
elif... | def data_received(self, data) | 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. | 4.013269 | 3.320907 | 1.208486 |
_LOGGER.warning('Response timed out %s', self.session.host)
self.stop()
self.callback(SIGNAL_FAILED) | 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. | 14.517021 | 10.450486 | 1.389124 |
message = self.message_methods[self.session.method]()
_LOGGER.debug(message)
return message | def message(self) | Return RTSP method based on sequence number from session. | 12.333429 | 7.354095 | 1.677083 |
message = "OPTIONS " + self.session.url + " RTSP/1.0\r\n"
message += self.sequence
message += self.authentication if authenticate else ''
message += self.user_agent
message += self.session_id
message += '\r\n'
return message | def OPTIONS(self, authenticate=True) | Request options device supports. | 4.840613 | 4.566931 | 1.059927 |
message = "DESCRIBE " + self.session.url + " RTSP/1.0\r\n"
message += self.sequence
message += self.authentication
message += self.user_agent
message += "Accept: application/sdp\r\n"
message += '\r\n'
return message | def DESCRIBE(self) | Request description of what services RTSP server make available. | 4.225686 | 3.551152 | 1.189948 |
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'
return message | def SETUP(self) | Set up stream transport. | 5.934971 | 5.273627 | 1.125406 |
message = "PLAY " + self.session.url + " RTSP/1.0\r\n"
message += self.sequence
message += self.authentication
message += self.user_agent
message += self.session_id
message += '\r\n'
return message | def PLAY(self) | RTSP session is ready to send data. | 5.349347 | 4.090453 | 1.307764 |
if self.session.digest:
authentication = self.session.generate_digest()
elif self.session.basic:
authentication = self.session.generate_basic()
else:
return ''
return "Authorization: " + authentication + '\r\n' | def authentication(self) | Generate authentication string. | 4.111048 | 3.452673 | 1.190686 |
transport = "Transport: RTP/AVP;unicast;client_port={}-{}\r\n"
return transport.format(
str(self.session.rtp_port), str(self.session.rtcp_port)) | def transport(self) | Generate transport string. | 6.285849 | 4.750096 | 1.32331 |
if self.method in ['OPTIONS', 'DESCRIBE', 'SETUP', 'PLAY']:
state = STATE_STARTING
elif self.method in ['KEEP-ALIVE']:
state = STATE_PLAYING
else:
state = STATE_STOPPED
_LOGGER.debug('RTSP session (%s) state %s', self.host, state)
retu... | def state(self) | Which state the session is in.
Starting - all messages needed to get stream started.
Playing - keep-alive messages every self.session_timeout. | 5.994031 | 4.428381 | 1.353549 |
data = response.splitlines()
_LOGGER.debug('Received data %s from %s', data, self.host)
while data:
line = data.pop(0)
if 'RTSP/1.0' in line:
self.rtsp_version = int(line.split(' ')[0][5])
self.status_code = int(line.split(' ')[1])... | def update(self, response) | Update session information from device response.
Increment sequence number when starting stream, not when playing.
If device requires authentication resend previous message with auth. | 2.449332 | 2.396998 | 1.021833 |
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()
encrypt_response = HA1 + ':' + self.nonce + ':' + HA2
... | def generate_digest(self) | RFC 2617. | 1.916316 | 1.862367 | 1.028968 |
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 self.basic_auth | def generate_basic(self) | RFC 2617. | 2.869702 | 2.45011 | 1.171255 |
def deco_retry(f):
def f_retry(*args, **kwargs):
mtries, mdelay = tries, timeout_secs
run_one_last_time = True
while mtries > 1:
try:
return f(*args, **kwargs)
except ExceptionToCheck as e:
# che... | def retry(ExceptionToCheck, tries=10, timeout_secs=1.0, logger=None, callback_by_exception=None) | 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 | 3.003117 | 3.069176 | 0.978477 |
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 | def stream_url(self) | Build url for stream. | 4.371603 | 4.112276 | 1.063062 |
if signal == SIGNAL_DATA:
self.event.new_event(self.data)
elif signal == SIGNAL_FAILED:
self.retry()
if signal in [SIGNAL_PLAYING, SIGNAL_FAILED] and \
self.connection_status_callback:
self.connection_status_callback(signal) | def session_callback(self, signal) | Signalling from stream session.
Data - new data available for processing.
Playing - Connection is healthy.
Retry - if there is no connection to device. | 6.577233 | 5.469753 | 1.202474 |
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,
self.session_callback)
self.stream.start() | def start(self) | Start stream. | 4.52639 | 4.024247 | 1.124779 |
if self.stream and self.stream.session.state != STATE_STOPPED:
self.stream.stop() | def stop(self) | Stop stream. | 7.400523 | 5.897167 | 1.254928 |
self.stream = None
self.config.loop.call_later(RETRY_TIMER, self.start)
_LOGGER.debug('Reconnecting to %s', self.config.host) | def retry(self) | No connection to device, retry connection after 15 seconds. | 6.519955 | 5.888474 | 1.10724 |
MySQLConnection.get_characterset_info = MySQLConnection.get_charset
db = create_engine(engine_name)
db.echo = True
db.connect()
return db | def connect_mysql() | return an inspector object | 10.228051 | 9.539201 | 1.072213 |
try:
perm = db.DBSession.query(Perm).filter(Perm.code==permission_code).one()
except NoResultFound:
raise PermissionError("Nonexistent permission type: %s"%(permission_code))
try:
res = db.DBSession.query(User).join(RoleUser, RoleUser.user_id==User.id).\
join(Perm,... | def check_perm(user_id, permission_code) | 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. | 2.624692 | 2.652628 | 0.989469 |
def dec_wrapper(wfunc):
@wraps(wfunc)
def wrapped(*args, **kwargs):
user_id = kwargs.get("user_id")
for perm in req_perms:
check_perm(user_id, perm)
return wfunc(*args, **kwargs)
return wrapped
return dec_wrapper | def required_perms(*req_perms) | 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 | 2.739109 | 2.616786 | 1.046746 |
def dec_wrapper(wfunc):
@wraps(wfunc)
def wrapped(*args, **kwargs):
user_id = kwargs.get("user_id")
try:
res = db.DBSession.query(RoleUser).filter(RoleUser.user_id==user_id).join(Role, Role.code==req_role).one()
except NoResultFound:
... | def required_role(req_role) | Decorator applied to functions requiring caller to possess the specified role | 3.307075 | 3.274507 | 1.009946 |
time_abbreviation = time_map.get(period_name.lower())
if time_abbreviation is None:
raise Exception("Symbol %s not recognised as a time period"%period_name)
return time_abbreviation | def get_time_period(period_name) | Given a time period name, fetch the hydra-compatible time
abbreviation. | 4.341033 | 3.871938 | 1.121153 |
timestamp_is_float = False
try:
float(timestamp)
timestamp_is_float = True
except (ValueError, TypeError):
pass
if timestamp_is_float == True:
raise ValueError("Timestamp %s is a float"%(timestamp,))
#First try to use date util. Failing that, continue
try:
... | def get_datetime(timestamp) | 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. | 3.534903 | 3.465685 | 1.019972 |
if timestamp is None:
return None
ts_time = get_datetime(timestamp)
# Convert time to Gregorian ordinal (1 = January 1st, year 1)
ordinal_ts_time = Decimal(ts_time.toordinal())
total_seconds = (ts_time -
datetime(ts_time.year,
... | def timestamp_to_ordinal(timestamp) | Convert a timestamp as defined in the soap interface to the time format
stored in the database. | 3.465964 | 3.430847 | 1.010236 |
seasonal_key = config.get('DEFAULT', 'seasonal_key', '9999')
if seasonal:
FORMAT = seasonal_key+'-%m-%dT%H:%M:%S.%f'
else:
FORMAT = '%Y-%m-%dT%H:%M:%S.%f'
return date.strftime(FORMAT) | def date_to_string(date, seasonal=False) | 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... | 3.719341 | 3.530027 | 1.05363 |
#If a single timestamp is passed in, turn it into a list
#Reindexing can't work if it's not a list
if not isinstance(new_timestamps, list):
new_timestamps = [new_timestamps]
#Convert the incoming timestamps to datetimes
#if they are not datetimes.
new_timestamps_converted = []
... | def reindex_timeseries(ts_string, new_timestamps) | 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 | 3.398214 | 3.499457 | 0.971069 |
log.info("Parsing time step %s", time_step)
# export numerical value from string using regex
value = re.findall(r'\d+', time_step)[0]
valuelen = len(value)
try:
value = float(value)
except:
HydraPluginError("Unable to extract number of time steps (%s) from time step %s" % (... | def parse_time_step(time_step, target='s', units_ref=None) | Read in the time step and convert it to seconds. | 4.088029 | 4.039095 | 1.012115 |
#Do this import here to avoid a circular dependency
from ..lib import units
if time_axis is not None:
actual_dates_axis = []
for t in time_axis:
#If the user has entered the time_axis with commas, remove them.
t = t.replace(',', '').strip()
if t == ... | def get_time_axis(start_time, end_time, time_step, time_axis=None) | 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... | 3.047958 | 3.032231 | 1.005187 |
attrs = network.attributes
for n in network.nodes:
attrs.extend(n.attributes)
for l in network.links:
attrs.extend(l.attributes)
for g in network.resourcegroups:
attrs.extend(g.attributes)
return attrs | 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. | 3.071391 | 3.159142 | 0.972223 |
base_qry = db.DBSession.query(
ResourceType.ref_key.label('ref_key'),
ResourceType.node_id.label('node_id'),
ResourceType.link_id.label('link_id'),
ResourceType.group_id.label('group_id')... | def _get_all_templates(network_id, template_id) | 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. | 1.790263 | 1.776683 | 1.007643 |
base_qry = db.DBSession.query(ResourceGroupItem)
item_qry = base_qry.join(Scenario).filter(Scenario.network_id==network_id)
x = time.time()
logging.info("Getting all items")
all_items = db.DBSession.execute(item_qry.statement).fetchall()
log.info("%s groups jointly retrieved in %s", len(a... | 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 scenario_id | 3.337883 | 3.136656 | 1.064153 |
rs_qry = db.DBSession.query(
Dataset.type,
Dataset.unit_id,
Dataset.name,
Dataset.hash,
Dataset.cr_date,
Dataset.created_by,
Dataset.hidden,
Dataset.value,
ResourceSc... | 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 on scenario_id | 2.714769 | 2.723566 | 0.99677 |
log.info("Getting Metadata")
dataset_qry = db.DBSession.query(
Dataset
).outerjoin(DatasetOwner, and_(DatasetOwner.dataset_id==Dataset.id, DatasetOwner.user_id==user_id)).filter(
or_(Dataset.hidden=='N', DatasetOwner.user_id != None),
Scenario.id==Resourc... | 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 | 3.132519 | 3.005633 | 1.042216 |
owners_i = db.DBSession.query(NetworkOwner).filter(
NetworkOwner.network_id==network_id).options(noload('network')).options(joinedload_all('user')).all()
owners = [JSONObject(owner_i) for owner_i in owners_i]
return owners | def _get_network_owners(network_id) | Get all the nodes in a network | 5.517672 | 5.721325 | 0.964405 |
extras = {'types':[], 'attributes':[]}
node_qry = db.DBSession.query(Node).filter(
Node.network_id==network_id,
Node.status=='A').options(
noload('network')
)
if template_id is not None:
node_qr... | def _get_nodes(network_id, template_id=None) | Get all the nodes in a network | 4.004581 | 3.907252 | 1.02491 |
extras = {'types':[], 'attributes':[]}
link_qry = db.DBSession.query(Link).filter(
Link.network_id==network_id,
Link.status=='A').options(
noload('network')
... | def _get_links(network_id, template_id=None) | Get all the links in a network | 4.043318 | 3.932318 | 1.028228 |
extras = {'types':[], 'attributes':[]}
group_qry = db.DBSession.query(ResourceGroup).filter(
ResourceGroup.network_id==network_id,
ResourceGroup.status=='A').options(
noload('network'... | def _get_groups(network_id, template_id=None) | Get all the resource groups in a network | 3.948766 | 3.776001 | 1.045753 |
scen_qry = db.DBSession.query(Scenario).filter(
Scenario.network_id == network_id).options(
noload('network')).filter(
Scenario.status == 'A')
if scenario_ids:
logging.info("Filtering by scenario_ids %s",scenario_ids)
scen... | def _get_scenarios(network_id, include_data, user_id, scenario_ids=None) | Get all the scenarios in a network | 3.230157 | 3.22271 | 1.002311 |
log.debug("getting network %s"%network_id)
user_id = kwargs.get('user_id')
network_id = int(network_id)
try:
log.debug("Querying Network %s", network_id)
net_i = db.DBSession.query(Network).filter(
Network.id == network_id).options(
... | def get_network(network_id, summary=False, include_data='N', scenario_ids=None, template_id=None, **kwargs) | 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... | 2.183839 | 2.182818 | 1.000468 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.