index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
51,983
etatime.eta
EtaBar
null
class EtaBar(tqdm): def __init__( self, *args, bar_format: str = "{l_bar}{bar}{r_barS}", **kwargs): if "bar_format" in kwargs: del kwargs["bar_format"] bar_format = bar_format.format_map(SafeDict( r_barS="| {n_fmt}/{total_fmt} | {remainingS} | {etaS}", r_barL="| {n_fmt}/{total_fmt} | {remainingL} | {etaL}", )) self.stats = EtaStats() super().__init__(*args, bar_format=bar_format, **kwargs) self.stats.start_time = self.start_t @property def format_dict(self): d = super().format_dict # Extract useful information from the tqdm progress bar self.stats.initial = d["initial"] self.stats.n = d["n"] self.stats.total_items = d["total"] self.stats.elapsed_time = d["elapsed"] self.stats.current_time = self.stats.start_time + self.stats.elapsed_time if self.stats.start_time else None self.stats.rate = d["rate"] if self.stats.rate is None and self.stats.elapsed_time: self.stats.rate = (self.stats.n - self.stats.initial) / self.stats.elapsed_time # Compute some values based on the tqdm source code self.stats.remaining_time = (self.stats.total_items - self.stats.n) / self.stats.rate if ( self.stats.rate and self.stats.total_items) else None # Compute the ETA self.stats.eta_time = self.stats.current_time + self.stats.remaining_time if ( self.stats.remaining_time and self.stats.current_time) else None # Get the percent self.stats.percent = self.stats.n / self.stats.total_items if self.stats.total_items else None # Get the datetime objects self.stats.start_datetime = datetime.datetime.fromtimestamp(self.stats.start_time) if ( self.stats.start_time) else None self.stats.current_datetime = datetime.datetime.fromtimestamp(self.stats.current_time) if ( self.stats.current_time) else None self.stats.elapsed_timedelta = datetime.timedelta(seconds=self.stats.elapsed_time) if ( self.stats.elapsed_time) else None self.stats.remaining_timedelta = datetime.timedelta(seconds=self.stats.remaining_time) if ( self.stats.remaining_time) else None self.stats.eta_datetime = datetime.datetime.fromtimestamp(self.stats.eta_time) if ( self.stats.eta_time) else None # Add custom format codes start_string = timefmt.dt.short(self.stats.start_datetime) if ( self.stats.start_datetime) else EtaDefaults.low_data_string start_string = f"S: {start_string}" d.update(startS=start_string) start_long_string = timefmt.dt.long(self.stats.start_datetime) if ( self.stats.start_datetime) else EtaDefaults.low_data_string start_long_string = f"S: {start_long_string}" d.update(startL=start_long_string) current_string = timefmt.dt.short(self.stats.current_datetime) if ( self.stats.current_datetime) else EtaDefaults.low_data_string current_string = f"C: {current_string}" d.update(currentS=current_string) current_long_string = timefmt.dt.long(self.stats.current_datetime) if ( self.stats.current_datetime) else EtaDefaults.low_data_string current_long_string = f"C: {current_long_string}" d.update(currentL=current_long_string) elapsed_string = timefmt.td.short(self.stats.elapsed_timedelta) if ( self.stats.elapsed_timedelta) else EtaDefaults.low_data_string elapsed_string = f"E: {elapsed_string}" d.update(elapsedS=elapsed_string) elapsed_long_string = timefmt.td.long(self.stats.elapsed_timedelta) if ( self.stats.elapsed_timedelta) else EtaDefaults.low_data_string elapsed_long_string = f"E: {elapsed_long_string}" d.update(elapsedL=elapsed_long_string) remaining_string = timefmt.td.short(self.stats.remaining_timedelta) if ( self.stats.remaining_timedelta) else EtaDefaults.low_data_string remaining_string = f"R: {remaining_string}" d.update(remainingS=remaining_string) remaining_long_string = timefmt.td.long(self.stats.remaining_timedelta) if ( self.stats.remaining_timedelta) else EtaDefaults.low_data_string remaining_long_string = f"R: {remaining_long_string}" d.update(remainingL=remaining_long_string) eta_string = timefmt.dt.short(self.stats.eta_datetime) if ( self.stats.eta_datetime) else EtaDefaults.low_data_string eta_string = f"ETA: {eta_string}" d.update(etaS=eta_string) eta_long_string = timefmt.dt.long(self.stats.eta_datetime) if ( self.stats.eta_datetime) else EtaDefaults.low_data_string eta_long_string = f"ETA: {eta_long_string}" d.update(etaL=eta_long_string) return d
(*args, bar_format: str = '{l_bar}{bar}{r_barS}', **kwargs)
51,984
tqdm.std
__bool__
null
def __bool__(self): if self.total is not None: return self.total > 0 if self.iterable is None: raise TypeError('bool() undefined when iterable == total == None') return bool(self.iterable)
(self)
51,985
tqdm.std
__contains__
null
def __contains__(self, item): contains = getattr(self.iterable, '__contains__', None) return contains(item) if contains is not None else item in self.__iter__()
(self, item)
51,988
tqdm.utils
__eq__
null
def __eq__(self, other): return self._comparable == other._comparable
(self, other)
51,989
tqdm.std
__exit__
null
def __exit__(self, exc_type, exc_value, traceback): try: self.close() except AttributeError: # maybe eager thread cleanup upon external error if (exc_type, exc_value, traceback) == (None, None, None): raise warn("AttributeError ignored", TqdmWarning, stacklevel=2)
(self, exc_type, exc_value, traceback)
51,991
tqdm.utils
__gt__
null
def __gt__(self, other): return not self <= other
(self, other)
51,993
etatime.eta
__init__
null
def __init__( self, *args, bar_format: str = "{l_bar}{bar}{r_barS}", **kwargs): if "bar_format" in kwargs: del kwargs["bar_format"] bar_format = bar_format.format_map(SafeDict( r_barS="| {n_fmt}/{total_fmt} | {remainingS} | {etaS}", r_barL="| {n_fmt}/{total_fmt} | {remainingL} | {etaL}", )) self.stats = EtaStats() super().__init__(*args, bar_format=bar_format, **kwargs) self.stats.start_time = self.start_t
(self, *args, bar_format: str = '{l_bar}{bar}{r_barS}', **kwargs)
51,994
tqdm.std
__iter__
Backward-compatibility to use: for x in tqdm(iterable)
def __iter__(self): """Backward-compatibility to use: for x in tqdm(iterable)""" # Inlining instance variables as locals (speed optimisation) iterable = self.iterable # If the bar is disabled, then just walk the iterable # (note: keep this check outside the loop for performance) if self.disable: for obj in iterable: yield obj return mininterval = self.mininterval last_print_t = self.last_print_t last_print_n = self.last_print_n min_start_t = self.start_t + self.delay n = self.n time = self._time try: for obj in iterable: yield obj # Update and possibly print the progressbar. # Note: does not call self.update(1) for speed optimisation. n += 1 if n - last_print_n >= self.miniters: cur_t = time() dt = cur_t - last_print_t if dt >= mininterval and cur_t >= min_start_t: self.update(n - last_print_n) last_print_n = self.last_print_n last_print_t = self.last_print_t finally: self.n = n self.close()
(self)
51,995
tqdm.utils
__le__
null
def __le__(self, other): return (self < other) or (self == other)
(self, other)
51,996
tqdm.std
__len__
null
def __len__(self): return ( self.total if self.iterable is None else self.iterable.shape[0] if hasattr(self.iterable, "shape") else len(self.iterable) if hasattr(self.iterable, "__len__") else self.iterable.__length_hint__() if hasattr(self.iterable, "__length_hint__") else getattr(self, "total", None))
(self)
51,997
tqdm.utils
__lt__
null
def __lt__(self, other): return self._comparable < other._comparable
(self, other)
51,999
tqdm.std
__new__
null
def __new__(cls, *_, **__): instance = object.__new__(cls) with cls.get_lock(): # also constructs lock if non-existent cls._instances.add(instance) # create monitoring thread if cls.monitor_interval and (cls.monitor is None or not cls.monitor.report()): try: cls.monitor = TMonitor(cls, cls.monitor_interval) except Exception as e: # pragma: nocover warn("tqdm:disabling monitor support" " (monitor_interval = 0) due to:\n" + str(e), TqdmMonitorWarning, stacklevel=2) cls.monitor_interval = 0 return instance
(cls, *_, **__)
52,000
tqdm.std
__reversed__
null
def __reversed__(self): try: orig = self.iterable except AttributeError: raise TypeError("'tqdm' object is not reversible") else: self.iterable = reversed(self.iterable) return self.__iter__() finally: self.iterable = orig
(self)
52,001
tqdm.std
__str__
null
def __str__(self): return self.format_meter(**self.format_dict)
(self)
52,002
tqdm.std
clear
Clear current bar display.
def clear(self, nolock=False): """Clear current bar display.""" if self.disable: return if not nolock: self._lock.acquire() pos = abs(self.pos) if pos < (self.nrows or 20): self.moveto(pos) self.sp('') self.fp.write('\r') # place cursor back at the beginning of line self.moveto(-pos) if not nolock: self._lock.release()
(self, nolock=False)
52,003
tqdm.std
close
Cleanup and (if leave=False) close the progressbar.
def close(self): """Cleanup and (if leave=False) close the progressbar.""" if self.disable: return # Prevent multiple closures self.disable = True # decrement instance pos and remove from internal set pos = abs(self.pos) self._decr_instances(self) if self.last_print_t < self.start_t + self.delay: # haven't ever displayed; nothing to clear return # GUI mode if getattr(self, 'sp', None) is None: return # annoyingly, _supports_unicode isn't good enough def fp_write(s): self.fp.write(str(s)) try: fp_write('') except ValueError as e: if 'closed' in str(e): return raise # pragma: no cover leave = pos == 0 if self.leave is None else self.leave with self._lock: if leave: # stats for overall rate (no weighted average) self._ema_dt = lambda: None self.display(pos=0) fp_write('\n') else: # clear previous display if self.display(msg='', pos=pos) and not pos: fp_write('\r')
(self)
52,004
tqdm.std
display
Use `self.sp` to display `msg` in the specified `pos`. Consider overloading this function when inheriting to use e.g.: `self.some_frontend(**self.format_dict)` instead of `self.sp`. Parameters ---------- msg : str, optional. What to display (default: `repr(self)`). pos : int, optional. Position to `moveto` (default: `abs(self.pos)`).
def display(self, msg=None, pos=None): """ Use `self.sp` to display `msg` in the specified `pos`. Consider overloading this function when inheriting to use e.g.: `self.some_frontend(**self.format_dict)` instead of `self.sp`. Parameters ---------- msg : str, optional. What to display (default: `repr(self)`). pos : int, optional. Position to `moveto` (default: `abs(self.pos)`). """ if pos is None: pos = abs(self.pos) nrows = self.nrows or 20 if pos >= nrows - 1: if pos >= nrows: return False if msg or msg is None: # override at `nrows - 1` msg = " ... (more hidden) ..." if not hasattr(self, "sp"): raise TqdmDeprecationWarning( "Please use `tqdm.gui.tqdm(...)`" " instead of `tqdm(..., gui=True)`\n", fp_write=getattr(self.fp, 'write', sys.stderr.write)) if pos: self.moveto(pos) self.sp(self.__str__() if msg is None else msg) if pos: self.moveto(-pos) return True
(self, msg=None, pos=None)
52,005
tqdm.std
format_interval
Formats a number of seconds as a clock time, [H:]MM:SS Parameters ---------- t : int Number of seconds. Returns ------- out : str [H:]MM:SS
@staticmethod def format_interval(t): """ Formats a number of seconds as a clock time, [H:]MM:SS Parameters ---------- t : int Number of seconds. Returns ------- out : str [H:]MM:SS """ mins, s = divmod(int(t), 60) h, m = divmod(mins, 60) return f'{h:d}:{m:02d}:{s:02d}' if h else f'{m:02d}:{s:02d}'
(t)
52,006
tqdm.std
format_meter
Return a string-based progress bar given some parameters Parameters ---------- n : int or float Number of finished iterations. total : int or float The expected total number of iterations. If meaningless (None), only basic progress statistics are displayed (no ETA). elapsed : float Number of seconds passed since start. ncols : int, optional The width of the entire output message. If specified, dynamically resizes `{bar}` to stay within this bound [default: None]. If `0`, will not print any bar (only stats). The fallback is `{bar:10}`. prefix : str, optional Prefix message (included in total width) [default: '']. Use as {desc} in bar_format string. ascii : bool, optional or str, optional If not set, use unicode (smooth blocks) to fill the meter [default: False]. The fallback is to use ASCII characters " 123456789#". unit : str, optional The iteration unit [default: 'it']. unit_scale : bool or int or float, optional If 1 or True, the number of iterations will be printed with an appropriate SI metric prefix (k = 10^3, M = 10^6, etc.) [default: False]. If any other non-zero number, will scale `total` and `n`. rate : float, optional Manual override for iteration rate. If [default: None], uses n/elapsed. bar_format : str, optional Specify a custom bar string formatting. May impact performance. [default: '{l_bar}{bar}{r_bar}'], where l_bar='{desc}: {percentage:3.0f}%|' and r_bar='| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, ' '{rate_fmt}{postfix}]' Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt, percentage, elapsed, elapsed_s, ncols, nrows, desc, unit, rate, rate_fmt, rate_noinv, rate_noinv_fmt, rate_inv, rate_inv_fmt, postfix, unit_divisor, remaining, remaining_s, eta. Note that a trailing ": " is automatically removed after {desc} if the latter is empty. postfix : *, optional Similar to `prefix`, but placed at the end (e.g. for additional stats). Note: postfix is usually a string (not a dict) for this method, and will if possible be set to postfix = ', ' + postfix. However other types are supported (#382). unit_divisor : float, optional [default: 1000], ignored unless `unit_scale` is True. initial : int or float, optional The initial counter value [default: 0]. colour : str, optional Bar colour (e.g. 'green', '#00ff00'). Returns ------- out : Formatted meter and stats, ready to display.
@staticmethod def format_meter(n, total, elapsed, ncols=None, prefix='', ascii=False, unit='it', unit_scale=False, rate=None, bar_format=None, postfix=None, unit_divisor=1000, initial=0, colour=None, **extra_kwargs): """ Return a string-based progress bar given some parameters Parameters ---------- n : int or float Number of finished iterations. total : int or float The expected total number of iterations. If meaningless (None), only basic progress statistics are displayed (no ETA). elapsed : float Number of seconds passed since start. ncols : int, optional The width of the entire output message. If specified, dynamically resizes `{bar}` to stay within this bound [default: None]. If `0`, will not print any bar (only stats). The fallback is `{bar:10}`. prefix : str, optional Prefix message (included in total width) [default: '']. Use as {desc} in bar_format string. ascii : bool, optional or str, optional If not set, use unicode (smooth blocks) to fill the meter [default: False]. The fallback is to use ASCII characters " 123456789#". unit : str, optional The iteration unit [default: 'it']. unit_scale : bool or int or float, optional If 1 or True, the number of iterations will be printed with an appropriate SI metric prefix (k = 10^3, M = 10^6, etc.) [default: False]. If any other non-zero number, will scale `total` and `n`. rate : float, optional Manual override for iteration rate. If [default: None], uses n/elapsed. bar_format : str, optional Specify a custom bar string formatting. May impact performance. [default: '{l_bar}{bar}{r_bar}'], where l_bar='{desc}: {percentage:3.0f}%|' and r_bar='| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, ' '{rate_fmt}{postfix}]' Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt, percentage, elapsed, elapsed_s, ncols, nrows, desc, unit, rate, rate_fmt, rate_noinv, rate_noinv_fmt, rate_inv, rate_inv_fmt, postfix, unit_divisor, remaining, remaining_s, eta. Note that a trailing ": " is automatically removed after {desc} if the latter is empty. postfix : *, optional Similar to `prefix`, but placed at the end (e.g. for additional stats). Note: postfix is usually a string (not a dict) for this method, and will if possible be set to postfix = ', ' + postfix. However other types are supported (#382). unit_divisor : float, optional [default: 1000], ignored unless `unit_scale` is True. initial : int or float, optional The initial counter value [default: 0]. colour : str, optional Bar colour (e.g. 'green', '#00ff00'). Returns ------- out : Formatted meter and stats, ready to display. """ # sanity check: total if total and n >= (total + 0.5): # allow float imprecision (#849) total = None # apply custom scale if necessary if unit_scale and unit_scale not in (True, 1): if total: total *= unit_scale n *= unit_scale if rate: rate *= unit_scale # by default rate = self.avg_dn / self.avg_dt unit_scale = False elapsed_str = tqdm.format_interval(elapsed) # if unspecified, attempt to use rate = average speed # (we allow manual override since predicting time is an arcane art) if rate is None and elapsed: rate = (n - initial) / elapsed inv_rate = 1 / rate if rate else None format_sizeof = tqdm.format_sizeof rate_noinv_fmt = ((format_sizeof(rate) if unit_scale else f'{rate:5.2f}') if rate else '?') + unit + '/s' rate_inv_fmt = ( (format_sizeof(inv_rate) if unit_scale else f'{inv_rate:5.2f}') if inv_rate else '?') + 's/' + unit rate_fmt = rate_inv_fmt if inv_rate and inv_rate > 1 else rate_noinv_fmt if unit_scale: n_fmt = format_sizeof(n, divisor=unit_divisor) total_fmt = format_sizeof(total, divisor=unit_divisor) if total is not None else '?' else: n_fmt = str(n) total_fmt = str(total) if total is not None else '?' try: postfix = ', ' + postfix if postfix else '' except TypeError: pass remaining = (total - n) / rate if rate and total else 0 remaining_str = tqdm.format_interval(remaining) if rate else '?' try: eta_dt = (datetime.now() + timedelta(seconds=remaining) if rate and total else datetime.fromtimestamp(0, timezone.utc)) except OverflowError: eta_dt = datetime.max # format the stats displayed to the left and right sides of the bar if prefix: # old prefix setup work around bool_prefix_colon_already = (prefix[-2:] == ": ") l_bar = prefix if bool_prefix_colon_already else prefix + ": " else: l_bar = '' r_bar = f'| {n_fmt}/{total_fmt} [{elapsed_str}<{remaining_str}, {rate_fmt}{postfix}]' # Custom bar formatting # Populate a dict with all available progress indicators format_dict = { # slight extension of self.format_dict 'n': n, 'n_fmt': n_fmt, 'total': total, 'total_fmt': total_fmt, 'elapsed': elapsed_str, 'elapsed_s': elapsed, 'ncols': ncols, 'desc': prefix or '', 'unit': unit, 'rate': inv_rate if inv_rate and inv_rate > 1 else rate, 'rate_fmt': rate_fmt, 'rate_noinv': rate, 'rate_noinv_fmt': rate_noinv_fmt, 'rate_inv': inv_rate, 'rate_inv_fmt': rate_inv_fmt, 'postfix': postfix, 'unit_divisor': unit_divisor, 'colour': colour, # plus more useful definitions 'remaining': remaining_str, 'remaining_s': remaining, 'l_bar': l_bar, 'r_bar': r_bar, 'eta': eta_dt, **extra_kwargs} # total is known: we can predict some stats if total: # fractional and percentage progress frac = n / total percentage = frac * 100 l_bar += f'{percentage:3.0f}%|' if ncols == 0: return l_bar[:-1] + r_bar[1:] format_dict.update(l_bar=l_bar) if bar_format: format_dict.update(percentage=percentage) # auto-remove colon for empty `{desc}` if not prefix: bar_format = bar_format.replace("{desc}: ", '') else: bar_format = "{l_bar}{bar}{r_bar}" full_bar = FormatReplace() nobar = bar_format.format(bar=full_bar, **format_dict) if not full_bar.format_called: return nobar # no `{bar}`; nothing else to do # Formatting progress bar space available for bar's display full_bar = Bar(frac, max(1, ncols - disp_len(nobar)) if ncols else 10, charset=Bar.ASCII if ascii is True else ascii or Bar.UTF, colour=colour) if not _is_ascii(full_bar.charset) and _is_ascii(bar_format): bar_format = str(bar_format) res = bar_format.format(bar=full_bar, **format_dict) return disp_trim(res, ncols) if ncols else res elif bar_format: # user-specified bar_format but no total l_bar += '|' format_dict.update(l_bar=l_bar, percentage=0) full_bar = FormatReplace() nobar = bar_format.format(bar=full_bar, **format_dict) if not full_bar.format_called: return nobar full_bar = Bar(0, max(1, ncols - disp_len(nobar)) if ncols else 10, charset=Bar.BLANK, colour=colour) res = bar_format.format(bar=full_bar, **format_dict) return disp_trim(res, ncols) if ncols else res else: # no total: no progressbar, ETA, just progress stats return (f'{(prefix + ": ") if prefix else ""}' f'{n_fmt}{unit} [{elapsed_str}, {rate_fmt}{postfix}]')
(n, total, elapsed, ncols=None, prefix='', ascii=False, unit='it', unit_scale=False, rate=None, bar_format=None, postfix=None, unit_divisor=1000, initial=0, colour=None, **extra_kwargs)
52,007
tqdm.std
format_num
Intelligent scientific notation (.3g). Parameters ---------- n : int or float or Numeric A Number. Returns ------- out : str Formatted number.
@staticmethod def format_num(n): """ Intelligent scientific notation (.3g). Parameters ---------- n : int or float or Numeric A Number. Returns ------- out : str Formatted number. """ f = f'{n:.3g}'.replace('e+0', 'e+').replace('e-0', 'e-') n = str(n) return f if len(f) < len(n) else n
(n)
52,008
tqdm.std
format_sizeof
Formats a number (greater than unity) with SI Order of Magnitude prefixes. Parameters ---------- num : float Number ( >= 1) to format. suffix : str, optional Post-postfix [default: '']. divisor : float, optional Divisor between prefixes [default: 1000]. Returns ------- out : str Number with Order of Magnitude SI unit postfix.
@staticmethod def format_sizeof(num, suffix='', divisor=1000): """ Formats a number (greater than unity) with SI Order of Magnitude prefixes. Parameters ---------- num : float Number ( >= 1) to format. suffix : str, optional Post-postfix [default: '']. divisor : float, optional Divisor between prefixes [default: 1000]. Returns ------- out : str Number with Order of Magnitude SI unit postfix. """ for unit in ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z']: if abs(num) < 999.5: if abs(num) < 99.95: if abs(num) < 9.995: return f'{num:1.2f}{unit}{suffix}' return f'{num:2.1f}{unit}{suffix}' return f'{num:3.0f}{unit}{suffix}' num /= divisor return f'{num:3.1f}Y{suffix}'
(num, suffix='', divisor=1000)
52,009
tqdm.std
moveto
null
def moveto(self, n): # TODO: private method self.fp.write('\n' * n + _term_move_up() * -n) getattr(self.fp, 'flush', lambda: None)()
(self, n)
52,010
tqdm.std
refresh
Force refresh the display of this bar. Parameters ---------- nolock : bool, optional If `True`, does not lock. If [default: `False`]: calls `acquire()` on internal lock. lock_args : tuple, optional Passed to internal lock's `acquire()`. If specified, will only `display()` if `acquire()` returns `True`.
def refresh(self, nolock=False, lock_args=None): """ Force refresh the display of this bar. Parameters ---------- nolock : bool, optional If `True`, does not lock. If [default: `False`]: calls `acquire()` on internal lock. lock_args : tuple, optional Passed to internal lock's `acquire()`. If specified, will only `display()` if `acquire()` returns `True`. """ if self.disable: return if not nolock: if lock_args: if not self._lock.acquire(*lock_args): return False else: self._lock.acquire() self.display() if not nolock: self._lock.release() return True
(self, nolock=False, lock_args=None)
52,011
tqdm.std
reset
Resets to 0 iterations for repeated use. Consider combining with `leave=True`. Parameters ---------- total : int or float, optional. Total to use for the new bar.
def reset(self, total=None): """ Resets to 0 iterations for repeated use. Consider combining with `leave=True`. Parameters ---------- total : int or float, optional. Total to use for the new bar. """ self.n = 0 if total is not None: self.total = total if self.disable: return self.last_print_n = 0 self.last_print_t = self.start_t = self._time() self._ema_dn = EMA(self.smoothing) self._ema_dt = EMA(self.smoothing) self._ema_miniters = EMA(self.smoothing) self.refresh()
(self, total=None)
52,012
tqdm.std
set_description
Set/modify description of the progress bar. Parameters ---------- desc : str, optional refresh : bool, optional Forces refresh [default: True].
def set_description(self, desc=None, refresh=True): """ Set/modify description of the progress bar. Parameters ---------- desc : str, optional refresh : bool, optional Forces refresh [default: True]. """ self.desc = desc + ': ' if desc else '' if refresh: self.refresh()
(self, desc=None, refresh=True)
52,013
tqdm.std
set_description_str
Set/modify description without ': ' appended.
def set_description_str(self, desc=None, refresh=True): """Set/modify description without ': ' appended.""" self.desc = desc or '' if refresh: self.refresh()
(self, desc=None, refresh=True)
52,014
tqdm.std
set_postfix
Set/modify postfix (additional stats) with automatic formatting based on datatype. Parameters ---------- ordered_dict : dict or OrderedDict, optional refresh : bool, optional Forces refresh [default: True]. kwargs : dict, optional
def set_postfix(self, ordered_dict=None, refresh=True, **kwargs): """ Set/modify postfix (additional stats) with automatic formatting based on datatype. Parameters ---------- ordered_dict : dict or OrderedDict, optional refresh : bool, optional Forces refresh [default: True]. kwargs : dict, optional """ # Sort in alphabetical order to be more deterministic postfix = OrderedDict([] if ordered_dict is None else ordered_dict) for key in sorted(kwargs.keys()): postfix[key] = kwargs[key] # Preprocess stats according to datatype for key in postfix.keys(): # Number: limit the length of the string if isinstance(postfix[key], Number): postfix[key] = self.format_num(postfix[key]) # Else for any other type, try to get the string conversion elif not isinstance(postfix[key], str): postfix[key] = str(postfix[key]) # Else if it's a string, don't need to preprocess anything # Stitch together to get the final postfix self.postfix = ', '.join(key + '=' + postfix[key].strip() for key in postfix.keys()) if refresh: self.refresh()
(self, ordered_dict=None, refresh=True, **kwargs)
52,015
tqdm.std
set_postfix_str
Postfix without dictionary expansion, similar to prefix handling.
def set_postfix_str(self, s='', refresh=True): """ Postfix without dictionary expansion, similar to prefix handling. """ self.postfix = str(s) if refresh: self.refresh()
(self, s='', refresh=True)
52,016
tqdm.std
status_printer
Manage the printing and in-place updating of a line of characters. Note that if the string is longer than a line, then in-place updating may not work (it will print a new line at each refresh).
@staticmethod def status_printer(file): """ Manage the printing and in-place updating of a line of characters. Note that if the string is longer than a line, then in-place updating may not work (it will print a new line at each refresh). """ fp = file fp_flush = getattr(fp, 'flush', lambda: None) # pragma: no cover if fp in (sys.stderr, sys.stdout): getattr(sys.stderr, 'flush', lambda: None)() getattr(sys.stdout, 'flush', lambda: None)() def fp_write(s): fp.write(str(s)) fp_flush() last_len = [0] def print_status(s): len_s = disp_len(s) fp_write('\r' + s + (' ' * max(last_len[0] - len_s, 0))) last_len[0] = len_s return print_status
(file)
52,017
tqdm.std
unpause
Restart tqdm timer from last print time.
def unpause(self): """Restart tqdm timer from last print time.""" if self.disable: return cur_t = self._time() self.start_t += cur_t - self.last_print_t self.last_print_t = cur_t
(self)
52,018
tqdm.std
update
Manually update the progress bar, useful for streams such as reading files. E.g.: >>> t = tqdm(total=filesize) # Initialise >>> for current_buffer in stream: ... ... ... t.update(len(current_buffer)) >>> t.close() The last line is highly recommended, but possibly not necessary if `t.update()` will be called in such a way that `filesize` will be exactly reached and printed. Parameters ---------- n : int or float, optional Increment to add to the internal counter of iterations [default: 1]. If using float, consider specifying `{n:.3f}` or similar in `bar_format`, or specifying `unit_scale`. Returns ------- out : bool or None True if a `display()` was triggered.
def update(self, n=1): """ Manually update the progress bar, useful for streams such as reading files. E.g.: >>> t = tqdm(total=filesize) # Initialise >>> for current_buffer in stream: ... ... ... t.update(len(current_buffer)) >>> t.close() The last line is highly recommended, but possibly not necessary if `t.update()` will be called in such a way that `filesize` will be exactly reached and printed. Parameters ---------- n : int or float, optional Increment to add to the internal counter of iterations [default: 1]. If using float, consider specifying `{n:.3f}` or similar in `bar_format`, or specifying `unit_scale`. Returns ------- out : bool or None True if a `display()` was triggered. """ if self.disable: return if n < 0: self.last_print_n += n # for auto-refresh logic to work self.n += n # check counter first to reduce calls to time() if self.n - self.last_print_n >= self.miniters: cur_t = self._time() dt = cur_t - self.last_print_t if dt >= self.mininterval and cur_t >= self.start_t + self.delay: cur_t = self._time() dn = self.n - self.last_print_n # >= n if self.smoothing and dt and dn: # EMA (not just overall average) self._ema_dn(dn) self._ema_dt(dt) self.refresh(lock_args=self.lock_args) if self.dynamic_miniters: # If no `miniters` was specified, adjust automatically to the # maximum iteration rate seen so far between two prints. # e.g.: After running `tqdm.update(5)`, subsequent # calls to `tqdm.update()` will only cause an update after # at least 5 more iterations. if self.maxinterval and dt >= self.maxinterval: self.miniters = dn * (self.mininterval or self.maxinterval) / dt elif self.smoothing: # EMA miniters update self.miniters = self._ema_miniters( dn * (self.mininterval / dt if self.mininterval and dt else 1)) else: # max iters between two prints self.miniters = max(self.miniters, dn) # Store old values for next call self.last_print_n = self.n self.last_print_t = cur_t return True
(self, n=1)
52,022
hanzidentifier.core
count_chinese
count how many chinese exist in a string
def count_chinese(s: str) -> int: """count how many chinese exist in a string""" result = 0 for i in s: if has_chinese(i): result += 1 return result
(s: str) -> int
52,023
hanzidentifier.core
has_chinese
Check if a string has Chinese characters in it. This is a faster version of: >>> identify('foo') is not UNKNOWN
def has_chinese(s): """Check if a string has Chinese characters in it. This is a faster version of: >>> identify('foo') is not UNKNOWN """ return bool(helpers.get_hanzi(s))
(s)
52,025
hanzidentifier.core
identify
Identify what kind of Chinese characters a string contains. *s* is a string to examine. The string's Chinese characters are tested to see if they are compatible with the Traditional or Simplified characters systems, compatible with both, or contain a mixture of Traditional and Simplified characters. The :data:`TRADITIONAL`, :data:`SIMPLIFIED`, :data:`BOTH`, or :data:`MIXED` constants are returned to indicate the string's identity. If *s* contains no Chinese characters, then :data:`UNKNOWN` is returned. All characters in a string that aren't found in the CC-CEDICT dictionary are ignored. Because the Traditional and Simplified Chinese character systems overlap, a string containing Simplified characters could identify as :data:`SIMPLIFIED` or :data:`BOTH` depending on if the characters are also Traditional characters. To make testing the identity of a string easier, the functions :func:`is_traditional`, :func:`is_simplified`, and :func:`has_chinese` are provided.
def identify(s): """Identify what kind of Chinese characters a string contains. *s* is a string to examine. The string's Chinese characters are tested to see if they are compatible with the Traditional or Simplified characters systems, compatible with both, or contain a mixture of Traditional and Simplified characters. The :data:`TRADITIONAL`, :data:`SIMPLIFIED`, :data:`BOTH`, or :data:`MIXED` constants are returned to indicate the string's identity. If *s* contains no Chinese characters, then :data:`UNKNOWN` is returned. All characters in a string that aren't found in the CC-CEDICT dictionary are ignored. Because the Traditional and Simplified Chinese character systems overlap, a string containing Simplified characters could identify as :data:`SIMPLIFIED` or :data:`BOTH` depending on if the characters are also Traditional characters. To make testing the identity of a string easier, the functions :func:`is_traditional`, :func:`is_simplified`, and :func:`has_chinese` are provided. """ chinese = helpers.get_hanzi(s) if not chinese: return UNKNOWN if chinese.issubset(helpers.SHARED_CHARACTERS): return BOTH if chinese.issubset(helpers.TRADITIONAL_CHARACTERS): return TRADITIONAL if chinese.issubset(helpers.SIMPLIFIED_CHARACTERS): return SIMPLIFIED return MIXED
(s)
52,026
hanzidentifier.core
is_simplified
Check if a string's Chinese characters are Simplified. This is equivalent to: >>> identify('foo') in (SIMPLIFIED, BOTH)
def is_simplified(s): """Check if a string's Chinese characters are Simplified. This is equivalent to: >>> identify('foo') in (SIMPLIFIED, BOTH) """ chinese = helpers.get_hanzi(s) if not chinese: return False if chinese.issubset(helpers.SHARED_CHARACTERS): return True if chinese.issubset(helpers.SIMPLIFIED_CHARACTERS): return True return False
(s)
52,027
hanzidentifier.core
is_traditional
Check if a string's Chinese characters are Traditional. This is equivalent to: >>> identify('foo') in (TRADITIONAL, BOTH)
def is_traditional(s): """Check if a string's Chinese characters are Traditional. This is equivalent to: >>> identify('foo') in (TRADITIONAL, BOTH) """ chinese = helpers.get_hanzi(s) if not chinese: return False if chinese.issubset(helpers.SHARED_CHARACTERS): return True if chinese.issubset(helpers.TRADITIONAL_CHARACTERS): return True return False
(s)
52,028
fs.enums
ResourceType
Resource Types. Positive values are reserved, negative values are implementation dependent. Most filesystems will support only directory(1) and file(2). Other types exist to identify more exotic resource types supported by Linux filesystems.
class ResourceType(IntEnum): """Resource Types. Positive values are reserved, negative values are implementation dependent. Most filesystems will support only directory(1) and file(2). Other types exist to identify more exotic resource types supported by Linux filesystems. """ #: Unknown resource type, used if the filesystem is unable to #: tell what the resource is. unknown = 0 #: A directory. directory = 1 #: A simple file. file = 2 #: A character file. character = 3 #: A block special file. block_special_file = 4 #: A first in first out file. fifo = 5 #: A socket. socket = 6 #: A symlink. symlink = 7
(value, names=None, *, module=None, qualname=None, type=None, start=1)
52,029
fs.enums
Seek
Constants used by `io.IOBase.seek`. These match `os.SEEK_CUR`, `os.SEEK_END`, and `os.SEEK_SET` from the standard library.
class Seek(IntEnum): """Constants used by `io.IOBase.seek`. These match `os.SEEK_CUR`, `os.SEEK_END`, and `os.SEEK_SET` from the standard library. """ #: Seek from the current file position. current = os.SEEK_CUR #: Seek from the end of the file. end = os.SEEK_END #: Seek from the start of the file. set = os.SEEK_SET
(value, names=None, *, module=None, qualname=None, type=None, start=1)
52,034
os
fsdecode
Decode filename (an os.PathLike, bytes, or str) from the filesystem encoding with 'surrogateescape' error handler, return str unchanged. On Windows, use 'strict' error handler if the file system encoding is 'mbcs' (which is the default encoding).
def _fscodec(): encoding = sys.getfilesystemencoding() errors = sys.getfilesystemencodeerrors() def fsencode(filename): """Encode filename (an os.PathLike, bytes, or str) to the filesystem encoding with 'surrogateescape' error handler, return bytes unchanged. On Windows, use 'strict' error handler if the file system encoding is 'mbcs' (which is the default encoding). """ filename = fspath(filename) # Does type-checking of `filename`. if isinstance(filename, str): return filename.encode(encoding, errors) else: return filename def fsdecode(filename): """Decode filename (an os.PathLike, bytes, or str) from the filesystem encoding with 'surrogateescape' error handler, return str unchanged. On Windows, use 'strict' error handler if the file system encoding is 'mbcs' (which is the default encoding). """ filename = fspath(filename) # Does type-checking of `filename`. if isinstance(filename, bytes): return filename.decode(encoding, errors) else: return filename return fsencode, fsdecode
(filename)
52,035
os
fsencode
Encode filename (an os.PathLike, bytes, or str) to the filesystem encoding with 'surrogateescape' error handler, return bytes unchanged. On Windows, use 'strict' error handler if the file system encoding is 'mbcs' (which is the default encoding).
def _fscodec(): encoding = sys.getfilesystemencoding() errors = sys.getfilesystemencodeerrors() def fsencode(filename): """Encode filename (an os.PathLike, bytes, or str) to the filesystem encoding with 'surrogateescape' error handler, return bytes unchanged. On Windows, use 'strict' error handler if the file system encoding is 'mbcs' (which is the default encoding). """ filename = fspath(filename) # Does type-checking of `filename`. if isinstance(filename, str): return filename.encode(encoding, errors) else: return filename def fsdecode(filename): """Decode filename (an os.PathLike, bytes, or str) from the filesystem encoding with 'surrogateescape' error handler, return str unchanged. On Windows, use 'strict' error handler if the file system encoding is 'mbcs' (which is the default encoding). """ filename = fspath(filename) # Does type-checking of `filename`. if isinstance(filename, bytes): return filename.decode(encoding, errors) else: return filename return fsencode, fsdecode
(filename)
52,038
uciwebauth.uciwebauth
AdsiUser
Active Directory Service Interfaces User Account. Examples -------- >>> user = AdsiUser('userid', username='username', password='password', ... dnname='LDAP://myserver/ou=Users,ou=myou,dc=mydomain,dc=com') >>> user.enable() >>> user.unlock() >>> user.set_password('new-password')
class AdsiUser: """Active Directory Service Interfaces User Account. Examples -------- >>> user = AdsiUser('userid', username='username', password='password', ... dnname='LDAP://myserver/ou=Users,ou=myou,dc=mydomain,dc=com') >>> user.enable() >>> user.unlock() >>> user.set_password('new-password') """ def __init__(self, userid, dnname, username, password): """Initialize ADSI user object from userid. Raise AdsiUserError if userid is not found. Parameters ---------- userid : str The Active Directory Id of a user. dnname : str The ADsPath to the ADSI user object. username : str The user name to be used for securing permission from the namespace server. password: str The password to be used to obtain permission from the namespace server. """ import win32com import win32com.adsi # type: ignore self.user = '' adsi = win32com.client.Dispatch('ADsNameSpaces') ldap = adsi.getobject('', 'LDAP:') users = ldap.OpenDSObject(dnname, username, password, 1) for user in users: if user.Class == 'user' and user.samAccountName == userid: self.user = user if self.user == '': raise AdsiUserError('user not found') def enable(self): """Enable user account. Return True if account has been enabled.""" if self.user.AccountDisabled: self.user.AccountDisabled = False self.user.SetInfo() return True return None def unlock(self): """Unlock user account. Return True if account has been unlocked.""" if self.user.IsAccountLocked: self.user.IsAccountLocked = False self.user.SetInfo() return True return None def set_password(self, password, validate=None): """Set user account password.""" if validate: validate(password) self.user.setpassword(password) # disable "Must change password at next logon" self.user.Put('pwdLastSet', -1) self.user.SetInfo() @property def must_change_password(self): """Return if user must change password at next logon.""" return ( self.user.pwdLastSet.lowpart + self.user.pwdLastSet.highpart == 0 ) @property def is_disabled(self): """Return if user account is disabled.""" return self.user.AccountDisabled def __str__(self): """Return string with information about user.""" return '\n'.join( f'{key}: {getattr(self.user, key)}' for key in ( 'cn', 'samAccountName', 'Fullname', 'Description', 'PasswordMinimumLength', 'AccountExpirationDate', 'AccountDisabled', ) )
(userid, dnname, username, password)
52,039
uciwebauth.uciwebauth
__init__
Initialize ADSI user object from userid. Raise AdsiUserError if userid is not found. Parameters ---------- userid : str The Active Directory Id of a user. dnname : str The ADsPath to the ADSI user object. username : str The user name to be used for securing permission from the namespace server. password: str The password to be used to obtain permission from the namespace server.
def __init__(self, userid, dnname, username, password): """Initialize ADSI user object from userid. Raise AdsiUserError if userid is not found. Parameters ---------- userid : str The Active Directory Id of a user. dnname : str The ADsPath to the ADSI user object. username : str The user name to be used for securing permission from the namespace server. password: str The password to be used to obtain permission from the namespace server. """ import win32com import win32com.adsi # type: ignore self.user = '' adsi = win32com.client.Dispatch('ADsNameSpaces') ldap = adsi.getobject('', 'LDAP:') users = ldap.OpenDSObject(dnname, username, password, 1) for user in users: if user.Class == 'user' and user.samAccountName == userid: self.user = user if self.user == '': raise AdsiUserError('user not found')
(self, userid, dnname, username, password)
52,040
uciwebauth.uciwebauth
__str__
Return string with information about user.
def __str__(self): """Return string with information about user.""" return '\n'.join( f'{key}: {getattr(self.user, key)}' for key in ( 'cn', 'samAccountName', 'Fullname', 'Description', 'PasswordMinimumLength', 'AccountExpirationDate', 'AccountDisabled', ) )
(self)
52,041
uciwebauth.uciwebauth
enable
Enable user account. Return True if account has been enabled.
def enable(self): """Enable user account. Return True if account has been enabled.""" if self.user.AccountDisabled: self.user.AccountDisabled = False self.user.SetInfo() return True return None
(self)
52,042
uciwebauth.uciwebauth
set_password
Set user account password.
def set_password(self, password, validate=None): """Set user account password.""" if validate: validate(password) self.user.setpassword(password) # disable "Must change password at next logon" self.user.Put('pwdLastSet', -1) self.user.SetInfo()
(self, password, validate=None)
52,043
uciwebauth.uciwebauth
unlock
Unlock user account. Return True if account has been unlocked.
def unlock(self): """Unlock user account. Return True if account has been unlocked.""" if self.user.IsAccountLocked: self.user.IsAccountLocked = False self.user.SetInfo() return True return None
(self)
52,044
uciwebauth.uciwebauth
AdsiUserError
Base class for errors in the AdsiUser class.
class AdsiUserError(Exception): """Base class for errors in the AdsiUser class."""
null
52,045
uciwebauth.uciwebauth
LdapPerson
A person entry in the UCI LDAP directory. Raise LdapPersonError if search fails or results are ambiguous or not a person. The first item of any LDAP record field listed in ATTRS is stored as an attribute. The complete LDAP search results are stored as 'records' attribute. Examples -------- >>> try: ... p = LdapPerson(TEST_USER) ... except LdapPersonError: ... print('LdapPerson failed') ... else: ... p2 = LdapPerson(p.uciCampusID) ... p3 = LdapPerson(f'*{p.givenName} {p.middleName}*', 'cn') ... (p.cn == p2.cn) and (p.mail == p3.mail) True
class LdapPerson: """A person entry in the UCI LDAP directory. Raise LdapPersonError if search fails or results are ambiguous or not a person. The first item of any LDAP record field listed in ATTRS is stored as an attribute. The complete LDAP search results are stored as 'records' attribute. Examples -------- >>> try: ... p = LdapPerson(TEST_USER) ... except LdapPersonError: ... print('LdapPerson failed') ... else: ... p2 = LdapPerson(p.uciCampusID) ... p3 = LdapPerson(f'*{p.givenName} {p.middleName}*', 'cn') ... (p.cn == p2.cn) and (p.mail == p3.mail) True """ SERVER = 'ldaps://ldap.oit.uci.edu:636' # 'ldap://ldap.oit.uci.edu:389' BASEDN = 'ou=people,dc=uci,dc=edu' TYPES = b'uciPerson', b'eduPerson', b'PERSON', b'STUDENT' ATTRS = ( 'appointmentType', 'cn', 'createTimestamp', 'dn', 'department', 'departmentNumber', 'displayName', 'eduPersonAffiliation', 'eduPersonPrincipalName', 'eduPersonPrincipalNamePrior', 'eduPersonOrgDN', 'eduPersonScopedAffiliation', 'employeeNumber', 'facsimileTelephoneNumber', 'givenName', 'l', 'mail', 'major', 'memberOf', 'middleName', 'modifyTimestamp', 'myDotName', 'o', 'objectClass', 'ou', 'postalAddress', 'postalCode', 'sn', 'st', 'telephoneNumber', 'title', 'uciAdminAppCSS', 'uciAffiliation', 'uciApplicantEmail', 'uciCampusID', 'uciCTOCode', 'uciEmployeeClass', 'uciEmployeeClassDescription', 'uciEmployeeGivenName', 'uciEmployeeMiddleName', 'uciEmployeeSN', 'uciEmployeeStatus', 'uciEmployeeStatusCode', 'uciFloater', 'uciGuestExpiration', 'uciHomeDepartment', 'uciHomeDepartmentCode', 'uciHomeDepartmentCodeTitle', 'uciHrStatus', 'uciKFSCampusCode', 'uciKFSChart', 'uciKFSChartOrgCode', 'uciKFSChartOrgName', 'uciKFSOrgCode', 'uciMailDeliveryPoint', 'ucinetidLocked', 'ucinetidLockedAt', 'ucinetidPasswordChangeAt', 'ucinetidReset', 'ucinetidResetAt', 'uciPrimaryCTOCode', 'uciPrimaryEmployeeClass', 'uciPrimaryEmployeeClassDescription', 'uciPrimaryTitle', 'uciPrimaryTitleCode', 'uciPublishFlag', 'uciRecentlyHired', 'uciReleaseFlag', 'uciSNAPTemplate', 'uciSponsorDepartment', 'uciSponsorDepartmentCode', 'uciSponsorID', 'uciStudentEmailRelease', 'uciStudentGivenName', 'uciStudentID', 'uciStudentLevel', 'uciStudentMiddleName', 'uciStudentSN', 'uciSupervisorDN', 'uciSupervisorRoleFlag', 'uciTestAccount', 'uciUCNetID', 'uciVPNFlag', 'uciWebMailAddress', 'uciZotCode', 'uciZotCodeName', 'uid', ) def __init__( self, query, rdn=None, uid=None, pwd=None, verifyssl=False, server=SERVER, basedn=BASEDN, attributes=ATTRS, types=TYPES, ): """Search LDAP directory for query and set attributes from results. Query is searched in 'uid' (if string), 'uciCampusID' (if int), or the relative distinguished name 'rdn' if specified. Raise LdapPersonError on failure. """ import ldap # noqa: delayed import if not verifyssl: ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER) if not query: raise ValueError('empty query') if query[0] == '(' and query[-1] == ')': pass elif rdn: query = f'({rdn}={query})' else: try: query = f'(uciCampusID={int(query):012d})' except Exception: query = f'(uid={query})' if uid and pwd and server == self.SERVER: server = server.replace('ldap.', 'ldap-auth.') try: ldapobj = ldap.initialize(server) except ldap.LDAPError as exc: raise LdapPersonError('LDAP initialization failed') from exc if uid and pwd: ldapobj.simple_bind_s(f'uid={uid},{basedn}', pwd) try: id_ = ldapobj.search(basedn, ldap.SCOPE_SUBTREE, query, None) results = [] while 1: ltype, data = ldapobj.result(id_, 0) if not data: break elif ltype == ldap.RES_SEARCH_ENTRY: results.append(data) except ldap.LDAPError as exc: raise LdapPersonError(f'LDAP search failed: {query!r}') from exc if len(results) != 1: raise LdapPersonError( f'{query} not found or result ambiguous: {results!r}' ) self.dn, self.records = results[0][0] if not self._is_type(types): raise LdapPersonError(f'{query} has wrong type') for attr in attributes: if attr in self.records: value = self.records[attr][0].decode() setattr(self, attr, value) else: setattr(self, attr, None) try: self.pretty_name = ' '.join( (self.givenName.split()[0].title(), self.sn.title()) ) except Exception: self.pretty_name = None def _is_type(self, types): """Return whether record is one of types.""" if not types: return True for type_ in ('objectClass', 'type'): if type_ in self.records: for value in self.records[type_]: if value in types: return True return False def __str__(self): """Return string with information about person.""" return '\n'.join( f'{attr}={getattr(self, attr)}' for attr in self.ATTRS if getattr(self, attr) )
(query, rdn=None, uid=None, pwd=None, verifyssl=False, server='ldaps://ldap.oit.uci.edu:636', basedn='ou=people,dc=uci,dc=edu', attributes=('appointmentType', 'cn', 'createTimestamp', 'dn', 'department', 'departmentNumber', 'displayName', 'eduPersonAffiliation', 'eduPersonPrincipalName', 'eduPersonPrincipalNamePrior', 'eduPersonOrgDN', 'eduPersonScopedAffiliation', 'employeeNumber', 'facsimileTelephoneNumber', 'givenName', 'l', 'mail', 'major', 'memberOf', 'middleName', 'modifyTimestamp', 'myDotName', 'o', 'objectClass', 'ou', 'postalAddress', 'postalCode', 'sn', 'st', 'telephoneNumber', 'title', 'uciAdminAppCSS', 'uciAffiliation', 'uciApplicantEmail', 'uciCampusID', 'uciCTOCode', 'uciEmployeeClass', 'uciEmployeeClassDescription', 'uciEmployeeGivenName', 'uciEmployeeMiddleName', 'uciEmployeeSN', 'uciEmployeeStatus', 'uciEmployeeStatusCode', 'uciFloater', 'uciGuestExpiration', 'uciHomeDepartment', 'uciHomeDepartmentCode', 'uciHomeDepartmentCodeTitle', 'uciHrStatus', 'uciKFSCampusCode', 'uciKFSChart', 'uciKFSChartOrgCode', 'uciKFSChartOrgName', 'uciKFSOrgCode', 'uciMailDeliveryPoint', 'ucinetidLocked', 'ucinetidLockedAt', 'ucinetidPasswordChangeAt', 'ucinetidReset', 'ucinetidResetAt', 'uciPrimaryCTOCode', 'uciPrimaryEmployeeClass', 'uciPrimaryEmployeeClassDescription', 'uciPrimaryTitle', 'uciPrimaryTitleCode', 'uciPublishFlag', 'uciRecentlyHired', 'uciReleaseFlag', 'uciSNAPTemplate', 'uciSponsorDepartment', 'uciSponsorDepartmentCode', 'uciSponsorID', 'uciStudentEmailRelease', 'uciStudentGivenName', 'uciStudentID', 'uciStudentLevel', 'uciStudentMiddleName', 'uciStudentSN', 'uciSupervisorDN', 'uciSupervisorRoleFlag', 'uciTestAccount', 'uciUCNetID', 'uciVPNFlag', 'uciWebMailAddress', 'uciZotCode', 'uciZotCodeName', 'uid'), types=(b'uciPerson', b'eduPerson', b'PERSON', b'STUDENT'))
52,046
uciwebauth.uciwebauth
__init__
Search LDAP directory for query and set attributes from results. Query is searched in 'uid' (if string), 'uciCampusID' (if int), or the relative distinguished name 'rdn' if specified. Raise LdapPersonError on failure.
def __init__( self, query, rdn=None, uid=None, pwd=None, verifyssl=False, server=SERVER, basedn=BASEDN, attributes=ATTRS, types=TYPES, ): """Search LDAP directory for query and set attributes from results. Query is searched in 'uid' (if string), 'uciCampusID' (if int), or the relative distinguished name 'rdn' if specified. Raise LdapPersonError on failure. """ import ldap # noqa: delayed import if not verifyssl: ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER) if not query: raise ValueError('empty query') if query[0] == '(' and query[-1] == ')': pass elif rdn: query = f'({rdn}={query})' else: try: query = f'(uciCampusID={int(query):012d})' except Exception: query = f'(uid={query})' if uid and pwd and server == self.SERVER: server = server.replace('ldap.', 'ldap-auth.') try: ldapobj = ldap.initialize(server) except ldap.LDAPError as exc: raise LdapPersonError('LDAP initialization failed') from exc if uid and pwd: ldapobj.simple_bind_s(f'uid={uid},{basedn}', pwd) try: id_ = ldapobj.search(basedn, ldap.SCOPE_SUBTREE, query, None) results = [] while 1: ltype, data = ldapobj.result(id_, 0) if not data: break elif ltype == ldap.RES_SEARCH_ENTRY: results.append(data) except ldap.LDAPError as exc: raise LdapPersonError(f'LDAP search failed: {query!r}') from exc if len(results) != 1: raise LdapPersonError( f'{query} not found or result ambiguous: {results!r}' ) self.dn, self.records = results[0][0] if not self._is_type(types): raise LdapPersonError(f'{query} has wrong type') for attr in attributes: if attr in self.records: value = self.records[attr][0].decode() setattr(self, attr, value) else: setattr(self, attr, None) try: self.pretty_name = ' '.join( (self.givenName.split()[0].title(), self.sn.title()) ) except Exception: self.pretty_name = None
(self, query, rdn=None, uid=None, pwd=None, verifyssl=False, server='ldaps://ldap.oit.uci.edu:636', basedn='ou=people,dc=uci,dc=edu', attributes=('appointmentType', 'cn', 'createTimestamp', 'dn', 'department', 'departmentNumber', 'displayName', 'eduPersonAffiliation', 'eduPersonPrincipalName', 'eduPersonPrincipalNamePrior', 'eduPersonOrgDN', 'eduPersonScopedAffiliation', 'employeeNumber', 'facsimileTelephoneNumber', 'givenName', 'l', 'mail', 'major', 'memberOf', 'middleName', 'modifyTimestamp', 'myDotName', 'o', 'objectClass', 'ou', 'postalAddress', 'postalCode', 'sn', 'st', 'telephoneNumber', 'title', 'uciAdminAppCSS', 'uciAffiliation', 'uciApplicantEmail', 'uciCampusID', 'uciCTOCode', 'uciEmployeeClass', 'uciEmployeeClassDescription', 'uciEmployeeGivenName', 'uciEmployeeMiddleName', 'uciEmployeeSN', 'uciEmployeeStatus', 'uciEmployeeStatusCode', 'uciFloater', 'uciGuestExpiration', 'uciHomeDepartment', 'uciHomeDepartmentCode', 'uciHomeDepartmentCodeTitle', 'uciHrStatus', 'uciKFSCampusCode', 'uciKFSChart', 'uciKFSChartOrgCode', 'uciKFSChartOrgName', 'uciKFSOrgCode', 'uciMailDeliveryPoint', 'ucinetidLocked', 'ucinetidLockedAt', 'ucinetidPasswordChangeAt', 'ucinetidReset', 'ucinetidResetAt', 'uciPrimaryCTOCode', 'uciPrimaryEmployeeClass', 'uciPrimaryEmployeeClassDescription', 'uciPrimaryTitle', 'uciPrimaryTitleCode', 'uciPublishFlag', 'uciRecentlyHired', 'uciReleaseFlag', 'uciSNAPTemplate', 'uciSponsorDepartment', 'uciSponsorDepartmentCode', 'uciSponsorID', 'uciStudentEmailRelease', 'uciStudentGivenName', 'uciStudentID', 'uciStudentLevel', 'uciStudentMiddleName', 'uciStudentSN', 'uciSupervisorDN', 'uciSupervisorRoleFlag', 'uciTestAccount', 'uciUCNetID', 'uciVPNFlag', 'uciWebMailAddress', 'uciZotCode', 'uciZotCodeName', 'uid'), types=(b'uciPerson', b'eduPerson', b'PERSON', b'STUDENT'))
52,047
uciwebauth.uciwebauth
__str__
Return string with information about person.
def __str__(self): """Return string with information about person.""" return '\n'.join( f'{attr}={getattr(self, attr)}' for attr in self.ATTRS if getattr(self, attr) )
(self)
52,048
uciwebauth.uciwebauth
_is_type
Return whether record is one of types.
def _is_type(self, types): """Return whether record is one of types.""" if not types: return True for type_ in ('objectClass', 'type'): if type_ in self.records: for value in self.records[type_]: if value in types: return True return False
(self, types)
52,049
uciwebauth.uciwebauth
LdapPersonError
Base class for errors in the LdapPerson class.
class LdapPersonError(Exception): """Base class for errors in the LdapPerson class."""
null
52,050
uciwebauth.uciwebauth
WebAuth
Authenticate against UCI WebAuth service. Raise WebAuthError if authentication fails. Attributes ---------- ucinetid_auth: str or None 64-character string stored in UCI WebAuth database as key to other information about login. ucinetid : str or None UCInetID authenticated with key. auth_host : str or None IP number of host that key was authenticated from. time_created : int or None Seconds since epoch that key was authenticated. last_checked : int or None Seconds since epoch to when webauth_check was last run on key. max_idle_time : int or None login_timeout : str or None campus_id : int or None Unique number for every person on UCI campus that will never be duplicated or repeated. uci_affiliations : str or None List of affiliations that a user has with UCI. student | staff | employee | guest | alumni | former_student age_in_seconds : int or None Number of seconds passed since password was authenticated. seconds_since_checked : int or None Seconds since last time webauth_check was run on key. auth_fail : str or None Reason for authorization failure. error_code : str or None Key to ERROR_CODES. Examples -------- >>> try: ... auth = WebAuth(TEST_USER, TEST_PASSWORD) ... except WebAuthError as e: ... print(e) ... else: ... auth.ucinetid == TEST_USER ... try: ... auth.check() ... except WebAuthError as e: ... print(e) ... try: ... auth.logout() ... except WebAuthError as e: ... print(e) True >>> auth = WebAuth() >>> try: ... auth.authenticate('not a valid ucinetid_auth token') ... except WebAuthError as e: ... print(e) No valid ucinetid_auth token found
class WebAuth: """Authenticate against UCI WebAuth service. Raise WebAuthError if authentication fails. Attributes ---------- ucinetid_auth: str or None 64-character string stored in UCI WebAuth database as key to other information about login. ucinetid : str or None UCInetID authenticated with key. auth_host : str or None IP number of host that key was authenticated from. time_created : int or None Seconds since epoch that key was authenticated. last_checked : int or None Seconds since epoch to when webauth_check was last run on key. max_idle_time : int or None login_timeout : str or None campus_id : int or None Unique number for every person on UCI campus that will never be duplicated or repeated. uci_affiliations : str or None List of affiliations that a user has with UCI. student | staff | employee | guest | alumni | former_student age_in_seconds : int or None Number of seconds passed since password was authenticated. seconds_since_checked : int or None Seconds since last time webauth_check was run on key. auth_fail : str or None Reason for authorization failure. error_code : str or None Key to ERROR_CODES. Examples -------- >>> try: ... auth = WebAuth(TEST_USER, TEST_PASSWORD) ... except WebAuthError as e: ... print(e) ... else: ... auth.ucinetid == TEST_USER ... try: ... auth.check() ... except WebAuthError as e: ... print(e) ... try: ... auth.logout() ... except WebAuthError as e: ... print(e) True >>> auth = WebAuth() >>> try: ... auth.authenticate('not a valid ucinetid_auth token') ... except WebAuthError as e: ... print(e) No valid ucinetid_auth token found """ LOGIN_URL = 'https://login.uci.edu/{}/webauth' CHECK_URL = 'https://login.uci.edu/ucinetid/webauth_check' LOGOUT_URL = 'https://login.uci.edu/ucinetid/webauth_logout' USER_AGENT = { 'User-Agent': 'Python-urllib/{} uciwebauth.py'.format( sys.version.split(' ', 1)[0] ) } ERROR_CODES = { 'WEBAUTH_DOWN': 'The WebAuth Server is currently down', 'NO_AUTH_KEY': 'No ucinetid_auth was provided', 'NOT_FOUND': 'The ucinetid_auth is not in the database', 'NO_AFFILIATION': 'Access denied to see user information', } ATTRS = { 'ucinetid': str, 'auth_host': str, 'x_forwarded_for': str, 'time_created': int, 'last_checked': int, 'max_idle_time': int, 'login_timeout': int, 'campus_id': str, 'uci_affiliations': str, 'age_in_seconds': int, 'seconds_since_checked': int, 'auth_contexts': str, 'auth_methods': str, 'auth_fail': str, 'error_code': str, } def __init__(self, usrid=None, password=None, duo=True): app = 'duo' if duo else 'uciwebauth' self._login_url = WebAuth.LOGIN_URL.format(app) self._check_url = WebAuth.CHECK_URL self._logout_url = WebAuth.LOGOUT_URL if usrid: self.authenticate(usrid, password) else: self._clear() def authenticate(self, usrid, password=None): """Get ucinetid_auth token. Usrid can be a UCInetId, a 64-byte WebAuth token or any string containing the token, e.g. HTTP QUERY_STRING or HTTP_COOKIE. Raise WebAuthError on failure. """ self._clear() if password is None and len(usrid) > 8: self.ucinetid_auth = self._search_token(usrid) else: self.ucinetid_auth = self._new_token(usrid, password) if not self.ucinetid_auth: raise WebAuthError('No valid ucinetid_auth token found') self.check() def check(self): """Get data associated with ucinetid_auth token. Raise WebAuthError on failure. """ if not self.ucinetid_auth: return data = urlencode({'ucinetid_auth': self.ucinetid_auth}).encode() request = Request(self._check_url, data, self.USER_AGENT) try: response = urlopen(request).read() except Exception as exc: raise WebAuthError('UCI webauth_check site not found') from exc for line in response.splitlines(): line = line.decode() try: attr, value = line.strip().split('=') setattr(self, attr, self.ATTRS[attr](value)) except (KeyError, ValueError): pass if self.auth_fail: raise WebAuthError(self.auth_fail) def logout(self): """Clear ucinetid_auth entry in UCI WebAuth database.""" if not self.ucinetid_auth: return data = urlencode({'ucinetid_auth': self.ucinetid_auth}).encode() request = Request(self._logout_url, data, self.USER_AGENT) try: urlopen(request).read() except Exception: raise WebAuthError('UCI webauth_logout site not found') self._clear() def validate(self, timeout=None, auth_host=None): """Raise WebAuthError if no token, timeout, or host mismatch.""" if not self.ucinetid_auth or len(self.ucinetid_auth) != 64: raise WebAuthError('Not logged in') if timeout is not None and self.age_in_seconds > timeout: raise WebAuthError('Authentication expired') if auth_host and self.auth_host != auth_host: raise WebAuthError( f'Host mismatch: ({self.auth_host} != {auth_host}' ) def login_url(self, return_url=''): """Return URL to log in to WebAuth.""" return ( self._login_url + '?' + urlencode({'return_url': return_url}).replace('&', '&amp;') ) def logout_url(self, return_url=''): """Return URL to log out of WebAuth.""" return ( self._logout_url + '?' + urlencode( {'ucinetid_auth': self.ucinetid_auth, 'return_url': return_url} ).replace('&', '&amp;') ) def _clear(self): """Initialize attributes to None.""" self.ucinetid_auth = None for attr in self.ATTRS: setattr(self, attr, None) def _search_token(self, search_string): """Return ucinetid_auth token from string.""" if search_string and len(search_string) >= 64: pattern = 'ucinetid_auth=' if len(search_string) > 64 else '' pattern += '([a-zA-Z0-9_]{64})' try: return re.search(pattern, search_string).group(1) except AttributeError: pass return None def _new_token(self, ucinetid, password): """Authenticate username/password and get new ucinetid_auth token.""" if password is None or not ucinetid or len(ucinetid) > 8: raise WebAuthError('Invalid ucinetid or password') data = urlencode( { 'ucinetid': ucinetid, 'password': password, 'return_url': '', 'referer': '', 'info_text': '', 'info_url': '', 'submit_type': '', 'return_auth_contexts': 'true', 'login_button': 'Login', } ).encode() request = Request(self._login_url, data, self.USER_AGENT) try: response = urlopen(request) except Exception as exc: raise WebAuthError('UCI webauth site not found') from exc try: cookie = response.info()['Set-Cookie'] if 'ucinetid_auth' not in cookie: raise ValueError() except Exception as exc: raise WebAuthError('Cookie not found') from exc ucinetid_auth = self._search_token(cookie) if not ucinetid_auth: raise WebAuthError('Authentication failed') return ucinetid_auth def __str__(self): """Return string with information about authenticated UCInetId.""" s = [f'ucinetid_auth={self.ucinetid_auth}'] for attr in self.ATTRS: value = getattr(self, attr) if value is not None: s.append(f'{attr}={value}') return '\n'.join(s)
(usrid=None, password=None, duo=True)
52,051
uciwebauth.uciwebauth
__init__
null
def __init__(self, usrid=None, password=None, duo=True): app = 'duo' if duo else 'uciwebauth' self._login_url = WebAuth.LOGIN_URL.format(app) self._check_url = WebAuth.CHECK_URL self._logout_url = WebAuth.LOGOUT_URL if usrid: self.authenticate(usrid, password) else: self._clear()
(self, usrid=None, password=None, duo=True)
52,052
uciwebauth.uciwebauth
__str__
Return string with information about authenticated UCInetId.
def __str__(self): """Return string with information about authenticated UCInetId.""" s = [f'ucinetid_auth={self.ucinetid_auth}'] for attr in self.ATTRS: value = getattr(self, attr) if value is not None: s.append(f'{attr}={value}') return '\n'.join(s)
(self)
52,053
uciwebauth.uciwebauth
_clear
Initialize attributes to None.
def _clear(self): """Initialize attributes to None.""" self.ucinetid_auth = None for attr in self.ATTRS: setattr(self, attr, None)
(self)
52,054
uciwebauth.uciwebauth
_new_token
Authenticate username/password and get new ucinetid_auth token.
def _new_token(self, ucinetid, password): """Authenticate username/password and get new ucinetid_auth token.""" if password is None or not ucinetid or len(ucinetid) > 8: raise WebAuthError('Invalid ucinetid or password') data = urlencode( { 'ucinetid': ucinetid, 'password': password, 'return_url': '', 'referer': '', 'info_text': '', 'info_url': '', 'submit_type': '', 'return_auth_contexts': 'true', 'login_button': 'Login', } ).encode() request = Request(self._login_url, data, self.USER_AGENT) try: response = urlopen(request) except Exception as exc: raise WebAuthError('UCI webauth site not found') from exc try: cookie = response.info()['Set-Cookie'] if 'ucinetid_auth' not in cookie: raise ValueError() except Exception as exc: raise WebAuthError('Cookie not found') from exc ucinetid_auth = self._search_token(cookie) if not ucinetid_auth: raise WebAuthError('Authentication failed') return ucinetid_auth
(self, ucinetid, password)
52,055
uciwebauth.uciwebauth
_search_token
Return ucinetid_auth token from string.
def _search_token(self, search_string): """Return ucinetid_auth token from string.""" if search_string and len(search_string) >= 64: pattern = 'ucinetid_auth=' if len(search_string) > 64 else '' pattern += '([a-zA-Z0-9_]{64})' try: return re.search(pattern, search_string).group(1) except AttributeError: pass return None
(self, search_string)
52,056
uciwebauth.uciwebauth
authenticate
Get ucinetid_auth token. Usrid can be a UCInetId, a 64-byte WebAuth token or any string containing the token, e.g. HTTP QUERY_STRING or HTTP_COOKIE. Raise WebAuthError on failure.
def authenticate(self, usrid, password=None): """Get ucinetid_auth token. Usrid can be a UCInetId, a 64-byte WebAuth token or any string containing the token, e.g. HTTP QUERY_STRING or HTTP_COOKIE. Raise WebAuthError on failure. """ self._clear() if password is None and len(usrid) > 8: self.ucinetid_auth = self._search_token(usrid) else: self.ucinetid_auth = self._new_token(usrid, password) if not self.ucinetid_auth: raise WebAuthError('No valid ucinetid_auth token found') self.check()
(self, usrid, password=None)
52,057
uciwebauth.uciwebauth
check
Get data associated with ucinetid_auth token. Raise WebAuthError on failure.
def check(self): """Get data associated with ucinetid_auth token. Raise WebAuthError on failure. """ if not self.ucinetid_auth: return data = urlencode({'ucinetid_auth': self.ucinetid_auth}).encode() request = Request(self._check_url, data, self.USER_AGENT) try: response = urlopen(request).read() except Exception as exc: raise WebAuthError('UCI webauth_check site not found') from exc for line in response.splitlines(): line = line.decode() try: attr, value = line.strip().split('=') setattr(self, attr, self.ATTRS[attr](value)) except (KeyError, ValueError): pass if self.auth_fail: raise WebAuthError(self.auth_fail)
(self)
52,058
uciwebauth.uciwebauth
login_url
Return URL to log in to WebAuth.
def login_url(self, return_url=''): """Return URL to log in to WebAuth.""" return ( self._login_url + '?' + urlencode({'return_url': return_url}).replace('&', '&amp;') )
(self, return_url='')
52,059
uciwebauth.uciwebauth
logout
Clear ucinetid_auth entry in UCI WebAuth database.
def logout(self): """Clear ucinetid_auth entry in UCI WebAuth database.""" if not self.ucinetid_auth: return data = urlencode({'ucinetid_auth': self.ucinetid_auth}).encode() request = Request(self._logout_url, data, self.USER_AGENT) try: urlopen(request).read() except Exception: raise WebAuthError('UCI webauth_logout site not found') self._clear()
(self)
52,060
uciwebauth.uciwebauth
logout_url
Return URL to log out of WebAuth.
def logout_url(self, return_url=''): """Return URL to log out of WebAuth.""" return ( self._logout_url + '?' + urlencode( {'ucinetid_auth': self.ucinetid_auth, 'return_url': return_url} ).replace('&', '&amp;') )
(self, return_url='')
52,061
uciwebauth.uciwebauth
validate
Raise WebAuthError if no token, timeout, or host mismatch.
def validate(self, timeout=None, auth_host=None): """Raise WebAuthError if no token, timeout, or host mismatch.""" if not self.ucinetid_auth or len(self.ucinetid_auth) != 64: raise WebAuthError('Not logged in') if timeout is not None and self.age_in_seconds > timeout: raise WebAuthError('Authentication expired') if auth_host and self.auth_host != auth_host: raise WebAuthError( f'Host mismatch: ({self.auth_host} != {auth_host}' )
(self, timeout=None, auth_host=None)
52,062
uciwebauth.uciwebauth
WebAuthBackend
UCI WebAuth backend for use in web apps. Attributes ---------- auth : WebAuth ldap : LdapPerson or None LDAP record of authenticated user. username : str UCInetId or full name from LDAP of the authenticated user. ucinetid : str UCInetId of authenticated user. messages : list of str Messages returned by WebAuth and LdapPerson. url : str URL of the web app.
class WebAuthBackend: """UCI WebAuth backend for use in web apps. Attributes ---------- auth : WebAuth ldap : LdapPerson or None LDAP record of authenticated user. username : str UCInetId or full name from LDAP of the authenticated user. ucinetid : str UCInetId of authenticated user. messages : list of str Messages returned by WebAuth and LdapPerson. url : str URL of the web app. """ def __init__( self, request=None, url=None, usrid=None, useldap=True, timeout=None ): """Initialize backend from request.""" self.auth = WebAuth() self.ldap = None self.url = url self.messages = [] self.ucinetid = '' self.username = '' if request is None: # CGI request self.environ = os.environ remoteaddr = self.environ.get('REMOTE_ADDR') if url is None: self.url = self._script_url() else: # Flask request self.environ = request.environ if request.headers.getlist('X-Forwarded-For'): remoteaddr = request.headers.getlist('X-Forwarded-For')[0] else: remoteaddr = request.remote_addr if url is None: self.url = request.base_url if usrid is None: # look in query string and cookies usrid = '{} {}'.format( self.environ.get('QUERY_STRING'), self.environ.get('HTTP_COOKIE'), ) try: self.auth.authenticate(usrid) self.auth.validate(timeout=timeout, auth_host=remoteaddr) except WebAuthError as exc: self.messages.append(str(exc)) return self.ucinetid = self.username = self.auth.ucinetid if useldap: try: self.ldap = LdapPerson(self.auth.campus_id) if self.ldap.pretty_name: self.username = self.ldap.pretty_name except LdapPersonError as exc: self.username = self.ucinetid self.messages.append(str(exc)) def __str__(self): """Return HTML code for logging in to/out of UCI WebAuth.""" if self.messages: return ( '<a href="{}" title="Reason: {}">' 'Log in</a> with your UCInetId'.format( self.login_url(), escape(self.messages[0]) ) ) return ( 'Welcome, <strong>{}</strong> ' '[ <a href="{}">Log out</a> ]'.format( escape(self.username), self.logout_url() ) ) def login_url(self): """Return URL for logging in to UCI WebAuth system.""" return self.auth.login_url(self.url) def logout_url(self): """Return URL for logging out of UCI WebAuth system.""" return self.auth.logout_url(self.url) def logout(self): """Log out of UCI WebAuth.""" self.auth.logout() def _script_url(self, pretty_url=False): """Return URL of CGI script, without script file name if pretty_url.""" netloc = self.environ.get('SERVER_NAME') port = self.environ.get('SERVER_PORT') path = self.environ.get('SCRIPT_NAME') if port and port != '80': netloc += ':' + port if path is None: path = self.environ.get('PATH_INFO') if path is None: path = '' elif pretty_url: s = path.rsplit('/', 1) if '.' in s[-1]: path = '/'.join(s[:-1]) scheme = 'https' if (port and int(port) == 443) else 'http' url = urlunsplit([scheme, netloc, path, '', '']) url = url.replace(r'//', r'/').replace(r':/', '://') return url.lower()
(request=None, url=None, usrid=None, useldap=True, timeout=None)
52,063
uciwebauth.uciwebauth
__init__
Initialize backend from request.
def __init__( self, request=None, url=None, usrid=None, useldap=True, timeout=None ): """Initialize backend from request.""" self.auth = WebAuth() self.ldap = None self.url = url self.messages = [] self.ucinetid = '' self.username = '' if request is None: # CGI request self.environ = os.environ remoteaddr = self.environ.get('REMOTE_ADDR') if url is None: self.url = self._script_url() else: # Flask request self.environ = request.environ if request.headers.getlist('X-Forwarded-For'): remoteaddr = request.headers.getlist('X-Forwarded-For')[0] else: remoteaddr = request.remote_addr if url is None: self.url = request.base_url if usrid is None: # look in query string and cookies usrid = '{} {}'.format( self.environ.get('QUERY_STRING'), self.environ.get('HTTP_COOKIE'), ) try: self.auth.authenticate(usrid) self.auth.validate(timeout=timeout, auth_host=remoteaddr) except WebAuthError as exc: self.messages.append(str(exc)) return self.ucinetid = self.username = self.auth.ucinetid if useldap: try: self.ldap = LdapPerson(self.auth.campus_id) if self.ldap.pretty_name: self.username = self.ldap.pretty_name except LdapPersonError as exc: self.username = self.ucinetid self.messages.append(str(exc))
(self, request=None, url=None, usrid=None, useldap=True, timeout=None)
52,064
uciwebauth.uciwebauth
__str__
Return HTML code for logging in to/out of UCI WebAuth.
def __str__(self): """Return HTML code for logging in to/out of UCI WebAuth.""" if self.messages: return ( '<a href="{}" title="Reason: {}">' 'Log in</a> with your UCInetId'.format( self.login_url(), escape(self.messages[0]) ) ) return ( 'Welcome, <strong>{}</strong> ' '[ <a href="{}">Log out</a> ]'.format( escape(self.username), self.logout_url() ) )
(self)
52,065
uciwebauth.uciwebauth
_script_url
Return URL of CGI script, without script file name if pretty_url.
def _script_url(self, pretty_url=False): """Return URL of CGI script, without script file name if pretty_url.""" netloc = self.environ.get('SERVER_NAME') port = self.environ.get('SERVER_PORT') path = self.environ.get('SCRIPT_NAME') if port and port != '80': netloc += ':' + port if path is None: path = self.environ.get('PATH_INFO') if path is None: path = '' elif pretty_url: s = path.rsplit('/', 1) if '.' in s[-1]: path = '/'.join(s[:-1]) scheme = 'https' if (port and int(port) == 443) else 'http' url = urlunsplit([scheme, netloc, path, '', '']) url = url.replace(r'//', r'/').replace(r':/', '://') return url.lower()
(self, pretty_url=False)
52,066
uciwebauth.uciwebauth
login_url
Return URL for logging in to UCI WebAuth system.
def login_url(self): """Return URL for logging in to UCI WebAuth system.""" return self.auth.login_url(self.url)
(self)
52,067
uciwebauth.uciwebauth
logout
Log out of UCI WebAuth.
def logout(self): """Log out of UCI WebAuth.""" self.auth.logout()
(self)
52,068
uciwebauth.uciwebauth
logout_url
Return URL for logging out of UCI WebAuth system.
def logout_url(self): """Return URL for logging out of UCI WebAuth system.""" return self.auth.logout_url(self.url)
(self)
52,069
uciwebauth.uciwebauth
WebAuthError
Base class for errors in the WebAuth class.
class WebAuthError(Exception): """Base class for errors in the WebAuth class."""
null
52,071
tussik.zpl.zplconfig
ZplConfig
null
class ZplConfig: __slots__ = ['timeout', 'width', 'height', 'dpmm'] def __init__(self, timeout: Optional[int] = None, width: Union[None, float, int] = None, height: Union[None, float, int] = None, dpmm: Union[None, float, int] = None): self.timeout: int = min(500, max(1, timeout if isinstance(timeout, int) else 10)) self.width: float = float(min(100, max(1, width if isinstance(width, (int, float)) else 4))) self.height: float = float(min(100, max(1, height if isinstance(height, (int, float)) else 6))) self.dpmm: float = float(min(100, max(1, dpmm if isinstance(dpmm, (int, float)) else 8))) def copy(self) -> "ZplConfig": return ZplConfig(self.timeout, self.width, self.height, self.dpmm)
(timeout: Optional[int] = None, width: Union[NoneType, float, int] = None, height: Union[NoneType, float, int] = None, dpmm: Union[NoneType, float, int] = None)
52,072
tussik.zpl.zplconfig
__init__
null
def __init__(self, timeout: Optional[int] = None, width: Union[None, float, int] = None, height: Union[None, float, int] = None, dpmm: Union[None, float, int] = None): self.timeout: int = min(500, max(1, timeout if isinstance(timeout, int) else 10)) self.width: float = float(min(100, max(1, width if isinstance(width, (int, float)) else 4))) self.height: float = float(min(100, max(1, height if isinstance(height, (int, float)) else 6))) self.dpmm: float = float(min(100, max(1, dpmm if isinstance(dpmm, (int, float)) else 8)))
(self, timeout: Optional[int] = None, width: Union[NoneType, float, int] = None, height: Union[NoneType, float, int] = None, dpmm: Union[NoneType, float, int] = None)
52,073
tussik.zpl.zplconfig
copy
null
def copy(self) -> "ZplConfig": return ZplConfig(self.timeout, self.width, self.height, self.dpmm)
(self) -> tussik.zpl.zplconfig.ZplConfig
52,074
tussik.zpl.zplwriter
ZplWriter
null
class ZplWriter: __slots__ = ['_stream', '_attrib', '_config', '_font', '_reverse'] def __init__(self, config: Optional[ZplConfig] = None): self._attrib: List[str] = [] self._stream: List[str] = [] self._font: str = '' self._reverse: str = '' self._config: ZplConfig = config.copy() if isinstance(config, ZplConfig) else ZplConfig() def export(self) -> str: config = "".join(self._attrib) stream = "".join(self._stream) return f"^XA^MT{config}{stream}^XZ" def clear(self): self._stream: List[str] = [] def add(self, command: str): self._stream.append(command) def coordinates(self, left: int, top: int) -> (int, int): left = min(max(int(left * self._config.dpmm), 0), 32000) top = min(max(int(top * self._config.dpmm), 0), 32000) return left, top def to_reverse(self): self._reverse = "^FR" def to_normal(self): self._reverse = "" def print(self, ipaddress: str, port: int = 9100) -> bool: mysocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: mysocket.settimeout(self._config.timeout) mysocket.connect((ipaddress, port)) # connecting to host content = self.export() payload = bytes(content, "utf8") mysocket.send(payload) mysocket.close() except OSError as e: logger.exception(f"Unable to connect to {ipaddress}:{port}") return False except Exception as e: logger.exception("Error with the connection") return False return True def saveas(self, destination: Union[str, io.BytesIO]) -> bool: # # uses a 3rd party service not affiliated with this library in any way # url = f"http://api.labelary.com/v1/printers/{int(self._config.dpmm)}dpmm/labels" \ f"/{int(self._config.width)}x{int(self._config.height)}/0/" headers = {'Accept': 'application/pdf'} response = requests.post(url, self.export(), headers=headers) if response.status_code == 200: if isinstance(destination, str): with open(destination, 'wb') as f: f.write(response.content) else: destination.write(response.content) return True logging.error(response.content) return False def textblock(self, left: int = 0, top: int = 0, data: str = "", width: int = 0, justify: str = "J", maxlines: int = 1) -> bool: left = min(max(int(left * self._config.dpmm), 0), 32000) top = min(max(int(top * self._config.dpmm), 0), 32000) justify = justify.upper() if justify not in ['L', 'C', 'R', 'J']: return False width = max(0, int(width * self._config.dpmm)) self.add(f"^FO{left},{top}{self._font}{self._reverse}" f"^FB{width},{maxlines},0,{justify},0^FD{data}^FS") return True def font(self, height: int = 10, width: Optional[int] = None, flip: int = 0, fontcode: str = "0", isdefault: bool = False): height = int(min(max(height * self._config.dpmm, 0), 32000)) if isinstance(width, int): width = int(min(max(width * self._config.dpmm, 0), 32000)) if flip >= 270: orient = "B" elif flip >= 180: orient = "I" elif flip >= 90: orient = "R" else: orient = "N" if width is None: self._font = f"^A{fontcode}{orient},{height}" if isdefault: self.add(f'^CF{fontcode},{height}') else: self._font = f"^A{fontcode}{orient},{height},{width}" if isdefault: self.add(f'^CF{fontcode},{height},{width}') def text(self, data: str, left: int = 0, top: int = 0): left = min(max(int(left * self._config.dpmm), 0), 32000) top = min(max(int(top * self._config.dpmm), 0), 32000) self.add(f"^FO{left},{top}{self._font}{self._reverse}^FD{data}^FS") def ellipse(self, left: int = 0, top: int = 0, width: int = 100, height: int = 100, thick: int = 2): width = int(min(max(width * self._config.dpmm, 3), 4095)) height = int(min(max(height * self._config.dpmm, 3), 4095)) thick = int(min(max(thick, 2), 4095)) left = min(max(int(left * self._config.dpmm), 0), 32000) top = min(max(int(top * self._config.dpmm), 0), 32000) self.add(f"^FO{left},{top}{self._reverse}^GE{width},{height},{thick},B^FS") def circle(self, left: int = 0, top: int = 0, diameter: int = 100, thick: int = 2): diameter = int(min(max(diameter * self._config.dpmm, 3), 4095)) thick = int(min(max(thick, 2), 4095)) left = min(max(int(left * self._config.dpmm), 0), 32000) top = min(max(int(top * self._config.dpmm), 0), 32000) self.add(f"^FO{left},{top}{self._reverse}^GC{diameter},{thick},B^FS") def box(self, left: int = 0, top: int = 0, width: int = 100, height: int = 100, thick: float = 2, round: int = 0): thick = int(min(max(1, int(thick * self._config.dpmm)), 32000)) width = int(min(max(thick, int(width * self._config.dpmm)), 32000)) height = int(min(max(thick, int(height * self._config.dpmm)), 32000)) round = int(min(max(0, round), 8)) left = min(max(int(left * self._config.dpmm), 0), 32000) top = min(max(int(top * self._config.dpmm), 0), 32000) self.add(f"^FO{left},{top}{self._reverse}^GB{width},{height},{thick},B,{round}^FS") def hline(self, left: int = 0, top: int = 0, width: int = 100, thick: int = 2): thick = int(min(max(1, int(thick * self._config.dpmm)), 32000)) width = int(min(max(thick, int(width * self._config.dpmm)), 32000)) height = max(thick, 0) left = min(max(int(left * self._config.dpmm), 0), 32000) top = min(max(int(top * self._config.dpmm), 0), 32000) self.add(f"^FO{left},{top}{self._reverse}^GB{width},{height},{thick},B,0^FS") def vline(self, left: int = 0, top: int = 0, height: int = 100, thick: int = 2): thick = int(min(max(1, int(thick * self._config.dpmm)), 32000)) width = max(thick, 0) height = int(min(max(thick, int(height * self._config.dpmm)), 32000)) left = min(max(int(left * self._config.dpmm), 0), 32000) top = min(max(int(top * self._config.dpmm), 0), 32000) self.add(f"^FO{left},{top}{self._reverse}^GB{width},{height},{thick},B,0^FS") def image(self, image: Union[str, Image], left: int = 0, top: int = 0, width: Optional[int] = None, height: Optional[int] = None) -> bool: if Image is None: raise Exception("Developer! pillow library is required for ZplWriter.image") try: left = min(max(int(left * self._config.dpmm), 0), 32000) top = min(max(int(top * self._config.dpmm), 0), 32000) if isinstance(image, str): rc = requests.get(image, stream=True) if not rc.ok: return False image = Image.open(rc.raw) if width is None: width = int(image.size[0]) if height is None: # maintain aspect ratio height = int(float(image.size[1]) / image.size[0] * width) width = width * self._config.dpmm height = height * self._config.dpmm totalbytes = math.ceil(width / 8.0) * height bytesperrow = math.ceil(width / 8.0) image = image.resize((int(width), int(height))) image = ImageOps.invert(image.convert('L')).convert('1') data = image.tobytes().hex().upper() self.add(f"^FO{left},{top}^GFA,{len(data)},{totalbytes},{bytesperrow},{data}") return True except Exception as e: logger.exception("failed to load image") return False def qrcode(self, left: int = 0, top: int = 0, data: Union[str, dict, list, int, float, None] = None, magnify: Optional[int] = None) -> None: if data is None: return elif isinstance(data, str): content = data elif isinstance(data, (int, float)): content = str(data) else: content = json.dumps(data) if magnify is None: magnify = '' left, top = self.coordinates(left, top) self.add(f"^FO{left},{top}^BQ,2,{magnify},H^FDQA,{content}^FS") def orientation(self, rotate: int = 0, justify: int = 2) -> None: if rotate < 90: rotate = 0 elif rotate < 180: rotate = 90 elif rotate < 270: rotate = 180 else: rotate = 270 justify = min(2, max(0, justify)) self.add(f"^FW{rotate},{justify}") def label_reverse(self, reverse: bool = False): a = "Y" if reverse else "N" self.add(f"^LR{a}") def label_length(self, length: int): len = int(min(32000, max(1, length)) * self._config.dpmm) self.add(f"^LL{len}") def cut(self, kiosk_cut_amount: bool = True): a = "0" if kiosk_cut_amount else "1" self.add(f"^CN{a}")
(config: Optional[tussik.zpl.zplconfig.ZplConfig] = None)
52,075
tussik.zpl.zplwriter
__init__
null
def __init__(self, config: Optional[ZplConfig] = None): self._attrib: List[str] = [] self._stream: List[str] = [] self._font: str = '' self._reverse: str = '' self._config: ZplConfig = config.copy() if isinstance(config, ZplConfig) else ZplConfig()
(self, config: Optional[tussik.zpl.zplconfig.ZplConfig] = None)
52,076
tussik.zpl.zplwriter
add
null
def add(self, command: str): self._stream.append(command)
(self, command: str)
52,077
tussik.zpl.zplwriter
box
null
def box(self, left: int = 0, top: int = 0, width: int = 100, height: int = 100, thick: float = 2, round: int = 0): thick = int(min(max(1, int(thick * self._config.dpmm)), 32000)) width = int(min(max(thick, int(width * self._config.dpmm)), 32000)) height = int(min(max(thick, int(height * self._config.dpmm)), 32000)) round = int(min(max(0, round), 8)) left = min(max(int(left * self._config.dpmm), 0), 32000) top = min(max(int(top * self._config.dpmm), 0), 32000) self.add(f"^FO{left},{top}{self._reverse}^GB{width},{height},{thick},B,{round}^FS")
(self, left: int = 0, top: int = 0, width: int = 100, height: int = 100, thick: float = 2, round: int = 0)
52,078
tussik.zpl.zplwriter
circle
null
def circle(self, left: int = 0, top: int = 0, diameter: int = 100, thick: int = 2): diameter = int(min(max(diameter * self._config.dpmm, 3), 4095)) thick = int(min(max(thick, 2), 4095)) left = min(max(int(left * self._config.dpmm), 0), 32000) top = min(max(int(top * self._config.dpmm), 0), 32000) self.add(f"^FO{left},{top}{self._reverse}^GC{diameter},{thick},B^FS")
(self, left: int = 0, top: int = 0, diameter: int = 100, thick: int = 2)
52,079
tussik.zpl.zplwriter
clear
null
def clear(self): self._stream: List[str] = []
(self)
52,080
tussik.zpl.zplwriter
coordinates
null
def coordinates(self, left: int, top: int) -> (int, int): left = min(max(int(left * self._config.dpmm), 0), 32000) top = min(max(int(top * self._config.dpmm), 0), 32000) return left, top
(self, left: int, top: int) -> (<class 'int'>, <class 'int'>)
52,081
tussik.zpl.zplwriter
cut
null
def cut(self, kiosk_cut_amount: bool = True): a = "0" if kiosk_cut_amount else "1" self.add(f"^CN{a}")
(self, kiosk_cut_amount: bool = True)
52,082
tussik.zpl.zplwriter
ellipse
null
def ellipse(self, left: int = 0, top: int = 0, width: int = 100, height: int = 100, thick: int = 2): width = int(min(max(width * self._config.dpmm, 3), 4095)) height = int(min(max(height * self._config.dpmm, 3), 4095)) thick = int(min(max(thick, 2), 4095)) left = min(max(int(left * self._config.dpmm), 0), 32000) top = min(max(int(top * self._config.dpmm), 0), 32000) self.add(f"^FO{left},{top}{self._reverse}^GE{width},{height},{thick},B^FS")
(self, left: int = 0, top: int = 0, width: int = 100, height: int = 100, thick: int = 2)
52,083
tussik.zpl.zplwriter
export
null
def export(self) -> str: config = "".join(self._attrib) stream = "".join(self._stream) return f"^XA^MT{config}{stream}^XZ"
(self) -> str
52,084
tussik.zpl.zplwriter
font
null
def font(self, height: int = 10, width: Optional[int] = None, flip: int = 0, fontcode: str = "0", isdefault: bool = False): height = int(min(max(height * self._config.dpmm, 0), 32000)) if isinstance(width, int): width = int(min(max(width * self._config.dpmm, 0), 32000)) if flip >= 270: orient = "B" elif flip >= 180: orient = "I" elif flip >= 90: orient = "R" else: orient = "N" if width is None: self._font = f"^A{fontcode}{orient},{height}" if isdefault: self.add(f'^CF{fontcode},{height}') else: self._font = f"^A{fontcode}{orient},{height},{width}" if isdefault: self.add(f'^CF{fontcode},{height},{width}')
(self, height: int = 10, width: Optional[int] = None, flip: int = 0, fontcode: str = '0', isdefault: bool = False)
52,085
tussik.zpl.zplwriter
hline
null
def hline(self, left: int = 0, top: int = 0, width: int = 100, thick: int = 2): thick = int(min(max(1, int(thick * self._config.dpmm)), 32000)) width = int(min(max(thick, int(width * self._config.dpmm)), 32000)) height = max(thick, 0) left = min(max(int(left * self._config.dpmm), 0), 32000) top = min(max(int(top * self._config.dpmm), 0), 32000) self.add(f"^FO{left},{top}{self._reverse}^GB{width},{height},{thick},B,0^FS")
(self, left: int = 0, top: int = 0, width: int = 100, thick: int = 2)
52,086
tussik.zpl.zplwriter
image
null
def image(self, image: Union[str, Image], left: int = 0, top: int = 0, width: Optional[int] = None, height: Optional[int] = None) -> bool: if Image is None: raise Exception("Developer! pillow library is required for ZplWriter.image") try: left = min(max(int(left * self._config.dpmm), 0), 32000) top = min(max(int(top * self._config.dpmm), 0), 32000) if isinstance(image, str): rc = requests.get(image, stream=True) if not rc.ok: return False image = Image.open(rc.raw) if width is None: width = int(image.size[0]) if height is None: # maintain aspect ratio height = int(float(image.size[1]) / image.size[0] * width) width = width * self._config.dpmm height = height * self._config.dpmm totalbytes = math.ceil(width / 8.0) * height bytesperrow = math.ceil(width / 8.0) image = image.resize((int(width), int(height))) image = ImageOps.invert(image.convert('L')).convert('1') data = image.tobytes().hex().upper() self.add(f"^FO{left},{top}^GFA,{len(data)},{totalbytes},{bytesperrow},{data}") return True except Exception as e: logger.exception("failed to load image") return False
(self, image: Optional[str], left: int = 0, top: int = 0, width: Optional[int] = None, height: Optional[int] = None) -> bool
52,087
tussik.zpl.zplwriter
label_length
null
def label_length(self, length: int): len = int(min(32000, max(1, length)) * self._config.dpmm) self.add(f"^LL{len}")
(self, length: int)
52,088
tussik.zpl.zplwriter
label_reverse
null
def label_reverse(self, reverse: bool = False): a = "Y" if reverse else "N" self.add(f"^LR{a}")
(self, reverse: bool = False)
52,089
tussik.zpl.zplwriter
orientation
null
def orientation(self, rotate: int = 0, justify: int = 2) -> None: if rotate < 90: rotate = 0 elif rotate < 180: rotate = 90 elif rotate < 270: rotate = 180 else: rotate = 270 justify = min(2, max(0, justify)) self.add(f"^FW{rotate},{justify}")
(self, rotate: int = 0, justify: int = 2) -> NoneType
52,090
tussik.zpl.zplwriter
print
null
def print(self, ipaddress: str, port: int = 9100) -> bool: mysocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: mysocket.settimeout(self._config.timeout) mysocket.connect((ipaddress, port)) # connecting to host content = self.export() payload = bytes(content, "utf8") mysocket.send(payload) mysocket.close() except OSError as e: logger.exception(f"Unable to connect to {ipaddress}:{port}") return False except Exception as e: logger.exception("Error with the connection") return False return True
(self, ipaddress: str, port: int = 9100) -> bool
52,091
tussik.zpl.zplwriter
qrcode
null
def qrcode(self, left: int = 0, top: int = 0, data: Union[str, dict, list, int, float, None] = None, magnify: Optional[int] = None) -> None: if data is None: return elif isinstance(data, str): content = data elif isinstance(data, (int, float)): content = str(data) else: content = json.dumps(data) if magnify is None: magnify = '' left, top = self.coordinates(left, top) self.add(f"^FO{left},{top}^BQ,2,{magnify},H^FDQA,{content}^FS")
(self, left: int = 0, top: int = 0, data: Union[str, dict, list, int, float, NoneType] = None, magnify: Optional[int] = None) -> NoneType
52,092
tussik.zpl.zplwriter
saveas
null
def saveas(self, destination: Union[str, io.BytesIO]) -> bool: # # uses a 3rd party service not affiliated with this library in any way # url = f"http://api.labelary.com/v1/printers/{int(self._config.dpmm)}dpmm/labels" \ f"/{int(self._config.width)}x{int(self._config.height)}/0/" headers = {'Accept': 'application/pdf'} response = requests.post(url, self.export(), headers=headers) if response.status_code == 200: if isinstance(destination, str): with open(destination, 'wb') as f: f.write(response.content) else: destination.write(response.content) return True logging.error(response.content) return False
(self, destination: Union[str, _io.BytesIO]) -> bool
52,093
tussik.zpl.zplwriter
text
null
def text(self, data: str, left: int = 0, top: int = 0): left = min(max(int(left * self._config.dpmm), 0), 32000) top = min(max(int(top * self._config.dpmm), 0), 32000) self.add(f"^FO{left},{top}{self._font}{self._reverse}^FD{data}^FS")
(self, data: str, left: int = 0, top: int = 0)
52,094
tussik.zpl.zplwriter
textblock
null
def textblock(self, left: int = 0, top: int = 0, data: str = "", width: int = 0, justify: str = "J", maxlines: int = 1) -> bool: left = min(max(int(left * self._config.dpmm), 0), 32000) top = min(max(int(top * self._config.dpmm), 0), 32000) justify = justify.upper() if justify not in ['L', 'C', 'R', 'J']: return False width = max(0, int(width * self._config.dpmm)) self.add(f"^FO{left},{top}{self._font}{self._reverse}" f"^FB{width},{maxlines},0,{justify},0^FD{data}^FS") return True
(self, left: int = 0, top: int = 0, data: str = '', width: int = 0, justify: str = 'J', maxlines: int = 1) -> bool
52,095
tussik.zpl.zplwriter
to_normal
null
def to_normal(self): self._reverse = ""
(self)
52,096
tussik.zpl.zplwriter
to_reverse
null
def to_reverse(self): self._reverse = "^FR"
(self)
52,097
tussik.zpl.zplwriter
vline
null
def vline(self, left: int = 0, top: int = 0, height: int = 100, thick: int = 2): thick = int(min(max(1, int(thick * self._config.dpmm)), 32000)) width = max(thick, 0) height = int(min(max(thick, int(height * self._config.dpmm)), 32000)) left = min(max(int(left * self._config.dpmm), 0), 32000) top = min(max(int(top * self._config.dpmm), 0), 32000) self.add(f"^FO{left},{top}{self._reverse}^GB{width},{height},{thick},B,0^FS")
(self, left: int = 0, top: int = 0, height: int = 100, thick: int = 2)
52,102
segindex.segregation_index
estimate_Hp
Arguments: vv_s (List[List[values]]): list of lists of values ww_s: weights over vv_s K: counts of thresholds m: degree of regression equation used for the estimation
def estimate_Hp(vv_s: List[List[Any]], ww_s=None, K=14, m=4): ''' Arguments: vv_s (List[List[values]]): list of lists of values ww_s: weights over vv_s K: counts of thresholds m: degree of regression equation used for the estimation ''' vv_s = from_vvs_to_rrs(vv_s, ww_s=ww_s) # rank-order transformation kk = np.array([e/K for e in range(1,K)]) # 1/K ~ (K-1)/K e_kk = np.array([entropy_p(k) for k in kk]) w_kk = e_kk**2 # tt = [len(vv) for vv in vv_s] Hp_kk = [] for k in kk: pp = [] for vv in vv_s: vv_k = [e for e in vv if e<=k] pp.append(len(vv_k)/len(vv)) Hp_k = Theil_p(tt,pp) Hp_kk.append(Hp_k) # d = pd.DataFrame({'Hp':Hp_kk, 'p':kk, 'weight': w_kk}) for n in range(2,m+1): d[f"p_{n}"] = d['p']**n exog = d[[c for c in d.columns if 'p' in c and 'Hp' not in c]] exog = sm.add_constant(exog) global f f = sm.WLS(endog=d['Hp'], exog=exog, weights=d['weight']).fit() # betas = [f.params['const'], f.params['p']] for n in range(2,m+1): betas.append(f.params[f"p_{n}"]) # deltas = [delta_m(e) for e in range(m+1)] betas, deltas = map(np.array, [betas, deltas]) # H_r = np.sum(betas*deltas) return H_r
(vv_s: List[List[Any]], ww_s=None, K=14, m=4)