_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q500
load_parcellation_coords
train
def load_parcellation_coords(parcellation_name): """ Loads coordinates of included parcellations. Parameters ---------- parcellation_name : str options: 'gordon2014_333', 'power2012_264', 'shen2013_278'. Returns ------- parc : array parcellation cordinates """ ...
python
{ "resource": "" }
q501
create_traj_ranges
train
def create_traj_ranges(start, stop, N): """ Fills in the trajectory range. # Adapted from https://stackoverflow.com/a/40624614 """ steps = (1.0/(N-1)) * (stop - start) if np.isscalar(steps): return steps*np.arange(N) + start else: return steps[:, None]*np.arange(N) + start[:...
python
{ "resource": "" }
q502
get_dimord
train
def get_dimord(measure, calc=None, community=None): """ Get the dimension order of a network measure. Parameters ---------- measure : str Name of funciton in teneto.networkmeasures. calc : str, default=None Calc parameter for the function community : bool, default=None ...
python
{ "resource": "" }
q503
create_supraadjacency_matrix
train
def create_supraadjacency_matrix(tnet, intersliceweight=1): """ Returns a supraadjacency matrix from a temporal network structure Parameters -------- tnet : TemporalNetwork Temporal network (any network type) intersliceweight : int Weight that links the same node from adjacent t...
python
{ "resource": "" }
q504
tnet_to_nx
train
def tnet_to_nx(df, t=None): """ Creates undirected networkx object """ if t is not None: df = get_network_when(df, t=t) if 'weight' in df.columns: nxobj = nx.from_pandas_edgelist( df, source='i', target='j', edge_attr='weight') else: nxobj = nx.from_pandas_edg...
python
{ "resource": "" }
q505
temporal_louvain
train
def temporal_louvain(tnet, resolution=1, intersliceweight=1, n_iter=100, negativeedge='ignore', randomseed=None, consensus_threshold=0.5, temporal_consensus=True, njobs=1): r""" Louvain clustering for a temporal network. Parameters ----------- tnet : array, dict, TemporalNetwork Input netwo...
python
{ "resource": "" }
q506
make_temporal_consensus
train
def make_temporal_consensus(com_membership): r""" Matches community labels accross time-points Jaccard matching is in a greedy fashiong. Matching the largest community at t with the community at t-1. Parameters ---------- com_membership : array Shape should be node, time. Returns...
python
{ "resource": "" }
q507
flexibility
train
def flexibility(communities): """ Amount a node changes community Parameters ---------- communities : array Community array of shape (node,time) Returns -------- flex : array Size with the flexibility of each node. Notes ----- Flexbility calculates the numb...
python
{ "resource": "" }
q508
load_tabular_file
train
def load_tabular_file(fname, return_meta=False, header=True, index_col=True): """ Given a file name loads as a pandas data frame Parameters ---------- fname : str file name and path. Must be tsv. return_meta : header : bool (default True) if there is a header in the tsv fil...
python
{ "resource": "" }
q509
get_sidecar
train
def get_sidecar(fname, allowedfileformats='default'): """ Loads sidecar or creates one """ if allowedfileformats == 'default': allowedfileformats = ['.tsv', '.nii.gz'] for f in allowedfileformats: fname = fname.split(f)[0] fname += '.json' if os.path.exists(fname): wi...
python
{ "resource": "" }
q510
process_exclusion_criteria
train
def process_exclusion_criteria(exclusion_criteria): """ Parses an exclusion critera string to get the function and threshold. Parameters ---------- exclusion_criteria : list list of strings where each string is of the format [relation][threshold]. E.g. \'<0.5\' or \'>=1\' Retur...
python
{ "resource": "" }
q511
reachability_latency
train
def reachability_latency(tnet=None, paths=None, rratio=1, calc='global'): """ Reachability latency. This is the r-th longest temporal path. Parameters --------- data : array or dict Can either be a network (graphlet or contact), binary unidrected only. Alternative can be a paths dictionar...
python
{ "resource": "" }
q512
recruitment
train
def recruitment(temporalcommunities, staticcommunities): """ Calculates recruitment coefficient for each node. Recruitment coefficient is the average probability of nodes from the same static communities being in the same temporal communities at other time-points or during different tasks. Parameters...
python
{ "resource": "" }
q513
integration
train
def integration(temporalcommunities, staticcommunities): """ Calculates the integration coefficient for each node. Measures the average probability that a node is in the same community as nodes from other systems. Parameters: ------------ temporalcommunities : array temporal co...
python
{ "resource": "" }
q514
intercontacttimes
train
def intercontacttimes(tnet): """ Calculates the intercontacttimes of each edge in a network. Parameters ----------- tnet : array, dict Temporal network (craphlet or contact). Nettype: 'bu', 'bd' Returns --------- contacts : dict Intercontact times as numpy array in di...
python
{ "resource": "" }
q515
gen_report
train
def gen_report(report, sdir='./', report_name='report.html'): """ Generates report of derivation and postprocess steps in teneto.derive """ # Create report directory if not os.path.exists(sdir): os.makedirs(sdir) # Add a slash to file directory if not included to avoid DirNameFleName ...
python
{ "resource": "" }
q516
TenetoBIDS.add_history
train
def add_history(self, fname, fargs, init=0): """ Adds a processing step to TenetoBIDS.history. """ if init == 1: self.history = [] self.history.append([fname, fargs])
python
{ "resource": "" }
q517
TenetoBIDS.derive_temporalnetwork
train
def derive_temporalnetwork(self, params, update_pipeline=True, tag=None, njobs=1, confound_corr_report=True): """ Derive time-varying connectivity on the selected files. Parameters ---------- params : dict. See teneto.timeseries.derive_temporalnetwork for the structu...
python
{ "resource": "" }
q518
TenetoBIDS.make_functional_connectivity
train
def make_functional_connectivity(self, njobs=None, returngroup=False, file_hdr=None, file_idx=None): """ Makes connectivity matrix for each of the subjects. Parameters ---------- returngroup : bool, default=False If true, returns the group average connectivity matrix...
python
{ "resource": "" }
q519
TenetoBIDS._save_namepaths_bids_derivatives
train
def _save_namepaths_bids_derivatives(self, f, tag, save_directory, suffix=None): """ Creates output directory and output name Paramters --------- f : str input files, includes the file bids_suffix tag : str what should be added to f in the output ...
python
{ "resource": "" }
q520
TenetoBIDS.get_tags
train
def get_tags(self, tag, quiet=1): """ Returns which tag alternatives can be identified in the BIDS derivatives structure. """ if not self.pipeline: print('Please set pipeline first.') self.get_pipeline_alternatives(quiet) else: if tag == 'sub':...
python
{ "resource": "" }
q521
TenetoBIDS.set_exclusion_file
train
def set_exclusion_file(self, confound, exclusion_criteria, confound_stat='mean'): """ Excludes subjects given a certain exclusion criteria. Parameters ---------- confound : str or list string or list of confound name(s) from confound files exclusi...
python
{ "resource": "" }
q522
TenetoBIDS.make_parcellation
train
def make_parcellation(self, parcellation, parc_type=None, parc_params=None, network='defaults', update_pipeline=True, removeconfounds=False, tag=None, njobs=None, clean_params=None, yeonetworkn=None): """ Reduces the data from voxel to parcellation space. Files get saved in a teneto folder in the deriva...
python
{ "resource": "" }
q523
TenetoBIDS.communitydetection
train
def communitydetection(self, community_detection_params, community_type='temporal', tag=None, file_hdr=False, file_idx=False, njobs=None): """ Calls temporal_louvain_with_consensus on connectivity data Parameters ---------- community_detection_params : dict kwargs f...
python
{ "resource": "" }
q524
TenetoBIDS.removeconfounds
train
def removeconfounds(self, confounds=None, clean_params=None, transpose=None, njobs=None, update_pipeline=True, overwrite=True, tag=None): """ Removes specified confounds using nilearn.signal.clean Parameters ---------- confounds : list List of confounds. Can be presp...
python
{ "resource": "" }
q525
TenetoBIDS.networkmeasures
train
def networkmeasures(self, measure=None, measure_params=None, tag=None, njobs=None): """ Calculates a network measure For available funcitons see: teneto.networkmeasures Parameters ---------- measure : str or list Mame of function(s) from teneto.networkmeasu...
python
{ "resource": "" }
q526
TenetoBIDS.set_bids_suffix
train
def set_bids_suffix(self, bids_suffix): """ The last analysis step is the final tag that is present in files. """ self.add_history(inspect.stack()[0][3], locals(), 1) self.bids_suffix = bids_suffix
python
{ "resource": "" }
q527
TenetoBIDS.set_pipeline
train
def set_pipeline(self, pipeline): """ Specify the pipeline. See get_pipeline_alternatives to see what are avaialble. Input should be a string. """ self.add_history(inspect.stack()[0][3], locals(), 1) if not os.path.exists(self.BIDS_dir + '/derivatives/' + pipeline): p...
python
{ "resource": "" }
q528
TenetoBIDS.load_frompickle
train
def load_frompickle(cls, fname, reload_object=False): """ Loaded saved instance of fname : str path to pickle object (output of TenetoBIDS.save_aspickle) reload_object : bool (default False) reloads object by calling teneto.TenetoBIDS (some information lost, for ...
python
{ "resource": "" }
q529
temporal_closeness_centrality
train
def temporal_closeness_centrality(tnet=None, paths=None): ''' Returns temporal closeness centrality per node. Parameters ----------- Input should be *either* tnet or paths. data : array or dict Temporal network input (graphlet or contact). nettype: 'bu', 'bd'. paths : pandas dat...
python
{ "resource": "" }
q530
flatten
train
def flatten(d, reducer='tuple', inverse=False): """Flatten dict-like object. Parameters ---------- d: dict-like object The dict that will be flattened. reducer: {'tuple', 'path', function} (default: 'tuple') The key joining method. If a function is given, the function will be ...
python
{ "resource": "" }
q531
nested_set_dict
train
def nested_set_dict(d, keys, value): """Set a value to a sequence of nested keys Parameters ---------- d: Mapping keys: Sequence[str] value: Any """ assert keys key = keys[0] if len(keys) == 1: if key in d: raise ValueError("duplicated key '{}'".format(key)) ...
python
{ "resource": "" }
q532
unflatten
train
def unflatten(d, splitter='tuple', inverse=False): """Unflatten dict-like object. Parameters ---------- d: dict-like object The dict that will be unflattened. splitter: {'tuple', 'path', function} (default: 'tuple') The key splitting method. If a function is given, the function will...
python
{ "resource": "" }
q533
plot_track
train
def plot_track(track, filename=None, beat_resolution=None, downbeats=None, preset='default', cmap='Blues', xtick='auto', ytick='octave', xticklabel=True, yticklabel='auto', tick_loc=None, tick_direction='in', label='both', grid='both', grid_linestyle=':', grid...
python
{ "resource": "" }
q534
Multitrack.append_track
train
def append_track(self, track=None, pianoroll=None, program=0, is_drum=False, name='unknown'): """ Append a multitrack.Track instance to the track list or create a new multitrack.Track object and append it to the track list. Parameters ---------- trac...
python
{ "resource": "" }
q535
Multitrack.check_validity
train
def check_validity(self): """ Raise an error if any invalid attribute found. Raises ------ TypeError If an attribute has an invalid type. ValueError If an attribute has an invalid value (of the correct type). """ # tracks ...
python
{ "resource": "" }
q536
Multitrack.clip
train
def clip(self, lower=0, upper=127): """ Clip the pianorolls of all tracks by the given lower and upper bounds. Parameters ---------- lower : int or float The lower bound to clip the pianorolls. Defaults to 0. upper : int or float The upper bound t...
python
{ "resource": "" }
q537
Multitrack.get_downbeat_steps
train
def get_downbeat_steps(self): """ Return the indices of time steps that contain downbeats. Returns ------- downbeat_steps : list The indices of time steps that contain downbeats. """ if self.downbeat is None: return [] downbeat_st...
python
{ "resource": "" }
q538
Multitrack.get_empty_tracks
train
def get_empty_tracks(self): """ Return the indices of tracks with empty pianorolls. Returns ------- empty_track_indices : list The indices of tracks with empty pianorolls. """ empty_track_indices = [idx for idx, track in enumerate(self.tracks) ...
python
{ "resource": "" }
q539
Multitrack.get_merged_pianoroll
train
def get_merged_pianoroll(self, mode='sum'): """ Return the merged pianoroll. Parameters ---------- mode : {'sum', 'max', 'any'} A string that indicates the merging strategy to apply along the track axis. Default to 'sum'. - In 'sum' mode, the...
python
{ "resource": "" }
q540
Multitrack.merge_tracks
train
def merge_tracks(self, track_indices=None, mode='sum', program=0, is_drum=False, name='merged', remove_merged=False): """ Merge pianorolls of the tracks specified by `track_indices`. The merged track will have program number as given by `program` and drum indicator a...
python
{ "resource": "" }
q541
Multitrack.pad_to_same
train
def pad_to_same(self): """Pad shorter pianorolls with zeros at the end along the time axis to make the resulting pianoroll lengths the same as the maximum pianoroll length among all the tracks.""" max_length = self.get_max_length() for track in self.tracks: if track.p...
python
{ "resource": "" }
q542
Multitrack.remove_tracks
train
def remove_tracks(self, track_indices): """ Remove tracks specified by `track_indices`. Parameters ---------- track_indices : list The indices of the tracks to be removed. """ if isinstance(track_indices, int): track_indices = [track_indi...
python
{ "resource": "" }
q543
Multitrack.transpose
train
def transpose(self, semitone): """ Transpose the pianorolls of all tracks by a number of semitones, where positive values are for higher key, while negative values are for lower key. The drum tracks are ignored. Parameters ---------- semitone : int Th...
python
{ "resource": "" }
q544
Multitrack.trim_trailing_silence
train
def trim_trailing_silence(self): """Trim the trailing silences of the pianorolls of all tracks. Trailing silences are considered globally.""" active_length = self.get_active_length() for track in self.tracks: track.pianoroll = track.pianoroll[:active_length]
python
{ "resource": "" }
q545
Multitrack.write
train
def write(self, filename): """ Write the multitrack pianoroll to a MIDI file. Parameters ---------- filename : str The name of the MIDI file to which the multitrack pianoroll is written. """ if not filename.endswith(('.mid', '.midi', '.MI...
python
{ "resource": "" }
q546
check_pianoroll
train
def check_pianoroll(arr): """ Return True if the array is a standard piano-roll matrix. Otherwise, return False. Raise TypeError if the input object is not a numpy array. """ if not isinstance(arr, np.ndarray): raise TypeError("`arr` must be of np.ndarray type") if not (np.issubdtype(ar...
python
{ "resource": "" }
q547
pad
train
def pad(obj, pad_length): """ Return a copy of the object with piano-roll padded with zeros at the end along the time axis. Parameters ---------- pad_length : int The length to pad along the time axis with zeros. """ _check_supported(obj) copied = deepcopy(obj) copied.p...
python
{ "resource": "" }
q548
pad_to_multiple
train
def pad_to_multiple(obj, factor): """ Return a copy of the object with its piano-roll padded with zeros at the end along the time axis with the minimal length that make the length of the resulting piano-roll a multiple of `factor`. Parameters ---------- factor : int The value which ...
python
{ "resource": "" }
q549
pad_to_same
train
def pad_to_same(obj): """ Return a copy of the object with shorter piano-rolls padded with zeros at the end along the time axis to the length of the piano-roll with the maximal length. """ if not isinstance(obj, Multitrack): raise TypeError("Support only `pypianoroll.Multitrack` class o...
python
{ "resource": "" }
q550
save
train
def save(filepath, obj, compressed=True): """ Save the object to a .npz file. Parameters ---------- filepath : str The path to save the file. obj: `pypianoroll.Multitrack` objects The object to be saved. """ if not isinstance(obj, Multitrack): raise TypeError("S...
python
{ "resource": "" }
q551
write
train
def write(obj, filepath): """ Write the object to a MIDI file. Parameters ---------- filepath : str The path to write the MIDI file. """ if not isinstance(obj, Multitrack): raise TypeError("Support only `pypianoroll.Multitrack` class objects") obj.write(filepath)
python
{ "resource": "" }
q552
_validate_pianoroll
train
def _validate_pianoroll(pianoroll): """Raise an error if the input array is not a standard pianoroll.""" if not isinstance(pianoroll, np.ndarray): raise TypeError("`pianoroll` must be of np.ndarray type.") if not (np.issubdtype(pianoroll.dtype, np.bool_) or np.issubdtype(pianoroll.dtype,...
python
{ "resource": "" }
q553
_to_chroma
train
def _to_chroma(pianoroll): """Return the unnormalized chroma features of a pianoroll.""" _validate_pianoroll(pianoroll) reshaped = pianoroll[:, :120].reshape(-1, 12, 10) reshaped[..., :8] += pianoroll[:, 120:].reshape(-1, 1, 8) return np.sum(reshaped, 1)
python
{ "resource": "" }
q554
empty_beat_rate
train
def empty_beat_rate(pianoroll, beat_resolution): """Return the ratio of empty beats to the total number of beats in a pianoroll.""" _validate_pianoroll(pianoroll) reshaped = pianoroll.reshape(-1, beat_resolution * pianoroll.shape[1]) n_empty_beats = np.count_nonzero(reshaped.any(1)) return n_emp...
python
{ "resource": "" }
q555
n_pitche_classes_used
train
def n_pitche_classes_used(pianoroll): """Return the number of unique pitch classes used in a pianoroll.""" _validate_pianoroll(pianoroll) chroma = _to_chroma(pianoroll) return np.count_nonzero(np.any(chroma, 0))
python
{ "resource": "" }
q556
polyphonic_rate
train
def polyphonic_rate(pianoroll, threshold=2): """Return the ratio of the number of time steps where the number of pitches being played is larger than `threshold` to the total number of time steps in a pianoroll.""" _validate_pianoroll(pianoroll) n_poly = np.count_nonzero(np.count_nonzero(pianoroll, 1...
python
{ "resource": "" }
q557
in_scale_rate
train
def in_scale_rate(pianoroll, key=3, kind='major'): """Return the ratio of the number of nonzero entries that lie in a specific scale to the total number of nonzero entries in a pianoroll. Default to C major scale.""" if not isinstance(key, int): raise TypeError("`key` must an integer.") if k...
python
{ "resource": "" }
q558
Track.assign_constant
train
def assign_constant(self, value, dtype=None): """ Assign a constant value to all nonzeros in the pianoroll. If the pianoroll is not binarized, its data type will be preserved. If the pianoroll is binarized, it will be casted to the type of `value`. Arguments --------- ...
python
{ "resource": "" }
q559
Track.binarize
train
def binarize(self, threshold=0): """ Binarize the pianoroll. Parameters ---------- threshold : int or float A threshold used to binarize the pianorolls. Defaults to zero. """ if not self.is_binarized(): self.pianoroll = (self.pianoroll > ...
python
{ "resource": "" }
q560
Track.check_validity
train
def check_validity(self): """"Raise error if any invalid attribute found.""" # pianoroll if not isinstance(self.pianoroll, np.ndarray): raise TypeError("`pianoroll` must be a numpy array.") if not (np.issubdtype(self.pianoroll.dtype, np.bool_) or np.issubdtype...
python
{ "resource": "" }
q561
Track.clip
train
def clip(self, lower=0, upper=127): """ Clip the pianoroll by the given lower and upper bounds. Parameters ---------- lower : int or float The lower bound to clip the pianoroll. Defaults to 0. upper : int or float The upper bound to clip the piano...
python
{ "resource": "" }
q562
Track.is_binarized
train
def is_binarized(self): """ Return True if the pianoroll is already binarized. Otherwise, return False. Returns ------- is_binarized : bool True if the pianoroll is already binarized; otherwise, False. """ is_binarized = np.issubdtype(self.pi...
python
{ "resource": "" }
q563
Track.pad
train
def pad(self, pad_length): """ Pad the pianoroll with zeros at the end along the time axis. Parameters ---------- pad_length : int The length to pad with zeros along the time axis. """ self.pianoroll = np.pad( self.pianoroll, ((0, pad_len...
python
{ "resource": "" }
q564
Track.pad_to_multiple
train
def pad_to_multiple(self, factor): """ Pad the pianoroll with zeros at the end along the time axis with the minimum length that makes the resulting pianoroll length a multiple of `factor`. Parameters ---------- factor : int The value which the length ...
python
{ "resource": "" }
q565
Track.transpose
train
def transpose(self, semitone): """ Transpose the pianoroll by a number of semitones, where positive values are for higher key, while negative values are for lower key. Parameters ---------- semitone : int The number of semitones to transpose the pianoroll. ...
python
{ "resource": "" }
q566
Track.trim_trailing_silence
train
def trim_trailing_silence(self): """Trim the trailing silence of the pianoroll.""" length = self.get_active_length() self.pianoroll = self.pianoroll[:length]
python
{ "resource": "" }
q567
plot_conv_weights
train
def plot_conv_weights(layer, figsize=(6, 6)): """Plot the weights of a specific layer. Only really makes sense with convolutional layers. Parameters ---------- layer : lasagne.layers.Layer """ W = layer.W.get_value() shape = W.shape nrows = np.ceil(np.sqrt(shape[0])).astype(int) ...
python
{ "resource": "" }
q568
plot_conv_activity
train
def plot_conv_activity(layer, x, figsize=(6, 8)): """Plot the acitivities of a specific layer. Only really makes sense with layers that work 2D data (2D convolutional layers, 2D pooling layers ...). Parameters ---------- layer : lasagne.layers.Layer x : numpy.ndarray Only takes one ...
python
{ "resource": "" }
q569
occlusion_heatmap
train
def occlusion_heatmap(net, x, target, square_length=7): """An occlusion test that checks an image for its critical parts. In this function, a square part of the image is occluded (i.e. set to 0) and then the net is tested for its propensity to predict the correct label. One should expect that this prop...
python
{ "resource": "" }
q570
plot_occlusion
train
def plot_occlusion(net, X, target, square_length=7, figsize=(9, None)): """Plot which parts of an image are particularly import for the net to classify the image correctly. See paper: Zeiler, Fergus 2013 Parameters ---------- net : NeuralNet instance The neural net to test. X : nump...
python
{ "resource": "" }
q571
multiclass_logloss
train
def multiclass_logloss(actual, predicted, eps=1e-15): """Multi class version of Logarithmic Loss metric. :param actual: Array containing the actual target classes :param predicted: Matrix with class predictions, one probability per class """ # Convert 'actual' to a binary array if it's not already:...
python
{ "resource": "" }
q572
objective
train
def objective(layers, loss_function, target, aggregate=aggregate, deterministic=False, l1=0, l2=0, get_output_kw=None): """ Default implementation of the NeuralNet objective. :param layers: The underlying laye...
python
{ "resource": "" }
q573
NeuralNet.initialize
train
def initialize(self): """Initializes the network. Checks that no extra kwargs were passed to the constructor, and compiles the train, predict, and evaluation functions. Subsequent calls to this function will return without any action. """ if getattr(self, '_initialized'...
python
{ "resource": "" }
q574
NeuralNet.fit
train
def fit(self, X, y, epochs=None): """ Runs the training loop for a given number of epochs :param X: The input data :param y: The ground truth :param epochs: The number of epochs to run, if `None` runs for the network's :attr:`max_epochs` :return:...
python
{ "resource": "" }
q575
NeuralNet.partial_fit
train
def partial_fit(self, X, y, classes=None): """ Runs a single epoch using the provided data :return: This instance """ return self.fit(X, y, epochs=1)
python
{ "resource": "" }
q576
ByDateQuerySetMixin.narrow
train
def narrow(self, **kwargs): """Up-to including""" from_date = kwargs.pop('from_date', None) to_date = kwargs.pop('to_date', None) date = kwargs.pop('date', None) qs = self if from_date: qs = qs.filter(date__gte=from_date) if to_date: qs = q...
python
{ "resource": "" }
q577
set_environment_variables
train
def set_environment_variables(json_file_path): """ Read and set environment variables from a flat json file. Bear in mind that env vars set this way and later on read using `os.getenv` function will be strings since after all env vars are just that - plain strings. Json file example: ``` ...
python
{ "resource": "" }
q578
millis_interval
train
def millis_interval(start, end): """start and end are datetime instances""" diff = end - start millis = diff.days * 24 * 60 * 60 * 1000 millis += diff.seconds * 1000 millis += diff.microseconds / 1000 return millis
python
{ "resource": "" }
q579
Script._import_lua
train
def _import_lua(load_dependencies=True): """ Import lua and dependencies. :param load_dependencies: should Lua library dependencies be loaded? :raises: RuntimeError if Lua is not available """ try: import lua except ImportError: raise Runt...
python
{ "resource": "" }
q580
Script._import_lua_dependencies
train
def _import_lua_dependencies(lua, lua_globals): """ Imports lua dependencies that are supported by redis lua scripts. The current implementation is fragile to the target platform and lua version and may be disabled if these imports are not needed. Included: - cjson ...
python
{ "resource": "" }
q581
MockRedis.lock
train
def lock(self, key, timeout=0, sleep=0): """Emulate lock.""" return MockRedisLock(self, key, timeout, sleep)
python
{ "resource": "" }
q582
MockRedis.keys
train
def keys(self, pattern='*'): """Emulate keys.""" # making sure the pattern is unicode/str. try: pattern = pattern.decode('utf-8') # This throws an AttributeError in python 3, or an # UnicodeEncodeError in python 2 except (AttributeError, UnicodeEncodeE...
python
{ "resource": "" }
q583
MockRedis.delete
train
def delete(self, *keys): """Emulate delete.""" key_counter = 0 for key in map(self._encode, keys): if key in self.redis: del self.redis[key] key_counter += 1 if key in self.timeouts: del self.timeouts[key] return key...
python
{ "resource": "" }
q584
MockRedis.do_expire
train
def do_expire(self): """ Expire objects assuming now == time """ # Deep copy to avoid RuntimeError: dictionary changed size during iteration _timeouts = deepcopy(self.timeouts) for key, value in _timeouts.items(): if value - self.clock.now() < timedelta(0): ...
python
{ "resource": "" }
q585
MockRedis.set
train
def set(self, key, value, ex=None, px=None, nx=False, xx=False): """ Set the ``value`` for the ``key`` in the context of the provided kwargs. As per the behavior of the redis-py lib: If nx and xx are both set, the function does nothing and None is returned. If px and ex are both...
python
{ "resource": "" }
q586
MockRedis._should_set
train
def _should_set(self, key, mode): """ Determine if it is okay to set a key. If the mode is None, returns True, otherwise, returns True of false based on the value of ``key`` and the ``mode`` (nx | xx). """ if mode is None or mode not in ["nx", "xx"]: return ...
python
{ "resource": "" }
q587
MockRedis.setex
train
def setex(self, name, time, value): """ Set the value of ``name`` to ``value`` that expires in ``time`` seconds. ``time`` can be represented by an integer or a Python timedelta object. """ if not self.strict: # when not strict mode swap value and time args ord...
python
{ "resource": "" }
q588
MockRedis.psetex
train
def psetex(self, key, time, value): """ Set the value of ``key`` to ``value`` that expires in ``time`` milliseconds. ``time`` can be represented by an integer or a Python timedelta object. """ return self.set(key, value, px=time)
python
{ "resource": "" }
q589
MockRedis.setnx
train
def setnx(self, key, value): """Set the value of ``key`` to ``value`` if key doesn't exist""" return self.set(key, value, nx=True)
python
{ "resource": "" }
q590
MockRedis.setbit
train
def setbit(self, key, offset, value): """ Set the bit at ``offset`` in ``key`` to ``value``. """ key = self._encode(key) index, bits, mask = self._get_bits_and_offset(key, offset) if index >= len(bits): bits.extend(b"\x00" * (index + 1 - len(bits))) ...
python
{ "resource": "" }
q591
MockRedis.getbit
train
def getbit(self, key, offset): """ Returns the bit value at ``offset`` in ``key``. """ key = self._encode(key) index, bits, mask = self._get_bits_and_offset(key, offset) if index >= len(bits): return 0 return 1 if (bits[index] & mask) else 0
python
{ "resource": "" }
q592
MockRedis.hexists
train
def hexists(self, hashkey, attribute): """Emulate hexists.""" redis_hash = self._get_hash(hashkey, 'HEXISTS') return self._encode(attribute) in redis_hash
python
{ "resource": "" }
q593
MockRedis.hget
train
def hget(self, hashkey, attribute): """Emulate hget.""" redis_hash = self._get_hash(hashkey, 'HGET') return redis_hash.get(self._encode(attribute))
python
{ "resource": "" }
q594
MockRedis.hmset
train
def hmset(self, hashkey, value): """Emulate hmset.""" redis_hash = self._get_hash(hashkey, 'HMSET', create=True) for key, value in value.items(): attribute = self._encode(key) redis_hash[attribute] = self._encode(value) return True
python
{ "resource": "" }
q595
MockRedis.hmget
train
def hmget(self, hashkey, keys, *args): """Emulate hmget.""" redis_hash = self._get_hash(hashkey, 'HMGET') attributes = self._list_or_args(keys, args) return [redis_hash.get(self._encode(attribute)) for attribute in attributes]
python
{ "resource": "" }
q596
MockRedis.hset
train
def hset(self, hashkey, attribute, value): """Emulate hset.""" redis_hash = self._get_hash(hashkey, 'HSET', create=True) attribute = self._encode(attribute) attribute_present = attribute in redis_hash redis_hash[attribute] = self._encode(value) return long(0) if attribut...
python
{ "resource": "" }
q597
MockRedis.hsetnx
train
def hsetnx(self, hashkey, attribute, value): """Emulate hsetnx.""" redis_hash = self._get_hash(hashkey, 'HSETNX', create=True) attribute = self._encode(attribute) if attribute in redis_hash: return long(0) else: redis_hash[attribute] = self._encode(value)...
python
{ "resource": "" }
q598
MockRedis.hincrby
train
def hincrby(self, hashkey, attribute, increment=1): """Emulate hincrby.""" return self._hincrby(hashkey, attribute, 'HINCRBY', long, increment)
python
{ "resource": "" }
q599
MockRedis.hincrbyfloat
train
def hincrbyfloat(self, hashkey, attribute, increment=1.0): """Emulate hincrbyfloat.""" return self._hincrby(hashkey, attribute, 'HINCRBYFLOAT', float, increment)
python
{ "resource": "" }