code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
from scipy.stats import norm a = np.asarray(a) c = norm.ppf(3 / 4.) if normalize else 1 center = np.apply_over_axes(np.median, a, axis) return np.median((np.fabs(a - center)) / c, axis=axis)
def mad(a, normalize=True, axis=0)
Median Absolute Deviation along given axis of an array. Parameters ---------- a : array-like Input array. normalize : boolean. If True, scale by a normalization constant (~0.67) axis : int, optional The defaul is 0. Can also be None. Returns ------- mad : float ...
3.774945
5.209544
0.724621
from scipy.stats import chi2 a = np.asarray(a) k = np.sqrt(chi2.ppf(0.975, 1)) return (np.fabs(a - np.median(a)) / mad(a)) > k
def madmedianrule(a)
Outlier detection based on the MAD-median rule. Parameters ---------- a : array-like Input array. Returns ------- outliers: boolean (same shape as a) Boolean array indicating whether each sample is an outlier (True) or not (False). References ---------- .. ...
3.700927
5.426536
0.682005
from scipy.stats import mannwhitneyu x = np.asarray(x) y = np.asarray(y) # Remove NA x, y = remove_na(x, y, paired=False) # Compute test if tail == 'one-sided': tail = 'less' if np.median(x) < np.median(y) else 'greater' uval, pval = mannwhitneyu(x, y, use_continuity=True,...
def mwu(x, y, tail='two-sided')
Mann-Whitney U Test (= Wilcoxon rank-sum test). It is the non-parametric version of the independent T-test. Parameters ---------- x, y : array_like First and second set of observations. x and y must be independent. tail : string Specify whether to return 'one-sided' or 'two-sided' p...
3.675413
3.013802
1.219527
from scipy.stats import chi2, rankdata, tiecorrect # Check data _check_dataframe(dv=dv, between=between, data=data, effects='between') # Remove NaN values data = data.dropna() # Reset index (avoid duplicate axis error) data = data.reset_index(drop=True) # Ex...
def kruskal(dv=None, between=None, data=None, detailed=False, export_filename=None)
Kruskal-Wallis H-test for independent samples. Parameters ---------- dv : string Name of column containing the dependant variable. between : string Name of column containing the between factor. data : pandas DataFrame DataFrame export_filename : string Filename (...
3.844047
3.459535
1.111146
from scipy.stats import rankdata, chi2, find_repeats # Check data _check_dataframe(dv=dv, within=within, data=data, subject=subject, effects='within') # Collapse to the mean data = data.groupby([subject, within]).mean().reset_index() # Remove NaN if data[dv].isnu...
def friedman(dv=None, within=None, subject=None, data=None, export_filename=None)
Friedman test for repeated measurements. Parameters ---------- dv : string Name of column containing the dependant variable. within : string Name of column containing the within-subject factor. subject : string Name of column containing the subject identifier. data : pan...
3.63799
3.428509
1.0611
from scipy.stats import chi2 # Check data _check_dataframe(dv=dv, within=within, data=data, subject=subject, effects='within') # Remove NaN if data[dv].isnull().any(): data = remove_rm_na(dv=dv, within=within, subject=subject, data=data...
def cochran(dv=None, within=None, subject=None, data=None, export_filename=None)
Cochran Q test. Special case of the Friedman test when the dependant variable is binary. Parameters ---------- dv : string Name of column containing the binary dependant variable. within : string Name of column containing the within-subject factor. subject : string Name ...
3.915335
3.714557
1.054052
if not _isconvertible(float, string): return False elif isinstance(string, (_text_type, _binary_type)) and ( math.isinf(float(string)) or math.isnan(float(string))): return string.lower() in ['inf', '-inf', 'nan'] return True
def _isnumber(string)
>>> _isnumber("123.45") True >>> _isnumber("123") True >>> _isnumber("spam") False >>> _isnumber("123e45678") False >>> _isnumber("inf") True
3.808424
4.46587
0.852784
return isinstance(string, _bool_type) or\ (isinstance(string, (_binary_type, _text_type)) and string in ("True", "False"))
def _isbool(string)
>>> _isbool(True) True >>> _isbool("False") True >>> _isbool(1) False
5.27175
6.219698
0.847589
if has_invisible and \ (isinstance(string, _text_type) or isinstance(string, _binary_type)): string = _strip_invisible(string) if string is None: return _none_type elif hasattr(string, "isoformat"): # datetime.datetime, date, and time return _text_type elif _isbool...
def _type(string, has_invisible=True, numparse=True)
The least generic type (type(None), int, float, str, unicode). >>> _type(None) is type(None) True >>> _type("foo") is type("") True >>> _type("1") is type(1) True >>> _type('\x1b[31m42\x1b[0m') is type(42) True >>> _type('\x1b[31m42\x1b[0m') is type(42) True
2.660929
2.711758
0.981256
# optional wide-character support if wcwidth is not None and WIDE_CHARS_MODE: len_fn = wcwidth.wcswidth else: len_fn = len if isinstance(s, _text_type) or isinstance(s, _binary_type): return len_fn(_strip_invisible(s)) else: return len_fn(_text_type(s))
def _visible_width(s)
Visible width of a printed string. ANSI color codes are removed. >>> _visible_width('\x1b[31mhello\x1b[0m'), _visible_width("world") (5, 5)
4.50258
5.076517
0.886943
return max(map(line_width_fn, re.split("[\r\n]", multiline_s)))
def _multiline_width(multiline_s, line_width_fn=len)
Visible width of a potentially multiline content.
3.526792
3.623228
0.973384
if has_invisible: line_width_fn = _visible_width elif enable_widechars: # optional wide-character support if available line_width_fn = wcwidth.wcswidth else: line_width_fn = len if is_multiline: def width_fn(s): return _multiline_width(s, line_width_fn) else: ...
def _choose_width_fn(has_invisible, enable_widechars, is_multiline)
Return a function to calculate visible cell width.
2.791327
2.700332
1.033697
strings, padfn = _align_column_choose_padfn( strings, alignment, has_invisible) width_fn = _choose_width_fn(has_invisible, enable_widechars, is_multiline) s_widths = list(map(width_fn, strings)) maxwidth = max(max(s_widths), minwidth) # TODO: refactor column alignment in single-line an...
def _align_column(strings, alignment, minwidth=0, has_invisible=True, enable_widechars=False, is_multiline=False)
[string] -> [padded_string]
2.923502
2.878685
1.015569
types = [_type(s, has_invisible, numparse) for s in strings] return reduce(_more_generic, types, _bool_type)
def _column_type(strings, has_invisible=True, numparse=True)
The least generic type all column values are convertible to. >>> _column_type([True, False]) is _bool_type True >>> _column_type(["1", "2"]) is _int_type True >>> _column_type(["1", "2.3"]) is _float_type True >>> _column_type(["1", "2.3", "four"]) is _text_type True >>> _column_typ...
6.315858
8.598729
0.734511
"Pad string header to width chars given known visible_width of the header." if is_multiline: header_lines = re.split(_multiline_codes, header) padded_lines = [_align_header(h, alignment, width, width_fn(h)) for h in header_lines] return "\n".join(padded_lines) ...
def _align_header(header, alignment, width, visible_width, is_multiline=False, width_fn=None)
Pad string header to width chars given known visible_width of the header.
4.585926
3.345514
1.370769
if index is None or index is False: return rows if len(index) != len(rows): print('index=', index) print('rows=', rows) raise ValueError('index must be as long as the number of data rows') rows = [[v] + list(row) for v, row in zip(index, rows)] return rows
def _prepend_row_index(rows, index)
Add a left-most index column.
3.466048
3.338651
1.038158
if isinstance(disable_numparse, Iterable): numparses = [True] * column_count for index in disable_numparse: numparses[index] = False return numparses else: return [not disable_numparse] * column_count
def _expand_numparse(disable_numparse, column_count)
Return a list of bools of length `column_count` which indicates whether number parsing should be used on each column. If `disable_numparse` is a list of indices, each of those indices are False, and everything else is True. If `disable_numparse` is a bool, then the returned list is all the same.
2.288369
2.273346
1.006608
alpha = np.array(alpha) return np.remainder(alpha * n, 2 * np.pi)
def circ_axial(alpha, n)
Transforms n-axial data to a common scale. Parameters ---------- alpha : array Sample of angles in radians n : int Number of modes Returns ------- alpha : float Transformed angles Notes ----- Tranform data with multiple modes (known as axial data) to a ...
4.331222
12.450227
0.347883
from scipy.stats import norm x = np.asarray(x) y = np.asarray(y) # Check size if x.size != y.size: raise ValueError('x and y must have the same length.') # Remove NA x, y = remove_na(x, y, paired=True) n = x.size # Compute correlation coefficient x_sin = np.sin(x ...
def circ_corrcc(x, y, tail='two-sided')
Correlation coefficient between two circular variables. Parameters ---------- x : np.array First circular variable (expressed in radians) y : np.array Second circular variable (expressed in radians) tail : string Specify whether to return 'one-sided' or 'two-sided' p-value. ...
2.946789
3.043482
0.96823
from scipy.stats import pearsonr, chi2 x = np.asarray(x) y = np.asarray(y) # Check size if x.size != y.size: raise ValueError('x and y must have the same length.') # Remove NA x, y = remove_na(x, y, paired=True) n = x.size # Compute correlation coefficent for sin and ...
def circ_corrcl(x, y, tail='two-sided')
Correlation coefficient between one circular and one linear variable random variables. Parameters ---------- x : np.array First circular variable (expressed in radians) y : np.array Second circular variable (linear) tail : string Specify whether to return 'one-sided' or ...
2.989195
3.133785
0.953861
alpha = np.array(alpha) if isinstance(w, (list, np.ndarray)): w = np.array(w) if alpha.shape != w.shape: raise ValueError("w must have the same shape as alpha.") else: w = np.ones_like(alpha) return np.angle(np.multiply(w, np.exp(1j * alpha)).sum(axis=axis))
def circ_mean(alpha, w=None, axis=0)
Mean direction for circular data. Parameters ---------- alpha : array Sample of angles in radians w : array Number of incidences in case of binned angle data axis : int Compute along this dimension Returns ------- mu : float Mean direction Examples ...
2.226115
3.066468
0.725954
alpha = np.array(alpha) w = np.array(w) if w is not None else np.ones(alpha.shape) if alpha.size is not w.size: raise ValueError("Input dimensions do not match") # Compute weighted sum of cos and sin of angles: r = np.multiply(w, np.exp(1j * alpha)).sum(axis=axis) # Obtain length:...
def circ_r(alpha, w=None, d=None, axis=0)
Mean resultant vector length for circular data. Parameters ---------- alpha : array Sample of angles in radians w : array Number of incidences in case of binned angle data d : float Spacing (in radians) of bin centers for binned data. If supplied, a correction factor...
3.899105
4.748212
0.821173
alpha = np.array(alpha) if w is None: r = circ_r(alpha) n = len(alpha) else: if len(alpha) is not len(w): raise ValueError("Input dimensions do not match") r = circ_r(alpha, w, d) n = np.sum(w) # Compute Rayleigh's statistic R = n * r z =...
def circ_rayleigh(alpha, w=None, d=None)
Rayleigh test for non-uniformity of circular data. Parameters ---------- alpha : np.array Sample of angles in radians. w : np.array Number of incidences in case of binned angle data. d : float Spacing (in radians) of bin centers for binned data. If supplied, a correc...
4.608276
4.965706
0.92802
pvals = np.asarray(pvals) num_nan = np.isnan(pvals).sum() pvals_corrected = pvals * (float(pvals.size) - num_nan) pvals_corrected = np.clip(pvals_corrected, None, 1) with np.errstate(invalid='ignore'): reject = np.less(pvals_corrected, alpha) return reject, pvals_corrected
def bonf(pvals, alpha=0.05)
P-values correction with Bonferroni method. Parameters ---------- pvals : array_like Array of p-values of the individual tests. alpha : float Error rate (= alpha level). Returns ------- reject : array, bool True if a hypothesis is rejected, False if not pval_cor...
2.859871
3.222886
0.887363
# Convert to array and save original shape pvals = np.asarray(pvals) shape_init = pvals.shape pvals = pvals.ravel() num_nan = np.isnan(pvals).sum() # Sort the (flattened) p-values pvals_sortind = np.argsort(pvals) pvals_sorted = pvals[pvals_sortind] sortrevind = pvals_sortind.a...
def holm(pvals, alpha=.05)
P-values correction with Holm method. Parameters ---------- pvals : array_like Array of p-values of the individual tests. alpha : float Error rate (= alpha level). Returns ------- reject : array, bool True if a hypothesis is rejected, False if not pvals_correcte...
3.086741
3.187692
0.968331
from pingouin import anova # Check dataframe if any(v is None for v in [data, groups, raters, scores]): raise ValueError('Data, groups, raters and scores must be specified') assert isinstance(data, pd.DataFrame), 'Data must be a pandas dataframe.' # Check that scores is a numeric varia...
def intraclass_corr(data=None, groups=None, raters=None, scores=None, ci=.95)
Intra-class correlation coefficient. Parameters ---------- data : pd.DataFrame Dataframe containing the variables groups : string Name of column in data containing the groups. raters : string Name of column in data containing the raters (scorers). scores : string ...
3.029181
3.12096
0.970592
# eq. 2.3 f = a[0]*math.log(r-1.) + \ a[1]*math.log(r-1.)**2 + \ a[2]*math.log(r-1.)**3 + \ a[3]*math.log(r-1.)**4 # eq. 2.7 and 2.8 corrections if r == 3: f += -0.002 / (1. + 12. * _phi(p)**2) if v <= 4.364: f += 1./517. - 1./(312.*(v,1e38)[np....
def _func(a, p, r, v)
calculates f-hat for the coefficients in a, probability p, sample mean difference r, and degrees of freedom v.
4.707823
4.664648
1.009256
# There are more generic ways of doing this but profiling # revealed that selecting these points is one of the slow # things that is easy to change. This is about 11 times # faster than the generic algorithm it is replacing. # # it is possible that different break points could yield # better...
def _select_ps(p)
returns the points to use for interpolating p
3.265475
3.192173
1.022963
# This one is is about 30 times faster than # the generic algorithm it is replacing. if v >= 120.: return 60, 120, inf elif v >= 60.: return 40, 60, 120 elif v >= 40.: return 30, 40, 60 elif v >= 30.: return 24, 30, 40 elif v >= 24.: return 20, 2...
def _select_vs(v, p)
returns the points to use for interpolating v
3.10561
3.155258
0.984265
# interpolate v (p should be in table) # ordinate: y**2 # abcissa: 1./v # find the 3 closest v values # only p >= .9 have table values for 1 degree of freedom. # The boolean is used to index the tuple and append 1 when # p >= .9 v0, v1, v2 = _select_vs(v, p) # y = f - 1. ...
def _interpolate_v(p, r, v)
interpolates v based on the values in the A table for the scalar value of r and th
4.141158
4.200194
0.985945
## print 'q',p # r is interpolated through the q to y here we only need to # account for when p and/or v are not found in the table. global A, p_keys, v_keys if p < .1 or p > .999: raise ValueError('p must be between .1 and .999') if p < .9: if v < 2: raise Valu...
def _qsturng(p, r, v)
scalar version of qsturng
3.828829
3.862076
0.991391
if all(map(_isfloat, [p, r, v])): return _qsturng(p, r, v) return _vqsturng(p, r, v)
def qsturng(p, r, v)
Approximates the quantile p for a studentized range distribution having v degrees of freedom and r samples for probability p. Parameters ---------- p : (scalar, array_like) The cumulative probability value p >= .1 and p <=.999 (values under .5 are not recommended) ...
4.22055
5.961322
0.707989
if q < 0.: raise ValueError('q should be >= 0') opt_func = lambda p, r, v : abs(_qsturng(p, r, v) - q) if v == 1: if q < _qsturng(.9, r, 1): return .1 elif q > _qsturng(.999, r, 1): return .001 return 1. - fminbound(opt_func, .9, .999, args=(r,v...
def _psturng(q, r, v)
scalar version of psturng
2.587962
2.603131
0.994173
if all(map(_isfloat, [q, r, v])): return _psturng(q, r, v) return _vpsturng(q, r, v)
def psturng(q, r, v)
Evaluates the probability from 0 to q for a studentized range having v degrees of freedom and r samples. Parameters ---------- q : (scalar, array_like) quantile value of Studentized Range q >= 0. r : (scalar, array_like) The number of samples r >= 2 and r <= 200 ...
4.242949
7.722878
0.5494
if self._consumer_fn is not None: raise ValueError('Consumer function is already defined for this ' 'Stream instance') if not any([asyncio.iscoroutine(fn), asyncio.iscoroutinefunction(fn)]): raise ValueError('Consumer function must be a corou...
def consumer(self, fn)
Consumer decorator :param fn: coroutine consumer function Example: >>> api = StreamingAPI('my_service_key') >>> stream = api.get_stream() >>> @stream.consumer >>> @asyncio.coroutine >>> def handle_event(payload): >>> print(payload)
3.60603
3.701343
0.974249
if self._consumer_fn is None: raise ValueError('Consumer function is not defined yet') logger.info('Start consuming the stream') @asyncio.coroutine def worker(conn_url): extra_headers = { 'Connection': 'upgrade', 'Upgrade...
def consume(self, timeout=None, loop=None)
Start consuming the stream :param timeout: int: if it's given then it stops consumer after given number of seconds
2.492908
2.49255
1.000143
resp = requests.post(url=self.REQUEST_URL.format(**self._params), json={'rule': {'value': value, 'tag': tag}}) return resp.json()
def add_rule(self, value, tag)
Add a new rule :param value: str :param tag: str :return: dict of a json response
5.431916
5.405386
1.004908
resp = requests.delete(url=self.REQUEST_URL.format(**self._params), json={'tag': tag}) return resp.json()
def remove_rule(self, tag)
Remove a rule by tag
7.831454
7.610659
1.029011
if not isinstance(data, dict): raise ValueError('Data must be dict. %r is passed' % data) values_dict = {} for key, value in data.items(): items = [] if isinstance(value, six.string_types): items.append(value) elif isinstance(value, Iterable): fo...
def stringify_values(data)
Coerce iterable values to 'val1,val2,valN' Example: fields=['nickname', 'city', 'can_see_all_posts'] --> fields='nickname,city,can_see_all_posts' :param data: dict :return: converted values dict
2.836832
2.831727
1.001803
parsed_url = urlparse(url) if fragment: url_query = parse_qsl(parsed_url.fragment) else: url_query = parse_qsl(parsed_url.query) # login_response_url_query can have multiple key url_query = dict(url_query) return url_query
def parse_url_query_params(url, fragment=True)
Parse url query params :param fragment: bool: flag is used for parsing oauth url :param url: str: url string :return: dict
3.225599
3.519151
0.916584
if parser is None: parser = bs4.BeautifulSoup(html, 'html.parser') forms = parser.find_all('form') if not forms: raise VkParseError('Action form is not found in the html \n%s' % html) if len(forms) > 1: raise VkParseError('Find more than 1 forms to handle:\n%s', forms) ...
def parse_form_action_url(html, parser=None)
Parse <form action="(.+)"> url :param html: str: raw html text :param parser: bs4.BeautifulSoup: html parser :return: url str: for example: /login.php?act=security_check&to=&hash=12346
3.412153
3.502926
0.974086
if parser is None: parser = bs4.BeautifulSoup(html, 'html.parser') fields = parser.find_all('span', {'class': 'field_prefix'}) if not fields: raise VkParseError( 'No <span class="field_prefix">...</span> in the \n%s' % html) result = [] for f in fields: val...
def parse_masked_phone_number(html, parser=None)
Get masked phone number from security check html :param html: str: raw html text :param parser: bs4.BeautifulSoup: html parser :return: tuple of phone prefix and suffix, for example: ('+1234', '89') :rtype : tuple
3.416479
3.375423
1.012163
if parser is None: parser = bs4.BeautifulSoup(html, 'html.parser') # Check warnings warnings = parser.find_all('div', {'class': 'service_msg_warning'}) if warnings: raise VkPageWarningsError('; '.join([w.get_text() for w in warnings])) return True
def check_html_warnings(html, parser=None)
Check html warnings :param html: str: raw html text :param parser: bs4.BeautifulSoup: html parser :raise VkPageWarningsError: in case of found warnings
4.057122
2.866462
1.415376
if self._http_session is None: session = VerboseHTTPSession() session.headers.update(self.DEFAULT_HTTP_HEADERS) self._http_session = session return self._http_session
def http_session(self)
HTTP Session property :return: vk_requests.utils.VerboseHTTPSession instance
3.594725
2.652027
1.355463
response = http_session.get(self.LOGIN_URL) action_url = parse_form_action_url(response.text) # Stop login it action url is not found if not action_url: logger.debug(response.text) raise VkParseError("Can't parse form action url") login_form_da...
def do_login(self, http_session)
Do vk login :param http_session: vk_requests.utils.VerboseHTTPSession: http session
3.286106
3.211532
1.023221
logger.info('Doing implicit flow authorization, app_id=%s', self.app_id) auth_data = { 'client_id': self.app_id, 'display': 'mobile', 'response_type': 'token', 'scope': self.scope, 'redirect_uri': 'https://oauth.vk.com/blank.html', ...
def do_implicit_flow_authorization(self, session)
Standard OAuth2 authorization method. It's used for getting access token More info: https://vk.com/dev/implicit_flow_user
2.930217
2.760979
1.061296
logger.info('Doing direct authorization, app_id=%s', self.app_id) auth_data = { 'client_id': self.app_id, 'client_secret': self._client_secret, 'username': self._login, 'password': self._password, 'grant_type': 'password', ...
def do_direct_authorization(self, session)
Direct Authorization, more info: https://vk.com/dev/auth_direct
2.810893
2.547714
1.1033
logger.info('Captcha is needed. Query params: %s', query_params) form_text = response.text action_url = parse_form_action_url(form_text) logger.debug('form action url: %s', action_url) if not action_url: raise VkAuthError('Cannot find form action url') ...
def require_auth_captcha(self, response, query_params, login_form_data, http_session)
Resolve auth captcha case :param response: http response :param query_params: dict: response query params, for example: {'s': '0', 'email': 'my@email', 'dif': '1', 'role': 'fast', 'sid': '1'} :param login_form_data: dict :param http_session: requests.Session :return: :r...
2.61096
2.561393
1.019352
if self._service_token: logger.info('Use service token: %s', 5 * '*' + self._service_token[50:]) return self._service_token if not all([self.app_id, self._login, self._password]): raise ValueError( 'app_id=%s, login=%s...
def _get_access_token(self)
Get access token using app_id, login and password OR service token (service token docs: https://vk.com/dev/service_token
3.691658
3.2966
1.119838
if self.interactive: print('Open CAPTCHA image url in your browser and enter it below: ', captcha_image_url) captcha_key = raw_input('Enter CAPTCHA key: ') return captcha_key else: raise VkAuthError( 'Captcha is ...
def get_captcha_key(self, captcha_image_url)
Read CAPTCHA key from user input
5.421278
4.923237
1.101161
logger.debug('Prepare API Method request %r', request) response = self._send_api_request(request=request, captcha_response=captcha_response) response.raise_for_status() response_or_error = json.loads(response.text) logger.debug('...
def make_request(self, request, captcha_response=None)
Make api request helper function :param request: vk_requests.api.Request instance :param captcha_response: None or dict, e.g {'sid': <sid>, 'key': <key>} :return: dict: json decoded http response
2.970418
2.868356
1.035582
url = self.API_URL + request.method_name # Prepare request arguments method_kwargs = {'v': self.api_version} # Shape up the request data for values in (request.method_args,): method_kwargs.update(stringify_values(values)) if self.is_token_required(...
def _send_api_request(self, request, captcha_response=None)
Prepare and send HTTP API request :param request: vk_requests.api.Request instance :param captcha_response: None or dict :return: HTTP response
4.520301
4.148309
1.089673
session = VKSession(app_id=app_id, user_login=login, user_password=password, phone_number=phone_number, scope=scope, service_token=service_token, api_version=api_versi...
def create_api(app_id=None, login=None, password=None, phone_number=None, scope='offline', api_version='5.92', http_params=None, interactive=False, service_token=None, client_secret=None, two_fa_supported=False, two_fa_force_sms=False)
Factory method to explicitly create API with app_id, login, password and phone_number parameters. If the app_id, login, password are not passed, then token-free session will be created automatically :param app_id: int: vk application id, more info: https://vk.com/dev/main :param login: str: vk log...
1.78163
1.947158
0.91499
if self._process_result: self._result = self._process_result(value) self._raw_result = value
def result(self, value)
The result of the command.
5.998717
5.87366
1.021291
path = '/'.join(str(v) for v in self._path) return 'coaps://{}:5684/{}'.format(host, path)
def url(self, host)
Generate url for coap client.
4.941291
3.46072
1.427822
for k, v in a.items(): if isinstance(v, dict): item = b.setdefault(k, {}) self._merge(v, item) elif isinstance(v, list): item = b.setdefault(k, [{}]) if len(v) == 1 and isinstance(v[0], dict): se...
def _merge(self, a, b)
Merges a into b.
1.811612
1.74703
1.036967
if command2 is None: return self._data = self._merge(command2._data, self._data)
def combine_data(self, command2)
Combines the data for this command with another.
5.635996
4.370011
1.289698
try: with open(filename, encoding='utf-8') as fdesc: return json.loads(fdesc.read()) except FileNotFoundError: # This is not a fatal error _LOGGER.debug('JSON file not found: %s', filename) except ValueError as error: _LOGGER.exception('Could not parse JSON c...
def load_json(filename: str) -> Union[List, Dict]
Load JSON data from a file and return as dict or list. Defaults to returning empty dict if file is not found.
2.730969
2.80824
0.972484
try: data = json.dumps(config, sort_keys=True, indent=4) with open(filename, 'w', encoding='utf-8') as fdesc: fdesc.write(data) return True except TypeError as error: _LOGGER.exception('Failed to serialize to JSON: %s', filename) ...
def save_json(filename: str, config: Union[List, Dict])
Save JSON data to a file. Returns True on success.
2.788369
2.631617
1.059565
return [k for k, b in self._lookup.items() if b & selection]
def get_selected_keys(self, selection)
Return a list of keys for the given selection.
8.932598
6.595808
1.354284
return [v for b, v in self._choices if b & selection]
def get_selected_values(self, selection)
Return a list of values for the given selection.
14.955264
11.215895
1.333399
output = output.strip() _LOGGER.debug('Received: %s', output) if not output: return None elif 'decrypt_verify' in output: raise RequestError( 'Please compile coap-client without debug output. See ' 'instructions at ' 'https://github.com/ggravlin...
def _process_output(output, parse_json=True)
Process output.
5.036912
4.874663
1.033284
@wraps(api) def retry_api(*args, **kwargs): for i in range(1, retries + 1): try: return api(*args, **kwargs) except RequestTimeout: if i == retries: raise return retry_api
def retry_timeout(api, retries=3)
Retry API call when a timeout occurs.
2.452056
2.263923
1.0831
if api_command.observe: self._observe(api_command) return method = api_command.method path = api_command.path data = api_command.data parse_json = api_command.parse_json url = api_command.url(self._host) proc_timeout = self._tim...
def _execute(self, api_command, *, timeout=None)
Execute the command.
2.578862
2.525974
1.020938
if not isinstance(api_commands, list): return self._execute(api_commands, timeout=timeout) command_results = [] for api_command in api_commands: result = self._execute(api_command, timeout=timeout) command_results.append(result) return comm...
def request(self, api_commands, *, timeout=None)
Make a request. Timeout is in seconds.
2.22601
2.083992
1.068147
path = api_command.path duration = api_command.observe_duration if duration <= 0: raise ValueError("Observation duration has to be greater than 0.") url = api_command.url(self._host) err_callback = api_command.err_callback command = (self._base_comma...
def _observe(self, api_command)
Observe an endpoint.
3.511969
3.414367
1.028586
if not self._psk: # Backup the real identity. existing_psk_id = self._psk_id # Set the default identity and security key for generation. self._psk_id = 'Client_identity' self._psk = security_key # Ask the Gateway to generate the ...
def generate_psk(self, security_key)
Generate and set a psk from the security key.
4.508446
4.34705
1.037128
return datetime.time( self.task_start_parameters[ ATTR_SMART_TASK_TRIGGER_TIME_START_HOUR], self.task_start_parameters[ ATTR_SMART_TASK_TRIGGER_TIME_START_MIN])
def task_start_time(self)
Return the time the task starts. Time is set according to iso8601.
5.035065
4.949285
1.017332
return TaskControl( self, self.state, self.path, self._gateway)
def task_control(self)
Method to control a task.
17.442301
15.421797
1.131016
return [StartActionItem( self._task, i, self.state, self.path, self.raw) for i in range(len(self.raw))]
def tasks(self)
Return task objects of the task control.
11.722322
10.533955
1.112813
# This is to calculate the difference between local time # and the time in the gateway d1 = self._gateway.get_gateway_info().current_time d2 = dt.utcnow() diff = d1 - d2 newtime = dt(100, 1, 1, hour, minute, 00) - diff command = { ATTR_SMAR...
def set_dimmer_start_time(self, hour, minute)
Set start time for task (hh:mm) in iso8601. NB: dimmer starts 30 mins before time in app
4.753451
4.765817
0.997405
return [StartActionItem( self.start_action, i, self.state, self.path, self.raw) for i in range( len(self.raw[ROOT_START_ACTION]))]
def devices(self)
Return state of start action task.
11.430624
7.929393
1.441551
json_list = {} z = 0 for x in self._raw[ROOT_START_ACTION]: if z != self.index: json_list.update(x) z = z + 1 return json_list
def devices_dict(self)
Return state of start action task.
8.759686
6.782763
1.291463
return StartActionItemController( self, self.raw, self.state, self.path, self.devices_dict)
def item_controller(self)
Method to control a task.
18.329113
16.329796
1.122434
command = { ATTR_START_ACTION: { ATTR_DEVICE_STATE: self.state, ROOT_START_ACTION: [{ ATTR_ID: self.raw[ATTR_ID], ATTR_LIGHT_DIMMER: dimmer, ATTR_TRANSITION_TIME: self.raw[ATTR_TR...
def set_dimmer(self, dimmer)
Set final dimmer value for task.
6.041952
5.868448
1.029566
command = { ATTR_START_ACTION: { ATTR_DEVICE_STATE: self.state, ROOT_START_ACTION: [{ ATTR_ID: self.raw[ATTR_ID], ATTR_LIGHT_DIMMER: self.raw[ATTR_LIGHT_DIMMER], ATTR_TRANSITION_T...
def set_transition_time(self, transition_time)
Set time (mins) for light transition.
6.247237
5.684238
1.099046
def observe_callback(value): self.raw = value callback(self) return Command('get', self.path, process_result=observe_callback, err_callback=err_callback, observe=True, observe_duration=dur...
def observe(self, callback, err_callback, duration=60)
Observe resource and call callback when updated.
6.80237
6.123836
1.110802
def process_result(result): self.raw = result return Command('get', self.path, process_result=process_result)
def update(self)
Update the group. Returns a Command.
10.080923
9.733917
1.035649
def process_result(result): return result[ATTR_PSK] return Command('post', [ROOT_GATEWAY, ATTR_AUTH], { ATTR_IDENTITY: identity }, process_result=process_result)
def generate_psk(self, identity)
Generates the PRE_SHARED_KEY from the gateway. Returns a Command.
12.611272
9.796833
1.28728
def process_result(result): return [line.split(';')[0][2:-1] for line in result.split(',')] return Command('get', ['.well-known', 'core'], parse_json=False, process_result=process_result)
def get_endpoints(self)
Return all available endpoints on the gateway. Returns a Command.
8.277596
7.319159
1.130949
def process_result(result): return [self.get_device(dev) for dev in result] return Command('get', [ROOT_DEVICES], process_result=process_result)
def get_devices(self)
Return the devices linked to the gateway. Returns a Command.
8.475373
7.646162
1.108448
def process_result(result): return Device(result) return Command('get', [ROOT_DEVICES, device_id], process_result=process_result)
def get_device(self, device_id)
Return specified device. Returns a Command.
10.300258
9.698241
1.062075
def process_result(result): return [self.get_group(group) for group in result] return Command('get', [ROOT_GROUPS], process_result=process_result)
def get_groups(self)
Return the groups linked to the gateway. Returns a Command.
8.620298
7.584568
1.136558
def process_result(result): return Group(self, result) return Command('get', [ROOT_GROUPS, group_id], process_result=process_result)
def get_group(self, group_id)
Return specified group. Returns a Command.
9.293819
9.567601
0.971384
def process_result(result): return GatewayInfo(result) return Command('get', [ROOT_GATEWAY, ATTR_GATEWAY_INFO], process_result=process_result)
def get_gateway_info(self)
Return the gateway info. Returns a Command.
11.398709
9.516211
1.19782
mood_parent = self._get_mood_parent() def process_result(result): return [self.get_mood(mood, mood_parent=mood_parent) for mood in result] return Command('get', [ROOT_MOODS, mood_parent], process_result=process_result)
def get_moods(self)
Return moods defined on the gateway. Returns a Command.
5.708956
5.086179
1.122445
if mood_parent is None: mood_parent = self._get_mood_parent() def process_result(result): return Mood(result, mood_parent) return Command('get', [ROOT_MOODS, mood_parent, mood_id], mood_parent, process_result=process_result)
def get_mood(self, mood_id, *, mood_parent=None)
Return a mood. Returns a Command.
4.269593
3.934708
1.085111
def process_result(result): return [self.get_smart_task(task) for task in result] return Command('get', [ROOT_SMART_TASKS], process_result=process_result)
def get_smart_tasks(self)
Return the transitions linked to the gateway. Returns a Command.
7.285981
6.87191
1.060256
def process_result(result): return SmartTask(self, result) return Command('get', [ROOT_SMART_TASKS, task_id], process_result=process_result)
def get_smart_task(self, task_id)
Return specified transition. Returns a Command.
8.039356
8.277949
0.971177
if ATTR_FIRST_SETUP not in self.raw: return None return datetime.utcfromtimestamp(self.raw[ATTR_FIRST_SETUP])
def first_setup(self)
This is a guess of the meaning of this value.
5.068933
4.001746
1.26668
if DeviceInfo.ATTR_POWER_SOURCE not in self.raw: return None return DeviceInfo.VALUE_POWER_SOURCES.get(self.power_source, 'Unknown')
def power_source_str(self)
String representation of current power source.
7.028918
6.134669
1.14577
return [Light(self._device, i) for i in range(len(self.raw))]
def lights(self)
Return light objects of the light control.
9.83152
7.199836
1.36552
return self.set_values({ ATTR_DEVICE_STATE: int(state) }, index=index)
def set_state(self, state, *, index=0)
Set state of a light.
8.374441
6.743827
1.241794
self._value_validate(dimmer, RANGE_BRIGHTNESS, "Dimmer") values = { ATTR_LIGHT_DIMMER: dimmer } if transition_time is not None: values[ATTR_TRANSITION_TIME] = transition_time return self.set_values(values, index=index)
def set_dimmer(self, dimmer, *, index=0, transition_time=None)
Set dimmer value of a light. transition_time: Integer representing tenth of a second (default None)
3.459108
3.459369
0.999925
self._value_validate(color_temp, RANGE_MIREDS, "Color temperature") values = { ATTR_LIGHT_MIREDS: color_temp } if transition_time is not None: values[ATTR_TRANSITION_TIME] = transition_time return self.set_values(values, index=index)
def set_color_temp(self, color_temp, *, index=0, transition_time=None)
Set color temp a light.
3.85257
3.572184
1.078492
values = { ATTR_LIGHT_COLOR_HEX: color, } if transition_time is not None: values[ATTR_TRANSITION_TIME] = transition_time return self.set_values(values, index=index)
def set_hex_color(self, color, *, index=0, transition_time=None)
Set hex color of the light.
3.018871
2.66609
1.132322
self._value_validate(color_x, RANGE_X, "X color") self._value_validate(color_y, RANGE_Y, "Y color") values = { ATTR_LIGHT_COLOR_X: color_x, ATTR_LIGHT_COLOR_Y: color_y } if transition_time is not None: values[ATTR_TRANSITION_TIME] = ...
def set_xy_color(self, color_x, color_y, *, index=0, transition_time=None)
Set xy color of the light.
2.435217
2.252311
1.081208
self._value_validate(hue, RANGE_HUE, "Hue") self._value_validate(saturation, RANGE_SATURATION, "Saturation") values = { ATTR_LIGHT_COLOR_SATURATION: saturation, ATTR_LIGHT_COLOR_HUE: hue } if brightness is not None: values[ATTR_LIGHT...
def set_hsb(self, hue, saturation, brightness=None, *, index=0, transition_time=None)
Set HSB color settings of the light.
2.218825
2.104539
1.054304
if value is not None and (value < rnge[0] or value > rnge[1]): raise ValueError('%s value must be between %d and %d.' % (identifier, rnge[0], rnge[1]))
def _value_validate(self, value, rnge, identifier="Given")
Make sure a value is within a given range
2.343742
2.249189
1.042039
assert len(self.raw) == 1, \ 'Only devices with 1 light supported' return Command('put', self._device.path, { ATTR_LIGHT_CONTROL: [ values ] })
def set_values(self, values, *, index=0)
Set values on light control. Returns a Command.
17.206543
11.059608
1.5558