docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Search word from FM-index Params: <str> | <Sequential> query <bool> _or <list <str> > ignores Return: <list>SEARCH_RESULT(<int> document_id, <list <int> > counts <str> doc)
def search(self, query, _or=False, ignores=[]): if isinstance(query, str): dids = MapIntInt({}) self.fm.search(query, dids) dids = dids.asdict() result = [] for did in sorted(dids.keys()): doc = self.fm.get_document(did) if not any(ignore in doc for ignore in ignores): count = dids[did] result.append(SEARCH_RESULT(int(did), [count], doc)) return result search_results = [] for q in query: dids = MapIntInt({}) self.fm.search(q, dids) search_results.append(dids.asdict()) merged_dids = self._merge_search_result(search_results, _or) result = [] for did in merged_dids: doc = self.fm.get_document(did) if not any(ignore in doc for ignore in ignores): counts = map(lambda x: int(x.pop(did, 0)), search_results) result.append(SEARCH_RESULT(int(did), list(counts), doc)) return result
991,750
Count word from FM-index Params: <str> | <Sequential> query <bool> _or <list <str> > ignores Return: <int> counts
def count(self, query, _or=False): if isinstance(query, str): return self.fm.count(query, MapIntInt({})) else: search_results = [] for q in query: dids = MapIntInt({}) self.fm.search(q, dids) search_results.append(dids.asdict()) merged_dids = self._merge_search_result(search_results, _or) counts = 0 for did in merged_dids: if _or: counts += reduce(add, [int(x.pop(did, 0)) for x in search_results]) else: counts += min([int(x.pop(did, 0)) for x in search_results]) return counts
991,751
Handles token authentication for Neurio Client. Args: key (string): your Neurio API key secret (string): your Neurio API secret
def __init__(self, key, secret): self.__key = key self.__secret = secret if self.__key is None or self.__secret is None: raise ValueError("Key and secret must be set.")
992,192
The Neurio API client. Args: token_provider (TokenProvider): object providing authentication services
def __init__(self, token_provider): if token_provider is None: raise ValueError("token_provider is required") if not isinstance(token_provider, TokenProvider): raise ValueError("token_provider must be instance of TokenProvider") self.__token = token_provider.get_token()
992,194
Get the information for a specified appliance Args: appliance_id (string): identifiying string of appliance Returns: list: dictionary object containing information about the specified appliance
def get_appliance(self, appliance_id): url = "https://api.neur.io/v1/appliances/%s"%(appliance_id) headers = self.__gen_headers() headers["Content-Type"] = "application/json" r = requests.get(url, headers=headers) return r.json()
992,196
Get the appliances added for a specified location. Args: location_id (string): identifiying string of appliance Returns: list: dictionary objects containing appliances data
def get_appliances(self, location_id): url = "https://api.neur.io/v1/appliances" headers = self.__gen_headers() headers["Content-Type"] = "application/json" params = { "locationId": location_id, } url = self.__append_url_params(url, params) r = requests.get(url, headers=headers) return r.json()
992,197
Gets current sample from *local* Neurio device IP address. This is a static method. It doesn't require a token to authenticate. Note, call get_user_information to determine local Neurio IP addresses. Args: ip (string): address of local Neurio device Returns: dictionary object containing current sample information
def get_local_current_sample(ip): valid_ip_pat = re.compile( "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$" ) if not valid_ip_pat.match(ip): raise ValueError("ip address invalid") url = "http://%s/current-sample" % (ip) headers = { "Content-Type": "application/json" } r = requests.get(url, headers=headers) return r.json()
992,200
Get recent samples, one sample per second for up to the last 2 minutes. Args: sensor_id (string): hexadecimal id of the sensor to query, e.g. ``0x0013A20040B65FAD`` last (string): starting range, as ISO8601 timestamp Returns: list: dictionary objects containing sample data
def get_samples_live(self, sensor_id, last=None): url = "https://api.neur.io/v1/samples/live" headers = self.__gen_headers() headers["Content-Type"] = "application/json" params = { "sensorId": sensor_id } if last: params["last"] = last url = self.__append_url_params(url, params) r = requests.get(url, headers=headers) return r.json()
992,201
Get the last sample recorded by the sensor. Args: sensor_id (string): hexadecimal id of the sensor to query, e.g. ``0x0013A20040B65FAD`` Returns: list: dictionary objects containing sample data
def get_samples_live_last(self, sensor_id): url = "https://api.neur.io/v1/samples/live/last" headers = self.__gen_headers() headers["Content-Type"] = "application/json" params = { "sensorId": sensor_id } url = self.__append_url_params(url, params) r = requests.get(url, headers=headers) return r.json()
992,202
Gets the current user information, including sensor ID Args: None Returns: dictionary object containing information about the current user
def get_user_information(self): url = "https://api.neur.io/v1/users/current" headers = self.__gen_headers() headers["Content-Type"] = "application/json" r = requests.get(url, headers=headers) return r.json()
992,204
A simple wrapper function that creates a handler function by using on the retry_loop function. Args: retries (Integral): The number of times to retry if a failure occurs. delay (timedelta, optional, 0 seconds): A timedelta representing the amount time to delay between retries. conditions (list): A list of retry conditions. Returns: function: The retry_loop function partialed.
def retry_handler(retries=0, delay=timedelta(), conditions=[]): delay_in_seconds = delay.total_seconds() return partial(retry_loop, retries, delay_in_seconds, conditions)
992,576
A decorator for making a function that retries on failure. Args: retries (Integral): The number of times to retry if a failure occurs. delay (timedelta, optional, 0 seconds): A timedelta representing the amount of time to delay between retries. conditions (list): A list of retry conditions.
def retry(retries=0, delay=timedelta(), conditions=[]): delay_in_seconds = delay.total_seconds() def decorator(function): @wraps(function) def wrapper(*args, **kwargs): func = partial(function, *args, **kwargs) return retry_loop(retries, delay_in_seconds, conditions, func) return wrapper return decorator
992,577
Returns a retry condition which will run the supplied function in either on_value or on_exception depending if kind == 'exception' or 'value' Args: function: The function to run. kind: the type of condition exception or value based.
def __init__(self, function, kind='exception'): self._function = function self._kind = kind if kind != 'exception' and kind != 'value': raise ValueError(kind)
992,579
Latest trading day w.r.t given dt Args: dt: date of reference cal: trading calendar Returns: pd.Timestamp: last trading day Examples: >>> trade_day('2018-12-25').strftime('%Y-%m-%d') '2018-12-24'
def trade_day(dt, cal='US'): from xone import calendar dt = pd.Timestamp(dt).date() return calendar.trading_dates(start=dt - pd.Timedelta('10D'), end=dt, calendar=cal)[-1]
992,690
on axes plot the signal contributions args: :: ax : matplotlib.axes.AxesSubplot object z : np.ndarray T : list, [tstart, tstop], which timeinterval ylims : list, set range of yaxis to scale with other plots fancy : bool, scaling_factor : float, scaling factor (e.g. to scale 10% data set up)
def plot_signal_sum(ax, z, fname='LFPsum.h5', unit='mV', ylabels=True, scalebar=True, vlimround=None, T=[0, 1000], color='k', label=''): #open file and get data, samplingrate f = h5py.File(fname) data = f['data'].value dataT = data.T - data.mean(axis=1) data = dataT.T srate = f['srate'].value #close file object f.close() # normalize data for plot tvec = np.arange(data.shape[1]) * 1000. / srate slica = (tvec <= T[1]) & (tvec >= T[0]) zvec = np.r_[z] zvec = np.r_[zvec, zvec[-1] + np.diff(zvec)[-1]] vlim = abs(data[:, slica]).max() if vlimround is None: vlimround = 2.**np.round(np.log2(vlim)) yticklabels=[] yticks = [] colors = [color]*data.shape[0] for i, z in enumerate(z): if i == 0: ax.plot(tvec[slica], data[i, slica] * 100 / vlimround + z, color=colors[i], rasterized=False, label=label, clip_on=False) else: ax.plot(tvec[slica], data[i, slica] * 100 / vlimround + z, color=colors[i], rasterized=False, clip_on=False) yticklabels.append('ch. %i' % (i+1)) yticks.append(z) if scalebar: ax.plot([tvec[slica][-1], tvec[slica][-1]], [-0, -100], lw=2, color='k', clip_on=False) ax.text(tvec[slica][-1]+np.diff(T)*0.02, -50, r'%g %s' % (vlimround, unit), color='k', rotation='vertical') ax.axis(ax.axis('tight')) ax.yaxis.set_ticks(yticks) if ylabels: ax.yaxis.set_ticklabels(yticklabels) else: ax.yaxis.set_ticklabels([]) for loc, spine in ax.spines.items(): if loc in ['right', 'top']: spine.set_color('none') ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.set_xlabel(r'time (ms)', labelpad=0)
992,736
mls on axes plot the correlation between x0 and x1 args: :: x0 : first dataset x1 : second dataset - e.g., the multichannel LFP ax : matplotlib.axes.AxesSubplot object title : text to be used as current axis object title
def plot_correlation(z_vec, x0, x1, ax, lag=20., title='firing_rate vs LFP'): zvec = np.r_[z_vec] zvec = np.r_[zvec, zvec[-1] + np.diff(zvec)[-1]] xcorr_all=np.zeros((np.size(z_vec), x0.shape[0])) for i, z in enumerate(z_vec): x2 = x1[i, ] xcorr1 = np.correlate(normalize(x0), normalize(x2), 'same') / x0.size xcorr_all[i,:]=xcorr1 # Find limits for the plot vlim = abs(xcorr_all).max() vlimround = 2.**np.round(np.log2(vlim)) yticklabels=[] yticks = [] ylimfound=np.zeros((1,2)) for i, z in enumerate(z_vec): ind = np.arange(x0.size) - x0.size/2 ax.plot(ind, xcorr_all[i,::-1] * 100. / vlimround + z, 'k', clip_on=True, rasterized=False) yticklabels.append('ch. %i' %(i+1)) yticks.append(z) remove_axis_junk(ax) ax.set_title(title) ax.set_xlabel(r'lag $\tau$ (ms)') ax.set_xlim(-lag, lag) ax.set_ylim(z-100, 100) axis = ax.axis() ax.vlines(0, axis[2], axis[3], 'r', 'dotted') ax.yaxis.set_ticks(yticks) ax.yaxis.set_ticklabels(yticklabels) ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') # Create a scaling bar ax.plot([lag, lag], [0, 100], lw=2, color='k', clip_on=False) ax.text(lag, 50, r'CC=%.2f' % vlimround, rotation='vertical', va='center')
992,743
Decorator to profile functions with cProfile Args: func: python function Returns: profile report References: https://osf.io/upav8/
def profile(func): def inner(*args, **kwargs): pr = cProfile.Profile() pr.enable() res = func(*args, **kwargs) pr.disable() s = io.StringIO() ps = pstats.Stats(pr, stream=s).sort_stats('cumulative') ps.print_stats() print(s.getvalue()) return res return inner
992,813
Represent a number-string in the form of a tuple of digits. "868.0F" -> (8, 6, 8, '.', 0, 15) Args: string - Number represented as a string of digits. Returns: Number represented as an iterable container of digits >>> represent_as_tuple('868.0F') (8, 6, 8, '.', 0, 15)
def represent_as_tuple(string): keep = (".", "[", "]") return tuple(str_digit_to_int(c) if c not in keep else c for c in string)
992,995
Represent a number in the form of a string. (8, 6, 8, '.', 0, 15) -> "868.0F" Args: iterable - Number represented as an iterable container of digits. Returns: Number represented as a string of digits. >>> represent_as_string((8, 6, 8, '.', 0, 15)) '868.0F'
def represent_as_string(iterable): keep = (".", "[", "]") return "".join(tuple(int_to_str_digit(i) if i not in keep else i for i in iterable))
992,996
Returns a tuple of the integer and fractional parts of a number. Args: number(iterable container): A number in the following form: (..., ".", int, int, int, ...) Returns: (integer_part, fractional_part): tuple. Example: >>> integer_fractional_parts((1,2,3,".",4,5,6)) ((1, 2, 3), ('.', 4, 5, 6))
def integer_fractional_parts(number): radix_point = number.index(".") integer_part = number[:radix_point] fractional_part = number[radix_point:] return(integer_part, fractional_part)
992,999
Converts a decimal integer to a specific base. Args: decimal(int) A base 10 number. output_base(int) base to convert to. Returns: A tuple of digits in the specified base. Examples: >>> from_base_10_int(255) (2, 5, 5) >>> from_base_10_int(255, 16) (15, 15) >>> from_base_10_int(9988664439, 8) (1, 1, 2, 3, 2, 7, 5, 6, 6, 1, 6, 7) >>> from_base_10_int(0, 17) (0,)
def from_base_10_int(decimal, output_base=10): if decimal <= 0: return (0,) if output_base == 1: return (1,) * decimal length = digits(decimal, output_base) converted = tuple(digit(decimal, i, output_base) for i in range(length)) return converted[::-1]
993,000
Converts an integer in any base into it's decimal representation. Args: n - An integer represented as a tuple of digits in the specified base. input_base - the base of the input number. Returns: integer converted into base 10. Example: >>> to_base_10_int((8,1), 16) 129
def to_base_10_int(n, input_base): return sum(c * input_base ** i for i, c in enumerate(n[::-1]))
993,001
Removes trailing zeros. Args: n: The number to truncate. This number should be in the following form: (..., '.', int, int, int, ..., 0) Returns: n with all trailing zeros removed >>> truncate((9, 9, 9, '.', 9, 9, 9, 9, 0, 0, 0, 0)) (9, 9, 9, '.', 9, 9, 9, 9) >>> truncate(('.',)) ('.',)
def truncate(n): count = 0 for digit in n[-1::-1]: if digit != 0: break count += 1 return n[:-count] if count > 0 else n
993,003
Converts a string character to a decimal number. Where "A"->10, "B"->11, "C"->12, ...etc Args: chr(str): A single character in the form of a string. Returns: The integer value of the input string digit.
def str_digit_to_int(chr): # 0 - 9 if chr in ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9"): n = int(chr) else: n = ord(chr) # A - Z if n < 91: n -= 55 # a - z or higher else: n -= 61 return n
993,004
Converts a positive integer, to a single string character. Where: 9 -> "9", 10 -> "A", 11 -> "B", 12 -> "C", ...etc Args: n(int): A positve integer number. Returns: The character representation of the input digit of value n (str).
def int_to_str_digit(n): # 0 - 9 if n < 10: return str(n) # A - Z elif n < 36: return chr(n + 55) # a - z or higher else: return chr(n + 61)
993,005
Expands a recurring pattern within a number. Args: number(tuple): the number to process in the form: (int, int, int, ... ".", ... , int int int) repeat: the number of times to expand the pattern. Returns: The original number with recurring pattern expanded. Example: >>> expand_recurring((1, ".", 0, "[", 9, "]"), repeat=3) (1, '.', 0, 9, 9, 9, 9)
def expand_recurring(number, repeat=5): if "[" in number: pattern_index = number.index("[") pattern = number[pattern_index + 1:-1] number = number[:pattern_index] number = number + pattern * (repeat + 1) return number
993,007
Provide interface for multiprocessing Args: func: callable functions keys: keys in kwargs that want to use process max_procs: max number of processes show_proc: whether to show process affinity: CPU affinity **kwargs: kwargs for func
def run(func, keys, max_procs=None, show_proc=False, affinity=None, **kwargs): if max_procs is None: max_procs = cpu_count() kw_arr = saturate_kwargs(keys=keys, **kwargs) if len(kw_arr) == 0: return if isinstance(affinity, int): win32process.SetProcessAffinityMask(win32api.GetCurrentProcess(), affinity) task_queue = queue.Queue() while len(kw_arr) > 0: for _ in range(max_procs): if len(kw_arr) == 0: break kw = kw_arr.pop(0) p = Process(target=func, kwargs=kw) p.start() sys.stdout.flush() task_queue.put(p) if show_proc: signature = ', '.join([f'{k}={v}' for k, v in kw.items()]) print(f'[{func.__name__}] ({signature})') while not task_queue.empty(): p = task_queue.get() p.join()
993,357
Saturate all combinations of kwargs Args: keys: keys in kwargs that want to use process **kwargs: kwargs for func
def saturate_kwargs(keys, **kwargs): # Validate if keys are in kwargs and if they are iterable if isinstance(keys, str): keys = [keys] keys = [k for k in keys if k in kwargs and hasattr(kwargs.get(k, None), '__iter__')] if len(keys) == 0: return [] # Saturate coordinates of kwargs kw_corr = list(product(*(range(len(kwargs[k])) for k in keys))) # Append all possible values kw_arr = [] for corr in kw_corr: kw_arr.append( dict(zip(keys, [kwargs[keys[i]][corr[i]] for i in range(len(keys))])) ) # All combinations of kwargs of inputs for k in keys: kwargs.pop(k, None) kw_arr = [{**k, **kwargs} for k in kw_arr] return kw_arr
993,358
Trading dates for given exchange Args: start: start date end: end date calendar: exchange as string Returns: pd.DatetimeIndex: datetime index Examples: >>> bus_dates = ['2018-12-24', '2018-12-26', '2018-12-27'] >>> trd_dates = trading_dates(start='2018-12-23', end='2018-12-27') >>> assert len(trd_dates) == len(bus_dates) >>> assert pd.Series(trd_dates == pd.DatetimeIndex(bus_dates)).all()
def trading_dates(start, end, calendar='US'): kw = dict(start=pd.Timestamp(start, tz='UTC').date(), end=pd.Timestamp(end, tz='UTC').date()) us_cal = getattr(sys.modules[__name__], f'{calendar}TradingCalendar')() return pd.bdate_range(**kw).drop(us_cal.holidays(**kw))
993,522
on colorplot and as background plot the summed CSD contributions args: :: ax : matplotlib.axes.AxesSubplot object T : list, [tstart, tstop], which timeinterval ylims : list, set range of yaxis to scale with other plots fancy : bool, N : integer, set to number of LFP generators in order to get the normalized signal
def plot_signal_sum_colorplot(ax, params, fname='LFPsum.h5', unit='mV', N=1, ylabels = True, T=[800, 1000], ylim=[-1500, 0], fancy=False, colorbar=True, cmap='spectral_r', absmax=None, transient=200, rasterized=True): f = h5py.File(fname) data = f['data'].value tvec = np.arange(data.shape[1]) * 1000. / f['srate'].value #for mean subtraction datameanaxis1 = f['data'].value[:, tvec >= transient].mean(axis=1) # slice slica = (tvec <= T[1]) & (tvec >= T[0]) data = data[:,slica] # subtract mean #dataT = data.T - data.mean(axis=1) dataT = data.T - datameanaxis1 data = dataT.T # normalize data = data/N zvec = params.electrodeParams['z'] if fancy: colors = phlp.get_colors(data.shape[0]) else: colors = ['k']*data.shape[0] if absmax == None: absmax=abs(np.array([data.max(), data.min()])).max() im = ax.pcolormesh(tvec[slica], np.r_[zvec, zvec[-1] + np.diff(zvec)[-1]] + 50, data, rasterized=rasterized, vmax=absmax, vmin=-absmax, cmap=cmap) ax.set_yticks(params.electrodeParams['z']) if ylabels: yticklabels = ['ch. %i' %(i+1) for i in np.arange(len(params.electrodeParams['z']))] ax.set_yticklabels(yticklabels) else: ax.set_yticklabels([]) if colorbar: #colorbar divider=make_axes_locatable(ax) cax=divider.append_axes("right", size="5%", pad=0.1) cbar=plt.colorbar(im, cax=cax) cbar.set_label(unit,labelpad=0.1) plt.axis('tight') ax.set_ylim(ylim) f.close() return im
993,590
on axes plot the LFP power spectral density The whole signal duration is used. args: :: ax : matplotlib.axes.AxesSubplot object fancy : bool,
def plot_signal_power_colorplot(ax, params, fname, transient=200, Df=None, mlab=True, NFFT=1000, window=plt.mlab.window_hanning, noverlap=0, cmap = plt.cm.get_cmap('jet', 21), vmin=None, vmax=None): zvec = np.r_[params.electrodeParams['z']] zvec = np.r_[zvec, zvec[-1] + np.diff(zvec)[-1]] #labels yticklabels=[] yticks = [] for i, kk in enumerate(params.electrodeParams['z']): yticklabels.append('ch. %i' % (i+1)) yticks.append(kk) freqs, PSD = calc_signal_power(params, fname=fname, transient=transient,Df=Df, mlab=mlab, NFFT=NFFT, window=window, noverlap=noverlap) #plot only above 1 Hz inds = freqs >= 1 # frequencies greater than 4 Hz im = ax.pcolormesh(freqs[inds], zvec+50, PSD[:, inds], rasterized=True, norm=LogNorm(), vmin=vmin,vmax=vmax, cmap=cmap, ) ax.yaxis.set_ticks(yticks) ax.yaxis.set_ticklabels(yticklabels) ax.semilogx() ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.set_xlabel(r'$f$ (Hz)', labelpad=0.1) ax.axis(ax.axis('tight')) return im
993,592
mls on axes plot the correlation between x0 and x1 args: :: x0 : first dataset x1 : second dataset - the LFP usually here ax : matplotlib.axes.AxesSubplot object title : text to be used as current axis object title normalize : if True, signals are z-scored before applying np.correlate unit : unit for scalebar
def plotting_correlation(params, x0, x1, ax, lag=20., scaling=None, normalize=True, color='k', unit=r'$cc=%.3f$' , title='firing_rate vs LFP', scalebar=True, **kwargs): zvec = np.r_[params.electrodeParams['z']] zvec = np.r_[zvec, zvec[-1] + np.diff(zvec)[-1]] xcorr_all=np.zeros((params.electrodeParams['z'].size, x0.shape[-1])) if normalize: for i, z in enumerate(params.electrodeParams['z']): if x0.ndim == 1: x2 = x1[i, ] xcorr1 = np.correlate(helpers.normalize(x0), helpers.normalize(x2), 'same') / x0.size elif x0.ndim == 2: xcorr1 = np.correlate(helpers.normalize(x0[i, ]), helpers.normalize(x1[i, ]), 'same') / x0.shape[-1] xcorr_all[i,:]=xcorr1 else: for i, z in enumerate(params.electrodeParams['z']): if x0.ndim == 1: x2 = x1[i, ] xcorr1 = np.correlate(x0,x2, 'same') elif x0.ndim == 2: xcorr1 = np.correlate(x0[i, ],x1[i, ], 'same') xcorr_all[i,:]=xcorr1 # Find limits for the plot if scaling is None: vlim = abs(xcorr_all).max() vlimround = 2.**np.round(np.log2(vlim)) else: vlimround = scaling yticklabels=[] yticks = [] #temporal slicing lagvector = np.arange(-lag, lag+1).astype(int) inds = lagvector + x0.shape[-1] / 2 for i, z in enumerate(params.electrodeParams['z']): ax.plot(lagvector, xcorr_all[i,inds[::-1]] * 100. / vlimround + z, 'k', clip_on=True, rasterized=False, color=color, **kwargs) yticklabels.append('ch. %i' %(i+1)) yticks.append(z) phlp.remove_axis_junk(ax) ax.set_title(title, va='center') ax.set_xlabel(r'$\tau$ (ms)', labelpad=0.1) ax.set_xlim(-lag, lag) ax.set_ylim(z-100, 100) axis = ax.axis() ax.vlines(0, axis[2], axis[3], 'k' if analysis_params.bw else 'k', 'dotted', lw=0.25) ax.yaxis.set_ticks(yticks) ax.yaxis.set_ticklabels(yticklabels) ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ## Create a scaling bar if scalebar: ax.plot([lag, lag], [-1500, -1400], lw=2, color='k', clip_on=False) ax.text(lag*1.04, -1450, unit % vlimround, rotation='vertical', va='center') return xcorr_all[:, inds[::-1]], vlimround
993,594
Data file Args: symbol: symbol func: use function to categorize data has_date: contains date in data file root: root path date_type: parameters pass to utils.cur_time, [date, time, time_path, ...] Returns: str: date file
def cache_file(symbol, func, has_date, root, date_type='date'): cur_mod = sys.modules[func.__module__] data_tz = getattr(cur_mod, 'DATA_TZ') if hasattr(cur_mod, 'DATA_TZ') else 'UTC' cur_dt = utils.cur_time(typ=date_type, tz=data_tz, trading=False) if has_date: if hasattr(cur_mod, 'FILE_WITH_DATE'): file_fmt = getattr(cur_mod, 'FILE_WITH_DATE') else: file_fmt = '{root}/{typ}/{symbol}/{cur_dt}.parq' else: if hasattr(cur_mod, 'FILE_NO_DATE'): file_fmt = getattr(cur_mod, 'FILE_NO_DATE') else: file_fmt = '{root}/{typ}/{symbol}.parq' return data_file( file_fmt=file_fmt, root=root, cur_dt=cur_dt, typ=func.__name__, symbol=symbol )
993,792
Decorator to save data more easily. Use parquet as data format Args: func: function to load data from data source Returns: wrapped function
def update_data(func): default = dict([ (param.name, param.default) for param in inspect.signature(func).parameters.values() if param.default != getattr(inspect, '_empty') ]) @wraps(func) def wrapper(*args, **kwargs): default.update(kwargs) kwargs.update(default) cur_mod = sys.modules[func.__module__] logger = logs.get_logger(name_or_func=f'{cur_mod.__name__}.{func.__name__}', types='stream') root_path = cur_mod.DATA_PATH date_type = kwargs.pop('date_type', 'date') save_static = kwargs.pop('save_static', True) save_dynamic = kwargs.pop('save_dynamic', True) symbol = kwargs.get('symbol') file_kw = dict(func=func, symbol=symbol, root=root_path, date_type=date_type) d_file = cache_file(has_date=True, **file_kw) s_file = cache_file(has_date=False, **file_kw) cached = kwargs.pop('cached', False) if cached and save_static and files.exists(s_file): logger.info(f'Reading data from {s_file} ...') return pd.read_parquet(s_file) data = func(*args, **kwargs) if save_static: files.create_folder(s_file, is_file=True) save_data(data=data, file_fmt=s_file, append=False) logger.info(f'Saved data file to {s_file} ...') if save_dynamic: drop_dups = kwargs.pop('drop_dups', None) files.create_folder(d_file, is_file=True) save_data(data=data, file_fmt=d_file, append=True, drop_dups=drop_dups) logger.info(f'Saved data file to {d_file} ...') return data return wrapper
993,793
Data file name for given infomation Args: file_fmt: file format in terms of f-strings info: dict, to be hashed and then pass to f-string using 'hash_key' these info will also be passed to f-strings **kwargs: arguments for f-strings Returns: str: data file name
def data_file(file_fmt, info=None, **kwargs): if isinstance(info, dict): kwargs['hash_key'] = hashlib.sha256(json.dumps(info).encode('utf-8')).hexdigest() kwargs.update(info) return utils.fstr(fmt=file_fmt, **kwargs)
993,795
Check the result of an API response. Ideally, this should be done by checking that the value of the ``resultCode`` attribute is 0, but there are endpoints that simply do not follow this rule. Args: data (dict): Response obtained from the API endpoint. key (string): Key to check for existence in the dict. Returns: bool: True if result was correct, False otherwise.
def check_result(data, key=''): if not isinstance(data, dict): return False if key: if key in data: return True return False if 'resultCode' in data.keys(): # OpenBus return True if data.get('resultCode', -1) == 0 else False elif 'code' in data.keys(): # Parking return True if data.get('code', -1) == 0 else False return False
994,201
Build a date string using the provided day, month, year numbers. Automatically adds a leading zero to ``day`` and ``month`` if they only have one digit. Args: day (int): Day number. month(int): Month number. year(int): Year number. hour (int): Hour of the day in 24h format. minute (int): Minute of the hour. Returns: str: Date in the format *YYYY-MM-DDThh:mm:ss*.
def datetime_string(day, month, year, hour, minute): # Overflow if hour < 0 or hour > 23: hour = 0 if minute < 0 or minute > 60: minute = 0 return '%d-%02d-%02dT%02d:%02d:00' % (year, month, day, hour, minute)
994,202
Convert a list of integers to a *|* separated string. Args: ints (list[int]|int): List of integer items to convert or single integer to convert. Returns: str: Formatted string
def ints_to_string(ints): if not isinstance(ints, list): return six.u(str(ints)) return '|'.join(six.u(str(l)) for l in ints)
994,203
Obtain the relevant response data in a list. If the response does not already contain the result in a list, a new one will be created to ease iteration in the parser methods. Args: data (dict): API response. key (str): Attribute of the response that contains the result values. Returns: List of response items (usually dict) or None if the key is not present.
def response_list(data, key): if key not in data: return None if isinstance(data[key], list): return data[key] else: return [data[key],]
994,204
Calling this function initializes the printer. Args: None Returns: None Raises: None
def initialize(self): self.fonttype = self.font_types['bitmap'] self.send(chr(27)+chr(64))
994,484
Select international character set and changes codes in code table accordingly Args: charset: String. The character set we want. Returns: None Raises: RuntimeError: Invalid charset.
def select_charset(self, charset): charsets = {'USA':0, 'France':1, 'Germany':2, 'UK':3, 'Denmark':4, 'Sweden':5, 'Italy':6, 'Spain':7, 'Japan':8, 'Norway':9, 'Denmark II':10, 'Spain II':11, 'Latin America':12, 'South Korea':13, 'Legal':64, } if charset in charsets: self.send(chr(27)+'R'+chr(charsets[charset])) else: raise RuntimeError('Invalid charset.')
994,485
Select character code table, from tree built in ones. Args: table: The desired character code table. Choose from 'standard', 'eastern european', 'western european', and 'spare' Returns: None Raises: RuntimeError: Invalid chartable.
def select_char_code_table(self, table): tables = {'standard': 0, 'eastern european': 1, 'western european': 2, 'spare': 3 } if table in tables: self.send(chr(27)+'t'+chr(tables[table])) else: raise RuntimeError('Invalid char table.')
994,486
Set cut setting for printer. Args: cut: The type of cut setting we want. Choices are 'full', 'half', 'chain', and 'special'. Returns: None Raises: RuntimeError: Invalid cut type.
def cut_setting(self, cut): cut_settings = {'full' : 0b00000001, 'half' : 0b00000010, 'chain': 0b00000100, 'special': 0b00001000 } if cut in cut_settings: self.send(chr(27)+'iC'+chr(cut_settings[cut])) else: raise RuntimeError('Invalid cut type.')
994,487
Calling this function applies the desired action to the printing orientation of the printer. Args: action: The desired printing orientation. 'rotate' enables rotated printing. 'normal' disables rotated printing. Returns: None Raises: RuntimeError: Invalid action.
def rotated_printing(self, action): if action=='rotate': action='1' elif action=='cancel': action='0' else: raise RuntimeError('Invalid action.') self.send(chr(27)+chr(105)+chr(76)+action)
994,488
Calling this function sets the form feed amount to the specified setting. Args: amount: the form feed setting you desire. Options are '1/8', '1/6', 'x/180', and 'x/60', with x being your own desired amount. X must be a minimum of 24 for 'x/180' and 8 for 'x/60' Returns: None Raises: None
def feed_amount(self, amount): n = None if amount=='1/8': amount = '0' elif amount=='1/6': amount = '2' elif re.search('/180', amount): n = re.search(r"(\d+)/180", amount) n = n.group(1) amount = '3' elif re.search('/60', amount): n = re.search(r"(\d+)/60", amount) n = n.group(1) amount = 'A' if n: self.send(chr(27)+amount+n) else: self.send(chr(27)+amount)
994,489
Specifies page length. This command is only valid with continuous length labels. Args: length: The length of the page, in dots. Can't exceed 12000. Returns: None Raises: RuntimeError: Length must be less than 12000.
def page_length(self, length): mH = length/256 mL = length%256 if length < 12000: self.send(chr(27)+'('+'C'+chr(2)+chr(0)+chr(mL)+chr(mH)) else: raise RuntimeError('Length must be less than 12000.')
994,490
Specify settings for top and bottom margins. Physically printable area depends on media. Args: topmargin: the top margin, in dots. The top margin must be less than the bottom margin. bottommargin: the bottom margin, in dots. The bottom margin must be less than the top margin. Returns: None Raises: RuntimeError: Top margin must be less than the bottom margin.
def page_format(self, topmargin, bottommargin): tL = topmargin%256 tH = topmargin/256 BL = bottommargin%256 BH = topmargin/256 if (tL+tH*256) < (BL + BH*256): self.send(chr(27)+'('+'c'+chr(4)+chr(0)+chr(tL)+chr(tH)+chr(BL)+chr(BH)) else: raise RuntimeError('The top margin must be less than the bottom margin')
994,491
Specify the left margin. Args: margin: The left margin, in character width. Must be less than the media's width. Returns: None Raises: RuntimeError: Invalid margin parameter.
def left_margin(self, margin): if margin <= 255 and margin >= 0: self.send(chr(27)+'I'+chr(margin)) else: raise RuntimeError('Invalid margin parameter.')
994,492
Specify the right margin. Args: margin: The right margin, in character width, must be less than the media's width. Returns: None Raises: RuntimeError: Invalid margin parameter
def right_margin(self, margin): if margin >=1 and margin <=255: self.send(chr(27)+'Q'+chr(margin)) else: raise RuntimeError('Invalid margin parameter in function rightMargin')
994,493
Sets tab positions, up to a maximum of 32 positions. Also can clear tab positions. Args: positions -- Either a list of tab positions (between 1 and 255), or 'clear'. Returns: None Raises: RuntimeError: Invalid position parameter. RuntimeError: Too many positions.
def vert_tab_pos(self, positions): if positions == 'clear': self.send(chr(27)+'B'+chr(0)) return if positions.min < 1 or positions.max >255: raise RuntimeError('Invalid position parameter in function horzTabPos') sendstr = chr(27) + 'D' if len(positions)<=16: for position in positions: sendstr += chr(position) self.send(sendstr + chr(0)) else: raise RuntimeError('Too many positions in function vertTabPos')
994,494
Calling this function finishes input of the current line, then moves the vertical print position forward by x/300 inch. Args: amount: how far foward you want the position moved. Actual movement is calculated as amount/300 inches. Returns: None Raises: RuntimeError: Invalid foward feed.
def forward_feed(self, amount): if amount <= 255 and amount >=0: self.send(chr(27)+'J'+chr(amount)) else: raise RuntimeError('Invalid foward feed, must be less than 255 and >= 0')
994,495
Specify vertical print position from the top margin position. Args: amount: The distance from the top margin you'd like, from 0 to 32767 Returns: None Raises: RuntimeError: Invalid vertical position.
def abs_vert_pos(self, amount): mL = amount%256 mH = amount/256 if amount < 32767 and amount > 0: self.send(chr(27)+'('+'V'+chr(2)+chr(0)+chr(mL)+chr(mH)) else: raise RuntimeError('Invalid vertical position in function absVertPos')
994,496
Calling this function sets the absoulte print position for the next data, this is the position from the left margin. Args: amount: desired positioning. Can be a number from 0 to 2362. The actual positioning is calculated as (amount/60)inches from the left margin. Returns: None Raises: None
def abs_horz_pos(self, amount): n1 = amount%256 n2 = amount/256 self.send(chr(27)+'${n1}{n2}'.format(n1=chr(n1), n2=chr(n2)))
994,497
Sets the alignment of the printer. Args: align: desired alignment. Options are 'left', 'center', 'right', and 'justified'. Anything else will throw an error. Returns: None Raises: RuntimeError: Invalid alignment.
def alignment(self, align): if align=='left': align = '0' elif align=='center': align = '1' elif align=='right': align = '2' elif align=='justified': align = '3' else: raise RuntimeError('Invalid alignment in function alignment') self.send(chr(27)+'a'+align)
994,499
Places/removes frame around text Args: action -- Enable or disable frame. Options are 'on' and 'off' Returns: None Raises: RuntimeError: Invalid action.
def frame(self, action): choices = {'on': '1', 'off': '0'} if action in choices: self.send(chr(27)+'if'+choices[action]) else: raise RuntimeError('Invalid action for function frame, choices are on and off')
994,500
Enable/cancel bold printing Args: action: Enable or disable bold printing. Options are 'on' and 'off' Returns: None Raises: RuntimeError: Invalid action.
def bold(self, action): if action =='on': action = 'E' elif action == 'off': action = 'F' else: raise RuntimeError('Invalid action for function bold. Options are on and off') self.send(chr(27)+action)
994,501
Enable/cancel italic printing Args: action: Enable or disable italic printing. Options are 'on' and 'off' Returns: None Raises: RuntimeError: Invalid action.
def italic(self, action): if action =='on': action = '4' elif action=='off': action = '5' else: raise RuntimeError('Invalid action for function italic. Options are on and off') self.send(chr(27)+action)
994,502
Enable/cancel doublestrike printing Args: action: Enable or disable doublestrike printing. Options are 'on' and 'off' Returns: None Raises: RuntimeError: Invalid action.
def double_strike(self, action): if action == 'on': action = 'G' elif action == 'off': action = 'H' else: raise RuntimeError('Invalid action for function doubleStrike. Options are on and off') self.send(chr(27)+action)
994,503
Enable/cancel doublewidth printing Args: action: Enable or disable doublewidth printing. Options are 'on' and 'off' Returns: None Raises: RuntimeError: Invalid action.
def double_width(self, action): if action == 'on': action = '1' elif action == 'off': action = '0' else: raise RuntimeError('Invalid action for function doubleWidth. Options are on and off') self.send(chr(27)+'W'+action)
994,504
Enable/cancel compressed character printing Args: action: Enable or disable compressed character printing. Options are 'on' and 'off' Returns: None Raises: RuntimeError: Invalid action.
def compressed_char(self, action): if action == 'on': action = 15 elif action == 'off': action = 18 else: raise RuntimeError('Invalid action for function compressedChar. Options are on and off') self.send(chr(action))
994,505
Enable/cancel underline printing Args: action -- Enable or disable underline printing. Options are '1' - '4' and 'cancel' Returns: None Raises: None
def underline(self, action): if action == 'off': action = '0' self.send(chr(27)+chr(45)+action) else: self.send(chr(27)+chr(45)+action)
994,506
Select font type Choices are: <Bit map fonts> 'brougham' 'lettergothicbold' 'brusselsbit' 'helsinkibit' 'sandiego' <Outline fonts> 'lettergothic' 'brusselsoutline' 'helsinkioutline' Args: font: font type Returns: None Raises: RuntimeError: Invalid font.
def select_font(self, font): fonts = {'brougham': 0, 'lettergothicbold': 1, 'brusselsbit' : 2, 'helsinkibit': 3, 'sandiego': 4, 'lettergothic': 9, 'brusselsoutline': 10, 'helsinkioutline': 11} if font in fonts: if font in ['broughham', 'lettergothicbold', 'brusselsbit', 'helsinkibit', 'sandiego']: self.fonttype = self.font_types['bitmap'] else: self.fonttype = self.font_types['outline'] self.send(chr(27)+'k'+chr(fonts[font])) else: raise RuntimeError('Invalid font in function selectFont')
994,508
Sets the character style. Args: style: The desired character style. Choose from 'normal', 'outline', 'shadow', and 'outlineshadow' Returns: None Raises: RuntimeError: Invalid character style
def char_style(self, style): styleset = {'normal': 0, 'outline': 1, 'shadow': 2, 'outlineshadow': 3 } if style in styleset: self.send(chr(27) + 'q' + chr(styleset[style])) else: raise RuntimeError('Invalid character style in function charStyle')
994,509
Specifies proportional characters. When turned on, the character spacing set with charSpacing. Args: action: Turn proportional characters on or off. Returns: None Raises: RuntimeError: Invalid action.
def proportional_char(self, action): actions = {'off': 0, 'on': 1 } if action in actions: self.send(chr(27)+'p'+action) else: raise RuntimeError('Invalid action in function proportionalChar')
994,510
Specifes character spacing in dots. Args: dots: the character spacing you desire, in dots Returns: None Raises: RuntimeError: Invalid dot amount.
def char_spacing(self, dots): if dots in range(0,127): self.send(chr(27)+chr(32)+chr(dots)) else: raise RuntimeError('Invalid dot amount in function charSpacing')
994,511
Choose a template Args: template: String, choose which template you would like. Returns: None Raises: None
def choose_template(self, template): n1 = int(template)/10 n2 = int(template)%10 self.send('^TS'+'0'+str(n1)+str(n2))
994,513
Perform machine operations Args: operations: which operation you would like Returns: None Raises: RuntimeError: Invalid operation
def machine_op(self, operation): operations = {'feed2start': 1, 'feedone': 2, 'cut': 3 } if operation in operations: self.send('^'+'O'+'P'+chr(operations[operation])) else: raise RuntimeError('Invalid operation.')
994,514
Set print start trigger. Args: type: The type of trigger you desire. Returns: None Raises: RuntimeError: Invalid type.
def print_start_trigger(self, type): types = {'recieved': 1, 'filled': 2, 'num_recieved': 3} if type in types: self.send('^PT'+chr(types[type])) else: raise RuntimeError('Invalid type.')
994,515
Set print command Args: command: the type of command you desire. Returns: None Raises: RuntimeError: Command too long.
def print_start_command(self, command): size = len(command) if size > 20: raise RuntimeError('Command too long') n1 = size/10 n2 = size%10 self.send('^PS'+chr(n1)+chr(n2)+command)
994,516
Set recieved char count limit Args: count: the amount of received characters you want to stop at. Returns: None Raises: None
def received_char_count(self, count): n1 = count/100 n2 = (count-(n1*100))/10 n3 = (count-((n1*100)+(n2*10))) self.send('^PC'+chr(n1)+chr(n2)+chr(n3))
994,517
Select desired delimeter Args: delim: The delimeter character you want. Returns: None Raises: RuntimeError: Delimeter too long.
def select_delim(self, delim): size = len(delim) if size > 20: raise RuntimeError('Delimeter too long') n1 = size/10 n2 = size%10 self.send('^SS'+chr(n1)+chr(n2))
994,518
Insert text into selected object. Args: data: The data you want to insert. Returns: None Raises: None
def insert_into_obj(self, data): if not data: data = '' size = len(data) n1 = size%256 n2 = size/256 self.send('^DI'+chr(n1)+chr(n2)+data)
994,519
Combines selection and data insertion into one function Args: name: the name of the object you want to insert into data: the data you want to insert Returns: None Raises: None
def select_and_insert(self, name, data): self.select_obj(name) self.insert_into_obj(data)
994,520
Initialization of the API module. Args: wrapper (Wrapper): Object that performs the requests to endpoints.
def __init__(self, wrapper): self._wrapper = wrapper self.make_request = self._wrapper.request_parking
994,883
Obtain detailed info of a given POI. Args: family (str): Family code of the POI (3 chars). lang (str): Language code (*es* or *en*). id (int): Optional, ID of the POI to query. Passing value -1 will result in information from all POIs. Returns: Status boolean and parsed response (list[PoiDetails]), or message string in case of error.
def detail_poi(self, **kwargs): # Endpoint parameters params = { 'language': util.language_code(kwargs.get('lang')), 'family': kwargs.get('family') } if kwargs.get('id'): params['id'] = kwargs['id'] # Request result = self.make_request('detail_poi', {}, **params) if not util.check_result(result): return False, result.get('message', 'UNKNOWN ERROR') # Parse values = util.response_list(result, 'Data') return True, [emtype.PoiDetails(**a) for a in values]
994,885
Obtain a list of elements that have an associated icon. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[IconDescription]), or message string in case of error.
def icon_description(self, **kwargs): # Endpoint parameters params = {'language': util.language_code(kwargs.get('lang'))} # Request result = self.make_request('icon_description', {}, **params) if not util.check_result(result): return False, result.get('message', 'UNKNOWN ERROR') # Parse values = util.response_list(result, 'Data') return True, [emtype.IconDescription(**a) for a in values]
994,886
Obtain a list of parkings. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[Parking]), or message string in case of error.
def list_features(self, **kwargs): # Endpoint parameters params = { 'language': util.language_code(kwargs.get('lang')), 'publicData': True } # Request result = self.make_request('list_features', {}, **params) if not util.check_result(result): return False, result.get('message', 'UNKNOWN ERROR') # Parse values = util.response_list(result, 'Data') return True, [emtype.ParkingFeature(**a) for a in values]
994,888
Obtain a list of parkings. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[Parking]), or message string in case of error.
def list_parking(self, **kwargs): # Endpoint parameters url_args = {'lang': util.language_code(kwargs.get('lang'))} # Request result = self.make_request('list_parking', url_args) if not util.check_result(result): return False, result.get('message', 'UNKNOWN ERROR') # Parse values = util.response_list(result, 'Data') return True, [emtype.Parking(**a) for a in values]
994,889
Obtain a list of addresses and POIs. This endpoint uses an address to perform the search Args: lang (str): Language code (*es* or *en*). address (str): Address in which to perform the search. Returns: Status boolean and parsed response (list[ParkingPoi]), or message string in case of error.
def list_street_poi_parking(self, **kwargs): # Endpoint parameters url_args = { 'language': util.language_code(kwargs.get('lang')), 'address': kwargs.get('address', '') } # Request result = self.make_request('list_street_poi_parking', url_args) if not util.check_result(result): return False, result.get('message', 'UNKNOWN ERROR') # Parse values = util.response_list(result, 'Data') return True, [emtype.ParkingPoi(**a) for a in values]
994,890
Obtain a list of families, types and categories of POI. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[ParkingPoiType]), or message string in case of error.
def list_types_poi(self, **kwargs): # Endpoint parameters url_args = {'language': util.language_code(kwargs.get('lang'))} # Request result = self.make_request('list_poi_types', url_args) if not util.check_result(result): return False, result.get('message', 'UNKNOWN ERROR') # Parse values = util.response_list(result, 'Data') return True, [emtype.ParkingPoiType(**a) for a in values]
994,891
Initialization of the API module. Args: wrapper (Wrapper): Object that performs the requests to endpoints.
def __init__(self, wrapper): self._wrapper = wrapper self.make_request = self._wrapper.request_openbus
995,132
Obtain bus arrival info in target stop. Args: stop_number (int): Stop number to query. lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[Arrival]), or message string in case of error.
def get_arrive_stop(self, **kwargs): # Endpoint parameters params = { 'idStop': kwargs.get('stop_number'), 'cultureInfo': util.language_code(kwargs.get('lang')) } # Request result = self.make_request('geo', 'get_arrive_stop', **params) # Funny endpoint, no status code if not util.check_result(result, 'arrives'): return False, 'UNKNOWN ERROR' # Parse values = util.response_list(result, 'arrives') return True, [emtype.Arrival(**a) for a in values]
995,133
Obtain line types and details. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[GeoGroupItem]), or message string in case of error.
def get_groups(self, **kwargs): # Endpoint parameters params = { 'cultureInfo': util.language_code(kwargs.get('lang')) } # Request result = self.make_request('geo', 'get_groups', **params) if not util.check_result(result): return False, result.get('resultDescription', 'UNKNOWN ERROR') # Parse values = util.response_list(result, 'resultValues') return True, [emtype.GeoGroupItem(**a) for a in values]
995,134
Obtain a list of POI in the given radius. Args: latitude (double): Latitude in decimal degrees. longitude (double): Longitude in decimal degrees. types (list[int] | int): POI IDs (or empty list to get all). radius (int): Radius (in meters) of the search. lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[Poi]), or message string in case of error.
def get_poi(self, **kwargs): # Endpoint parameters params = { 'coordinateX': kwargs.get('longitude'), 'coordinateY': kwargs.get('latitude'), 'tipos': util.ints_to_string(kwargs.get('types')), 'Radius': kwargs.get('radius'), 'cultureInfo': util.language_code(kwargs.get('lang')) } # Request result = self.make_request('geo', 'get_poi', **params) # Funny endpoint, no status code if not util.check_result(result, 'poiList'): return False, 'UNKNOWN ERROR' # Parse values = util.response_list(result, 'poiList') return True, [emtype.Poi(**a) for a in values]
995,136
Obtain POI types. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[PoiType]), or message string in case of error.
def get_poi_types(self, **kwargs): # Endpoint parameters params = { 'cultureInfo': util.language_code(kwargs.get('lang')) } # Request result = self.make_request('geo', 'get_poi_types', **params) # Parse values = result.get('types', []) return True, [emtype.PoiType(**a) for a in values]
995,137
Obtain information on the stops of the given lines. Arguments: lines (list[int] | int): Lines to query, may be empty to get all the lines. direction (str): Optional, either *forward* or *backward*. lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[Stop]), or message string in case of error.
def get_stops_line(self, **kwargs): # Endpoint parameters params = { 'line': util.ints_to_string(kwargs.get('lines', [])), 'direction': util.direction_code(kwargs.get('direction', '')), 'cultureInfo': util.language_code(kwargs.get('lang')) } # Request result = self.make_request('geo', 'get_stops_line', **params) # Funny endpoint, no status code # Only interested in 'stop' if not util.check_result(result, 'stop'): return False, 'UNKNOWN ERROR' # Parse values = util.response_list(result, 'stop') return True, [emtype.Stop(**a) for a in values]
995,139
Obtain a list of streets around the specified point. Args: latitude (double): Latitude in decimal degrees. longitude (double): Longitude in decimal degrees. radius (int): Radius (in meters) of the search. lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[Street]), or message string in case of error.
def get_street_from_xy(self, **kwargs): # Endpoint parameters params = { 'coordinateX': kwargs.get('longitude'), 'coordinateY': kwargs.get('latitude'), 'Radius': kwargs.get('radius'), 'cultureInfo': util.language_code(kwargs.get('lang')) } # Request result = self.make_request('geo', 'get_street_from_xy', **params) # Funny endpoint, no status code if not util.check_result(result, 'site'): return False, 'UNKNOWN ERROR' # Parse values = util.response_list(result, 'site') return True, [emtype.Street(**a) for a in values]
995,141
Obtain stop IDs, coordinates and line information. Args: nodes (list[int] | int): nodes to query, may be empty to get all nodes. Returns: Status boolean and parsed response (list[NodeLinesItem]), or message string in case of error.
def get_nodes_lines(self, **kwargs): # Endpoint parameters params = {'Nodes': util.ints_to_string(kwargs.get('nodes', []))} # Request result = self.make_request('bus', 'get_nodes_lines', **params) if not util.check_result(result): return False, result.get('resultDescription', 'UNKNOWN ERROR') # Parse values = util.response_list(result, 'resultValues') return True, [emtype.NodeLinesItem(**a) for a in values]
995,290
Initialize the interface attributes. Initialization may also be performed at a later point by manually calling the ``initialize()`` method. Args: emt_id (str): ID given by the server upon registration emt_pass (str): Token given by the server upon registration
def __init__(self, emt_id='', emt_pass=''): if emt_id and emt_pass: self.initialize(emt_id, emt_pass)
995,796
Manual initialization of the interface attributes. This is useful when the interface must be declare but initialized later on with parsed configuration values. Args: emt_id (str): ID given by the server upon registration emt_pass (str): Token given by the server upon registration
def initialize(self, emt_id, emt_pass): self._emt_id = emt_id self._emt_pass = emt_pass # Initialize modules self.bus = BusApi(self) self.geo = GeoApi(self) self.parking = ParkingApi(self)
995,797
Answer will provide all necessary feedback for the caller Args: c (int): HTTP Code details (dict): Response payload Returns: dict: Response payload Raises: ErrAtlasBadRequest ErrAtlasUnauthorized ErrAtlasForbidden ErrAtlasNotFound ErrAtlasMethodNotAllowed ErrAtlasConflict ErrAtlasServerErrors
def answer(self, c, details): if c in [Settings.SUCCESS, Settings.CREATED, Settings.ACCEPTED]: return details elif c == Settings.BAD_REQUEST: raise ErrAtlasBadRequest(c, details) elif c == Settings.UNAUTHORIZED: raise ErrAtlasUnauthorized(c, details) elif c == Settings.FORBIDDEN: raise ErrAtlasForbidden(c, details) elif c == Settings.NOTFOUND: raise ErrAtlasNotFound(c, details) elif c == Settings.METHOD_NOT_ALLOWED: raise ErrAtlasMethodNotAllowed(c, details) elif c == Settings.CONFLICT: raise ErrAtlasConflict(c, details) else: # Settings.SERVER_ERRORS raise ErrAtlasServerErrors(c, details)
997,183
Get request Args: uri (str): URI Returns: Json: API response Raises: Exception: Network issue
def get(self, uri): r = None try: r = requests.get(uri, allow_redirects=True, timeout=Settings.requests_timeout, headers={}, auth=HTTPDigestAuth(self.user, self.password)) return self.answer(r.status_code, r.json()) except: raise finally: if r: r.connection.close()
997,184
Add multiple roles Args: databaseName (str): Database Name roleNames (list of RoleSpecs): roles Keyword Args: collectionName (str): Collection Raises: ErrRoleException: role not compatible with the databaseName and/or collectionName
def add_roles(self, databaseName, roleNames, collectionName=None): for roleName in roleNames: self.add_role(databaseName, roleName, collectionName)
997,302
Add one role Args: databaseName (str): Database Name roleName (RoleSpecs): role Keyword Args: collectionName (str): Collection Raises: ErrRole: role not compatible with the databaseName and/or collectionName
def add_role(self, databaseName, roleName, collectionName=None): role = {"databaseName" : databaseName, "roleName" : roleName} if collectionName: role["collectionName"] = collectionName # Check atlas constraints if collectionName and roleName not in [RoleSpecs.read, RoleSpecs.readWrite]: raise ErrRole("Permissions [%s] not available for a collection" % roleName) elif not collectionName and roleName not in [RoleSpecs.read, RoleSpecs.readWrite, RoleSpecs.dbAdmin] and databaseName != "admin": raise ErrRole("Permissions [%s] is only available for admin database" % roleName) if role not in self.roles: self.roles.append(role)
997,303
Remove multiple roles Args: databaseName (str): Database Name roleNames (list of RoleSpecs): roles Keyword Args: collectionName (str): Collection
def remove_roles(self, databaseName, roleNames, collectionName=None): for roleName in roleNames: self.remove_role(databaseName, roleName, collectionName)
997,304
Remove one role Args: databaseName (str): Database Name roleName (RoleSpecs): role Keyword Args: collectionName (str): Collection
def remove_role(self, databaseName, roleName, collectionName=None): role = {"databaseName" : databaseName, "roleName" : roleName} if collectionName: role["collectionName"] = collectionName if role in self.roles: self.roles.remove(role)
997,305
Formatting JSON API Error Object Constructing an error object based on JSON API standard ref: http://jsonapi.org/format/#error-objects Args: status: Can be a http status codes title: A summary of error detail: A descriptive error message code: Application error codes (if any) Returns: A dictionary contains of status, title, detail and code
def format_error(status=None, title=None, detail=None, code=None): error = {} error.update({ 'title': title }) if status is not None: error.update({ 'status': status }) if detail is not None: error.update({ 'detail': detail }) if code is not None: error.update({ 'code': code }) return error
997,392
List of errors Put all errors into a list of errors ref: http://jsonapi.org/format/#errors Args: *args: A tuple contain errors Returns: A dictionary contains a list of errors
def return_an_error(*args): list_errors = [] list_errors.extend(list(args)) errors = { 'errors': list_errors } return errors
997,393
Intermediate fetching Args: pageNum (int): Page number itemsPerPage (int): Number of Users per Page Returns: dict: Response payload
def fetch(self, pageNum, itemsPerPage): return self.get_all_alerts(self.status, pageNum, itemsPerPage)
997,476
Check ISBN is a string, and passes basic sanity checks. Args: isbn (str): SBN, ISBN-10 or ISBN-13 checksum (bool): ``True`` if ``isbn`` includes checksum character Returns: ``str``: ISBN with hyphenation removed, including when called with a SBN Raises: TypeError: ``isbn`` is not a ``str`` type IsbnError: Incorrect length for ``isbn`` IsbnError: Incorrect SBN or ISBN formatting
def _isbn_cleanse(isbn, checksum=True): if not isinstance(isbn, string_types): raise TypeError('ISBN must be a string, received %r' % isbn) if PY2 and isinstance(isbn, str): # pragma: Python 2 isbn = unicode(isbn) uni_input = False else: # pragma: Python 3 uni_input = True for dash in DASHES: isbn = isbn.replace(dash, unicode()) if checksum: if not isbn[:-1].isdigit(): raise IsbnError('non-digit parts') if len(isbn) == 9: isbn = '0' + isbn if len(isbn) == 10: if not (isbn[-1].isdigit() or isbn[-1] in 'Xx'): raise IsbnError('non-digit or X checksum') elif len(isbn) == 13: if not isbn[-1].isdigit(): raise IsbnError('non-digit checksum') if not isbn.startswith(('978', '979')): raise IsbnError('invalid Bookland region') else: raise IsbnError('ISBN must be either 10 or 13 characters long') else: if len(isbn) == 8: isbn = '0' + isbn elif len(isbn) == 12 and not isbn[:3].startswith(('978', '979')): raise IsbnError('invalid Bookland region') if not isbn.isdigit(): raise IsbnError('non-digit parts') if not len(isbn) in (9, 12): raise IsbnError('ISBN must be either 9 or 12 characters long ' 'without checksum') if PY2 and not uni_input: # pragma: Python 2 # Sadly, type ping-pong is required to maintain backwards compatibility # with previous pyisbn releases for Python 2 users. return str(isbn) else: # pragma: Python 3 return isbn
997,667