Search is not available for this dataset
text
stringlengths
75
104k
def connect(self): """|coro| Connect to ubisoft, automatically called when needed""" if time.time() < self._login_cooldown: raise FailedToConnect("login on cooldown") resp = yield from self.session.post("https://connect.ubi.com/ubiservices/v2/profiles/sessions", headers = {...
def get_players(self, name=None, platform=None, uid=None): """|coro| get a list of players matching the term on that platform, exactly one of uid and name must be given, platform must be given, this list almost always has only 1 element, so it's easier to use get_player Paramet...
def get_player(self, name=None, platform=None, uid=None): """|coro| Calls get_players and returns the first element, exactly one of uid and name must be given, platform must be given Parameters ---------- name : str the name of the player you're searching fo...
def get_operator_definitions(self): """|coro| Retrieves a list of information about operators - their badge, unique statistic, etc. Returns ------- dict operators""" if self._op_definitions is not None: return self._op_definitions resp =...
def get_operator_index(self, name): """|coro| Gets the operators index from the operator definitions dict Returns ------- str the operator index""" opdefs = yield from self.get_operator_definitions() name = name.lower() if name not in opdefs...
def get_operator_statistic(self, name): """|coro| Gets the operator unique statistic from the operator definitions dict Returns ------- str the name of the operator unique statistic""" opdefs = yield from self.get_operator_definitions() name = name....
def get_operator_badge(self, name): """|coro| Gets the operator badge URL Returns ------- str the operators badge URL""" opdefs = yield from self.get_operator_definitions() name = name.lower() if name not in opdefs: return None ...
def get_definitions(self): """|coro| Retrieves the list of api definitions, downloading it from Ubisoft if it hasn't been fetched all ready Primarily for internal use, but could contain useful information. Returns ------- dict definitions""" if self....
def get_object_index(self, key): """|coro| Mainly for internal use with get_operator, returns the "location" index for the key in the definitions Returns ------- str the object's location index""" defns = yield from self.get_definitions() fo...
def get_charm_url(self): """Get charm URL for the bracket this rank is in Returns ------- :class:`str` the URL for the charm """ if self.rank_id <= 4: return self.RANK_CHARMS[0] if self.rank_id <= 8: return self.RANK_CHARMS[1] if self.rank_id...
def load_level(self): """|coro| Load the players XP and level""" data = yield from self.auth.get("https://public-ubiservices.ubi.com/v1/spaces/%s/sandboxes/%s/r6playerprofile/playerprofile/progressions?profile_ids=%s" % (self.spaceid, self.platform_url, self.id)) if "player_profiles" i...
def load_rank(self, region, season=-1): """|coro| Loads the players rank for this region and season Parameters ---------- region : str the name of the region you want to get the rank for season : Optional[int] the season you want to get the rank f...
def get_rank(self, region, season=-1): """|coro| Checks the players rank for this region, only loading it if it hasn't already been found Parameters ---------- region : str the name of the region you want to get the rank for season : Optional[int] ...
def load_all_operators(self): """|coro| Loads the player stats for all operators Returns ------- dict[:class:`Operator`] the dictionary of all operators found""" statistics = "operatorpvp_kills,operatorpvp_death,operatorpvp_roundwon,operatorpvp_roundlost,ope...
def get_all_operators(self): """|coro| Checks the player stats for all operators, loading them all again if any aren't found This is significantly more efficient than calling get_operator for every operator name. Returns ------- dict[:class:`Operator`] the d...
def load_operator(self, operator): """|coro| Loads the players stats for the operator Parameters ---------- operator : str the name of the operator Returns ------- :class:`Operator` the operator object found""" location =...
def get_operator(self, operator): """|coro| Checks the players stats for this operator, only loading them if they haven't already been found Parameters ---------- operator : str the name of the operator Returns ------- :class:`Operator` ...
def load_weapons(self): """|coro| Load the players weapon stats Returns ------- list[:class:`Weapon`] list of all the weapon objects found""" data = yield from self.auth.get("https://public-ubiservices.ubi.com/v1/spaces/%s/sandboxes/%s/playerstats2/statistic...
def load_gamemodes(self): """|coro| Loads the players gamemode stats Returns ------- dict dict of all the gamemodes found (gamemode_name: :class:`Gamemode`)""" stats = yield from self._fetch_statistics("secureareapvp_matchwon", "secureareapvp_matchlost", "s...
def load_general(self): """|coro| Loads the players general stats""" stats = yield from self._fetch_statistics("generalpvp_timeplayed", "generalpvp_matchplayed", "generalpvp_matchwon", "generalpvp_matchlost", "generalpvp_kills", "generalpvp_dea...
def load_queues(self): """|coro| Loads the players game queues""" stats = yield from self._fetch_statistics("casualpvp_matchwon", "casualpvp_matchlost", "casualpvp_timeplayed", "casualpvp_matchplayed", "casualpvp_kills", "casualpvp_death", ...
def load_terrohunt(self): """|coro| Loads the player's general stats for terrorist hunt""" stats = yield from self._fetch_statistics("generalpve_dbnoassists", "generalpve_death", "generalpve_revive", "generalpve_matchwon", "generalpve_suicide", ...
def execute(self, method, *args, **kargs): result = None ''' max 10 rechecks ''' for i in range(0, 10): try: method_map = { 'get_lead_by_id': self.get_lead_by_id, 'get_multiple_leads_by_filter_type': self.g...
def load_libdmtx(): """Loads the libdmtx shared library. Populates the globals LIBDMTX and EXTERNAL_DEPENDENCIES. """ global LIBDMTX global EXTERNAL_DEPENDENCIES if not LIBDMTX: LIBDMTX = dmtx_library.load() EXTERNAL_DEPENDENCIES = [LIBDMTX] return LIBDMTX
def libdmtx_function(fname, restype, *args): """Returns a foreign function exported by `libdmtx`. Args: fname (:obj:`str`): Name of the exported function as string. restype (:obj:): Return type - one of the `ctypes` primitive C data types. *args: Arguments - a sequence of `ctype...
def load(): """Loads the libdmtx shared library. """ if 'Windows' == platform.system(): # Possible scenarios here # 1. Run from source, DLLs are in pylibdmtx directory # cdll.LoadLibrary() imports DLLs in repo root directory # 2. Wheel install into CPython installat...
def _image(pixels, width, height, pack): """A context manager for `DmtxImage`, created and destroyed by `dmtxImageCreate` and `dmtxImageDestroy`. Args: pixels (:obj:): width (int): height (int): pack (int): Yields: DmtxImage: The created image Raises: ...
def _decoder(image, shrink): """A context manager for `DmtxDecode`, created and destroyed by `dmtxDecodeCreate` and `dmtxDecodeDestroy`. Args: image (POINTER(DmtxImage)): shrink (int): Yields: POINTER(DmtxDecode): The created decoder Raises: PyLibDMTXError: If the ...
def _region(decoder, timeout): """A context manager for `DmtxRegion`, created and destroyed by `dmtxRegionFindNext` and `dmtxRegionDestroy`. Args: decoder (POINTER(DmtxDecode)): timeout (int or None): Yields: DmtxRegion: The next region or None, if all regions have been found. ...
def _decoded_matrix_region(decoder, region, corrections): """A context manager for `DmtxMessage`, created and destoyed by `dmtxDecodeMatrixRegion` and `dmtxMessageDestroy`. Args: decoder (POINTER(DmtxDecode)): region (POINTER(DmtxRegion)): corrections (int): Yields: Dmt...
def _decode_region(decoder, region, corrections, shrink): """Decodes and returns the value in a region. Args: region (DmtxRegion): Yields: Decoded or None: The decoded value. """ with _decoded_matrix_region(decoder, region, corrections) as msg: if msg: # Coordin...
def _pixel_data(image): """Returns (pixels, width, height, bpp) Returns: :obj: `tuple` (pixels, width, height, bpp) """ # Test for PIL.Image and numpy.ndarray without requiring that cv2 or PIL # are installed. if 'PIL.' in str(type(image)): pixels = image.tobytes() width...
def decode(image, timeout=None, gap_size=None, shrink=1, shape=None, deviation=None, threshold=None, min_edge=None, max_edge=None, corrections=None, max_count=None): """Decodes datamatrix barcodes in `image`. Args: image: `numpy.ndarray`, `PIL.Image` or tuple (pixels, width, heigh...
def encode(data, scheme=None, size=None): """ Encodes `data` in a DataMatrix image. For now bpp is the libdmtx default which is 24 Args: data: bytes instance scheme: encoding scheme - one of `ENCODING_SCHEME_NAMES`, or `None`. If `None`, defaults to 'Ascii'. size: i...
def lines(self, Width=1, Color='k'): ''' read the Excel, then draw the wulf net and Plot points, job done~ ''' self.axes.clear() # self.axes.set_xlim(-90, 450) self.axes.set_ylim(0, 90) titles = list('NWSE') titles = ['N', '330', '300', 'W', '240', '210...
def add_edge(edges, edge_points, coords, i, j): """ Add a line between the i-th and j-th points, if not in the list already """ if (i, j) in edges or (j, i) in edges: # already added return( edges.add((i, j)), edge_points.append(coords[[i, j]]))
def alpha_shape(points, alpha): """ Compute the alpha shape (concave hull) of a set of points. @param points: Iterable container of points. @param alpha: alpha value to influence the gooeyness of the border. Smaller numbers don't fall inward as much as larger numbers. Too lar...
def Distance_Calculation(self): print(self.whole_labels) distance_result={} #distance_result[self.whole_labels[i]] = [] print(distance_result) for i in range(len(self.whole_labels)): #print(self.whole_labels[i], self.fa_result[self.result_to_fit.index == self.whol...
def create_main_frame(self): self.main_frame = QWidget() #self.main_frame.setFixedSize(self.width(), self.width()) self.dpi = 128 self.ShapeGroups =200 self.view = gl.GLViewWidget() #self.view = pg.PlotWidget() #self.view.setFixedSize(self.width(),self.height(...
def Magic(self): #self.view.setFixedSize(self.width(), self.width()) self.WholeData = [] self.x_scale = self.width_plot / self.width_load self.y_scale = self.height_plot / self.height_load self.z_scale = self.depth_plot / self.depth_load # print(self.x_scale,' and ...
def create_main_frame(self): self.resize(800, 800) self.main_frame = QWidget() self.dpi = 128 self.fig = Figure((8.0, 8.0), dpi=self.dpi) self.fig.subplots_adjust(hspace=0.5, wspace=0.5, left=0.13, bottom=0.2, right=0.7, top=0.9) self.canvas = FigureCanvas(self.fig)...
def create_main_frame(self): self.resize(800, 1000) self.main_frame = QWidget() self.dpi = 128 self.fig = Figure((12, 11), dpi=self.dpi) self.fig.subplots_adjust(hspace=0.5, wspace=0.5, left=0.1, bottom=0.2, right=0.7, top=0.9) # 8 * np.sqrt(3) self.canvas = Fig...
def TriToBin(self, x, y, z): ''' Turn an x-y-z triangular coord to an a-b coord. if z is negative, calc with its abs then return (a, -b). :param x,y,z: the three numbers of the triangular coord :type x,y,z: float or double are both OK, just numbers :return: the correspo...
def BinToTri(self, a, b): ''' Turn an a-b coord to an x-y-z triangular coord . if z is negative, calc with its abs then return (a, -b). :param a,b: the numbers of the a-b coord :type a,b: float or double are both OK, just numbers :return: the corresponding x-y-z triangu...
def Cross(self, A=[(0, 0), (10, 10)], B=[(0, 10), (100, 0)]): ''' Return the crosspoint of two line A and B. :param A: first line :type A: a list consist of two tuples, beginning and end point of the line :param B: second line :type B: a list consist of two tuples, begin...
def TriCross(self, A=[(100, 0, 0), (0, 50, 60)], B=[(50, 50, 0), (0, 0, 100)]): ''' Return the crosspoint of two line A and B in triangular coord. :param A: first line :type A: a list consist of two tuples, beginning and end point of the line :param B: second line :type ...
def Fill(self, P=[(100, 0), (85, 15), (0, 3)], Color='blue', Alpha=0.3): ''' Fill a region in planimetric rectangular coord. :param P: the peak points of the region in planimetric rectangular coord :type P: a list consist of at least three tuples, which are the points in planimetric rec...
def TriFill(self, P=[(100, 0, 0), (85, 15, 0), (0, 3, 97)], Color='blue', Alpha=0.3): ''' Fill a region in triangular coord. :param P: the peak points of the region in triangular coord :type P: a list consist of at least three tuples, which are the points in triangular coord :p...
def sequence(self): ''' sort the points in the line with given option ''' if (len(self.Points[0]) == 2): if (self.Sort == 'X' or self.Sort == 'x'): self.Points.sort(key=lambda x: x[0]) self.order(self.Points) elif (self.Sort == 'Y'...
def resizeEvent(self, evt=None): w = self.width() h = self.height() ''' if h<=360: h=360 self.resize(w,h) if w<=640: w = 640 self.resize(w, h) ''' step = (w * 94 / 100) / 5 foot = h * 3 / 48
def K2OSiO2(self, Left=35, Right=79, X0=30, X1=90, X_Gap=7, Base=0, Top=19, Y0=1, Y1=19, Y_Gap=19, FontSize=12, xlabel=r'$SiO_2 wt\%$', ylabel=r'$K_2O wt\%$', width=12, height=12, dpi=300): self.setWindowTitle('K2OSiO2 diagram ') self.axes.clear() #self.axes.axis('off') ...
def REE(self, Left=0, Right=16, X0=1, X1=15, X_Gap=15, Base=-1, Top=6, Y0=-1, Y1=3, Y_Gap=5, FontSize=12, xLabel=r'$REE-Standardlized-Pattern$', yLabel='', width=12, height=12, dpi=300): self.axes.clear() self.axes.spines['right'].set_color('none') self.axes....
def create_main_frame(self): self.resize(800, 600) self.main_frame = QWidget() self.dpi = 128 self.save_button = QPushButton('&Save Result') self.save_button.clicked.connect(self.saveResult) self.qapf_button = QPushButton('&QAPF') self.qapf_button.clicked.con...
def singleCalc(self, m={'Al2O3': 13.01, 'Alpha': 0.6, 'Ba': 188.0, 'Be': 0.85, 'CaO': 8.35, 'Ce': 28.2, 'Co': 45.2, 'Cr': 117.0, 'Cs': 0.83, 'Cu': 53.5, 'Dy': 5.58, 'Er': 2.96, 'Eu': 1.79, 'Fe2O3': 14.47, 'FeO': 5.51, 'Ga': 19.4, 'Gd': 5.24, 'Hf': 3.38, 'Ho...
def retranslateUi(self): _translate = QtCore.QCoreApplication.translate self.talk= _translate('MainWindow','You are using GeoPyTool ') + version +'\n'+ _translate('MainWindow','released on ') + date + '\n' self.menuFile.setTitle(_translate('MainWindow', u'Data File')) self.menuGeoChem....
def singlerose(self, Width=1, Color=['red']): ''' draw the rose map of single sample with different items~ ''' self.chooser_label.setText(self.ChooseItems[self.chooser.value() - 1]) self.MultipleRoseName = self.ChooseItems[self.chooser.value() - 1] self.SingleRoseName =...
def multirose(self, Width=1, Name='Dip'): ''' draw the rose map of multiple samples~ ''' Name = self.MultipleRoseName self.axes.clear() # self.axes.set_xlim(-90, 450) # self.axes.set_ylim(0, 90) titles = list('NWSE') titles = ['N', '330', '300'...
def resample(df, rule, time_index, groupby=None, aggregation='mean'): """pd.DataFrame.resample adapter. Call the `df.resample` method on the given time_index and afterwards call the indicated aggregation. Optionally group the dataframe by the indicated columns before performing the resampling. ...
def _join_names(names): """Join the names of a multi-level index with an underscore.""" levels = (str(name) for name in names if name != '') return '_'.join(levels)
def unstack(df, level=-1, reset_index=True): """pd.DataFrame.unstack adapter. Call the `df.unstack` method using the indicated level and afterwards join the column names using an underscore. Args: df (pandas.DataFrame): DataFrame to unstack. level (str, int or list): Level(s) of index ...
def next_power_of_2(x): """Finds the next power of 2 value Args: x: Input value Returns: power_of_2: Next power of 2 value """ power_of_2 = 1 if x == 0 else 2 ** np.ceil(np.log2(x)) return power_of_2
def window_design(self, window_length, beta): """Kaiser window design Args: window_length: Length of the window in number of samples beta: Beta value for Kaiser window design Returns: window: Window designed using the beta and length provided as inpu...
def fit(self, X): """Defines a spectral mask based on training data Args: X: Training data """ training_signal = X self.window_design(self.window_length, self.beta) if self.method == 'std_dev': self.fit_freq_std_dev(training_signa...
def fit_freq_min_max(self, training_signal): """Defines a spectral mask based on training data using min and max values of each frequency component Args: training_signal: Training data """ window_length = len(self.window) window_weight = sum(...
def fit_freq_std_dev(self, training_signal): """Defines a spectral mask based on training data using the standard deviation values of each frequency component Args: training_signal: Training data """ window_length = len(self.window) window_we...
def produce(self, X): """Detects anomalies in telemetry data based on its power spectral density Args: X: Telemetry data Returns: anomalies: Data vector consisting of the anomalies detected in the telemetry data """ signal = X win...
def load_boston_multitask(): """Boston House Prices Dataset with a synthetic multitask output. The multitask output is obtained by applying a linear transformation to the original y and adding it as a second output column. """ dataset = datasets.load_boston() y = dataset.target target = np....
def energy(data): """Computes signal energy of data""" data = np.mean(data, axis=1) return np.sum(data ** 2) / np.float64(len(data))
def spectral_entropy(data, numOfShortBlocks=10): """Computes the spectral entropy""" data = np.mean(data, axis=1) nFFT = len(data) // 2 X = FFT(data, nFFT) L = len(X) # number of frame data Eol = np.sum(X ** 2) # total spectral energy subWinLength = int(n...
def zcr(data): """Computes zero crossing rate of segment""" data = np.mean(data, axis=1) count = len(data) countZ = np.sum(np.abs(np.diff(np.sign(data)))) / 2 return (np.float64(countZ) / np.float64(count - 1.0))
def spectral_flux(d0, d1): """ Computes the spectral flux feature of the current frame """ # compute the spectral flux as the sum of square distances: d0 = np.mean(d0, axis=1) d1 = np.mean(d1, axis=1) nFFT = min(len(d0) // 2, len(d1) // 2) X = FFT(d0, nFFT) Xprev = FFT(d1, nFFT) ...
def energy_entropy(data, fs, numOfShortBlocks=10): """Computes entropy of energy""" data = np.mean(data, axis=1) Eol = np.sum(data ** 2) # total data energy L = len(data) subWinLength = int(np.floor(L / numOfShortBlocks)) if L != subWinLength * numOfShortBlocks: data = data[0:subWinL...
def spectral_centroid_and_spread(data, fs): """Computes spectral centroid of frame (given abs(FFT))""" data = np.mean(data, axis=1) nFFT = len(data) // 2 X = FFT(data, nFFT) ind = (np.arange(1, len(X) + 1)) * (fs / (2.0 * len(X))) Xt = X.copy() Xt = Xt / Xt.max() NUM = np.sum(ind * Xt...
def spectral_rolloff(data, coeff): """Computes spectral roll-off""" data = np.mean(data, axis=1) nFFT = len(data) // 2 X = FFT(data, nFFT) totalEnergy = np.sum(X ** 2) fftLength = len(X) Thres = coeff * totalEnergy # Find the spectral rolloff as the frequency position where the # r...
def rolling_window_sequences(X, index, window_size, target_size, target_column): """Create rolling window sequences out of timeseries data.""" out_X = list() out_y = list() X_index = list() y_index = list() target = X[:, target_column] for start in range(len(X) - window_size - target_size ...
def time_segments_average(X, interval, time_column): """Compute average of values over fixed length time segments.""" warnings.warn(_TIME_SEGMENTS_AVERAGE_DEPRECATION_WARNING, DeprecationWarning) if isinstance(X, np.ndarray): X = pd.DataFrame(X) X = X.sort_values(time_column).set_index(time_co...
def time_segments_aggregate(X, interval, time_column, method=['mean']): """Aggregate values over fixed length time segments.""" if isinstance(X, np.ndarray): X = pd.DataFrame(X) X = X.sort_values(time_column).set_index(time_column) if isinstance(method, str): method = [method] sta...
def image_transform(X, function, reshape_before=False, reshape_after=False, width=None, height=None, **kwargs): """Apply a function image by image. Args: reshape_before: whether 1d array needs to be reshaped to a 2d image reshape_after: whether the returned values need to be...
def regression_errors(y, y_hat, smoothing_window=0.01, smooth=True): """Compute an array of absolute errors comparing predictions and expected output. If smooth is True, apply EWMA to the resulting array of errors. Args: y (array): Ground truth. y_hat (array): Predictions array. sm...
def deltas(errors, epsilon, mean, std): """Compute mean and std deltas. delta_mean = mean(errors) - mean(all errors below epsilon) delta_std = std(errors) - std(all errors below epsilon) """ below = errors[errors <= epsilon] if not len(below): return 0, 0 return mean - below.mean()...
def count_above(errors, epsilon): """Count number of errors and continuous sequences above epsilon. Continuous sequences are counted by shifting and counting the number of positions where there was a change and the original value was true, which means that a sequence started at that position. """ ...
def z_cost(z, errors, mean, std): """Compute how bad a z value is. The original formula is:: (delta_mean/mean) + (delta_std/std) ------------------------------------------------------ number of errors above + (number of sequences above)^2 which computes the "goodness" of ...
def find_threshold(errors, z_range=(0, 10)): """Find the ideal threshold. The ideal threshold is the one that minimizes the z_cost function. """ mean = errors.mean() std = errors.std() min_z, max_z = z_range best_z = min_z best_cost = np.inf for z in range(min_z, max_z): b...
def find_sequences(errors, epsilon): """Find sequences of values that are above epsilon. This is done following this steps: * create a boolean mask that indicates which value are above epsilon. * shift this mask by one place, filing the empty gap with a False * compare the shifted mask...
def find_anomalies(errors, index, z_range=(0, 10)): """Find sequences of values that are anomalous. We first find the ideal threshold for the set of errors that we have, and then find the sequences of values that are above this threshold. Lastly, we compute a score proportional to the maximum error in...
def GaussianBlur(X, ksize_width, ksize_height, sigma_x, sigma_y): """Apply Gaussian blur to the given data. Args: X: data to blur kernel_size: Gaussian kernel size stddev: Gaussian kernel standard deviation (in both X and Y directions) """ return image_transform( X, ...
def rolling_window_sequences(X, window_size, target_size, value_column, time_column): """ Function that takes in a pandas.DataFrame and a window_size then creates output arrays that correspond to a timeseries sequence with window_size overlap. The output arrays can be fed into a time...
def time_segments_average(X, interval, value_column, time_column): """ function that aggregates data in a pandas dataframe by averaging over a given interval. it starts averaging from the smallest timestamp in the dataframe and ends at the largest timestamp. assumes the input is time...
def get_forecast_errors(y_hat, y_true, window_size=5, batch_size=30, smoothing_percent=0.05, smoothed=True): """ Calculates the forecasting error for two arrays of data. If smoothed errors des...
def extract_anomalies(y_true, smoothed_errors, window_size, batch_size, error_buffer): """ Extracts anomalies from the errors. Args: y_true (): smoothed_errors (): window_size (int): batch_size (int): error_buffer (int): Returns: ...
def compute_threshold(smoothed_errors, error_buffer, sd_limit=12.0): """Helper method for `extract_anomalies` method. Calculates the epsilon (threshold) for anomalies. """ mu = np.mean(smoothed_errors) sigma = np.std(smoothed_errors) max_epsilon = 0 sd_threshold = sd_limit # The tresho...
def get_anomalies(smoothed_errors, y_true, z, window, all_anomalies, error_buffer): """ Helper method to get anomalies. """ mu = np.mean(smoothed_errors) sigma = np.std(smoothed_errors) epsilon = mu + (z * sigma) # compare to epsilon errors_seq, anomaly_indices, max_error_below_e ...
def prune_anomalies(e_seq, smoothed_errors, max_error_below_e, anomaly_indices): """ Helper method that removes anomalies which don't meet a minimum separation from next anomaly. """ # min accepted perc decrease btwn max errors in anomalous sequences MIN_PERCENT_DECREASE = 0.05 e_seq_max, sm...
def _configure_nodes(self, nodes): """Parse and set up the given nodes. :param nodes: nodes used to create the continuum (see doc for format). """ if isinstance(nodes, str): nodes = [nodes] elif not isinstance(nodes, (dict, list)): raise ValueError( ...
def _get_pos(self, key): """Get the index of the given key in the sorted key list. We return the position with the nearest hash based on the provided key unless we reach the end of the continuum/ring in which case we return the 0 (beginning) index position. :param key: the key ...
def _get(self, key, what): """Generic getter magic method. The node with the nearest but not less hash value is returned. :param key: the key to look for. :param what: the information to look for in, allowed values: - instance (default): associated node instance ...
def get_instances(self): """Returns a list of the instances of all the configured nodes. """ return [c.get('instance') for c in self.runtime._nodes.values() if c.get('instance')]
def get_points(self): """Returns a ketama compatible list of (position, nodename) tuples. """ return [(k, self.runtime._ring[k]) for k in self.runtime._keys]
def iterate_nodes(self, key, distinct=True): """hash_ring compatibility implementation. Given a string key it returns the nodes as a generator that can hold the key. The generator iterates one time through the ring starting at the correct position. if `distinct` is set, ...
def print_continuum(self): """Prints a ketama compatible continuum report. """ numpoints = len(self.runtime._keys) if numpoints: print('Numpoints in continuum: {}'.format(numpoints)) else: print('Continuum empty') for p in self.get_points(): ...