Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
list
start_point
list
end_point
list
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
test_dashboard_assert_classification_pos_label
(dashboard, data_classification_balanced, input_label)
Testing if assessing provided classification_pos_label returns the provided label if its in y values.
Testing if assessing provided classification_pos_label returns the provided label if its in y values.
def test_dashboard_assert_classification_pos_label(dashboard, data_classification_balanced, input_label): """Testing if assessing provided classification_pos_label returns the provided label if its in y values.""" y = data_classification_balanced[1] dashboard.y = y pos_label = 1 # placeholder value to ...
[ "def", "test_dashboard_assert_classification_pos_label", "(", "dashboard", ",", "data_classification_balanced", ",", "input_label", ")", ":", "y", "=", "data_classification_balanced", "[", "1", "]", "dashboard", ".", "y", "=", "y", "pos_label", "=", "1", "# placeholde...
[ 16, 0 ]
[ 22, 35 ]
python
en
['en', 'en', 'en']
True
test_dashboard_assert_classification_pos_label_error
(dashboard, data_classification_balanced, error_label)
Testing if dashboard raises an error when classification_pos_label is explicitly provided but it doesn't exist in y.
Testing if dashboard raises an error when classification_pos_label is explicitly provided but it doesn't exist in y.
def test_dashboard_assert_classification_pos_label_error(dashboard, data_classification_balanced, error_label): """Testing if dashboard raises an error when classification_pos_label is explicitly provided but it doesn't exist in y.""" y = data_classification_balanced[1] dashboard.y = y with pytest.r...
[ "def", "test_dashboard_assert_classification_pos_label_error", "(", "dashboard", ",", "data_classification_balanced", ",", "error_label", ")", ":", "y", "=", "data_classification_balanced", "[", "1", "]", "dashboard", ".", "y", "=", "y", "with", "pytest", ".", "raises...
[ 33, 0 ]
[ 41, 49 ]
python
en
['en', 'en', 'en']
True
test_dashboard_assert_classification_pos_label_warning
( dashboard, data_multiclass, root_path_to_package, warning_label )
Testing if warning is raised when classification_pos_label is explicitly provided for multiclass y.
Testing if warning is raised when classification_pos_label is explicitly provided for multiclass y.
def test_dashboard_assert_classification_pos_label_warning( dashboard, data_multiclass, root_path_to_package, warning_label ): """Testing if warning is raised when classification_pos_label is explicitly provided for multiclass y.""" y = data_multiclass[1] dashboard.y = y dashboard._force_classif...
[ "def", "test_dashboard_assert_classification_pos_label_warning", "(", "dashboard", ",", "data_multiclass", ",", "root_path_to_package", ",", "warning_label", ")", ":", "y", "=", "data_multiclass", "[", "1", "]", "dashboard", ".", "y", "=", "y", "dashboard", ".", "_f...
[ 52, 0 ]
[ 63, 28 ]
python
en
['en', 'en', 'en']
True
test_dashboard_assert_classification_pos_label_forced
( dashboard, data_multiclass, root_path_to_package, input_label )
Testing if classification_pos_label is set correctly for multiclass y when flag for forcing it is set to True.
Testing if classification_pos_label is set correctly for multiclass y when flag for forcing it is set to True.
def test_dashboard_assert_classification_pos_label_forced( dashboard, data_multiclass, root_path_to_package, input_label ): """Testing if classification_pos_label is set correctly for multiclass y when flag for forcing it is set to True.""" y = data_multiclass[1] dashboard.y = y dashboard._force...
[ "def", "test_dashboard_assert_classification_pos_label_forced", "(", "dashboard", ",", "data_multiclass", ",", "root_path_to_package", ",", "input_label", ")", ":", "y", "=", "data_multiclass", "[", "1", "]", "dashboard", ".", "y", "=", "y", "dashboard", ".", "_forc...
[ 74, 0 ]
[ 83, 35 ]
python
en
['en', 'en', 'en']
True
test_dashboard_assess_n_features
(dashboard, input_df, limit, expected_flag)
Testing if assessing dataframes for the number of features correctly sets the flag (based on the limit).
Testing if assessing dataframes for the number of features correctly sets the flag (based on the limit).
def test_dashboard_assess_n_features(dashboard, input_df, limit, expected_flag): """Testing if assessing dataframes for the number of features correctly sets the flag (based on the limit).""" dashboard._n_features_pairplots_limit = limit dashboard._assess_n_features(input_df) assert dashboard._create_p...
[ "def", "test_dashboard_assess_n_features", "(", "dashboard", ",", "input_df", ",", "limit", ",", "expected_flag", ")", ":", "dashboard", ".", "_n_features_pairplots_limit", "=", "limit", "dashboard", ".", "_assess_n_features", "(", "input_df", ")", "assert", "dashboar...
[ 95, 0 ]
[ 100, 60 ]
python
en
['en', 'en', 'en']
True
test_dashboard_create_test_splits
(dashboard, data_classification_balanced, seed)
Testing if the train/test split in dashboard is done correctly.
Testing if the train/test split in dashboard is done correctly.
def test_dashboard_create_test_splits(dashboard, data_classification_balanced, seed): """Testing if the train/test split in dashboard is done correctly.""" X, y = data_classification_balanced X = X.drop(["Date"], axis=1) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=seed) X...
[ "def", "test_dashboard_create_test_splits", "(", "dashboard", ",", "data_classification_balanced", ",", "seed", ")", ":", "X", ",", "y", "=", "data_classification_balanced", "X", "=", "X", ".", "drop", "(", "[", "\"Date\"", "]", ",", "axis", "=", "1", ")", "...
[ 103, 0 ]
[ 118, 42 ]
python
en
['en', 'en', 'en']
True
test_dashboard_fit_transform_test_splits
(dashboard, data_classification_balanced, seed)
Testing if fit_transform_test_splits does fitting on train data and the transforms splits appropriately.
Testing if fit_transform_test_splits does fitting on train data and the transforms splits appropriately.
def test_dashboard_fit_transform_test_splits(dashboard, data_classification_balanced, seed): """Testing if fit_transform_test_splits does fitting on train data and the transforms splits appropriately.""" d = dashboard d._create_test_splits() transformer_X = clone(d.transformer_eval.preprocessor_X) t...
[ "def", "test_dashboard_fit_transform_test_splits", "(", "dashboard", ",", "data_classification_balanced", ",", "seed", ")", ":", "d", "=", "dashboard", "d", ".", "_create_test_splits", "(", ")", "transformer_X", "=", "clone", "(", "d", ".", "transformer_eval", ".", ...
[ 121, 0 ]
[ 141, 64 ]
python
en
['en', 'en', 'en']
True
test_dashboard_set_custom_transformer
(dashboard, data_classification_balanced)
Testing if setting custom transformers update both instances of regular and train/test splits Transformers.
Testing if setting custom transformers update both instances of regular and train/test splits Transformers.
def test_dashboard_set_custom_transformer(dashboard, data_classification_balanced): """Testing if setting custom transformers update both instances of regular and train/test splits Transformers.""" numerical_tr = [SimpleImputer(strategy="mean"), PowerTransformer()] categorical_tr = [SimpleImputer(strategy="...
[ "def", "test_dashboard_set_custom_transformer", "(", "dashboard", ",", "data_classification_balanced", ")", ":", "numerical_tr", "=", "[", "SimpleImputer", "(", "strategy", "=", "\"mean\"", ")", ",", "PowerTransformer", "(", ")", "]", "categorical_tr", "=", "[", "Si...
[ 144, 0 ]
[ 155, 48 ]
python
en
['en', 'en', 'en']
True
test_dashboard_train_test_split_match_original_transformed_X
(dashboard, data_classification_balanced)
Testing if indexes of original train/test data match those of transformed train/test data (X).
Testing if indexes of original train/test data match those of transformed train/test data (X).
def test_dashboard_train_test_split_match_original_transformed_X(dashboard, data_classification_balanced): """Testing if indexes of original train/test data match those of transformed train/test data (X).""" d = dashboard d._do_transformations() tr = d.transformer_eval X_train, X_test = d.X_train, d...
[ "def", "test_dashboard_train_test_split_match_original_transformed_X", "(", "dashboard", ",", "data_classification_balanced", ")", ":", "d", "=", "dashboard", "d", ".", "_do_transformations", "(", ")", "tr", "=", "d", ".", "transformer_eval", "X_train", ",", "X_test", ...
[ 158, 0 ]
[ 179, 47 ]
python
en
['en', 'en', 'en']
True
test_dashboard_train_test_split_match_original_transformed_y
(dashboard, data_classification_balanced)
Testing if indexes of original train/test data match those of transformed train/test data (y).
Testing if indexes of original train/test data match those of transformed train/test data (y).
def test_dashboard_train_test_split_match_original_transformed_y(dashboard, data_classification_balanced): """Testing if indexes of original train/test data match those of transformed train/test data (y).""" d = dashboard d._do_transformations() tr = d.transformer_eval y_train, y_test = d.y_train, d...
[ "def", "test_dashboard_train_test_split_match_original_transformed_y", "(", "dashboard", ",", "data_classification_balanced", ")", ":", "d", "=", "dashboard", "d", ".", "_do_transformations", "(", ")", "tr", "=", "d", ".", "transformer_eval", "y_train", ",", "y_test", ...
[ 182, 0 ]
[ 200, 36 ]
python
en
['en', 'en', 'en']
True
test_dashboard_check_transformed_cols
(dashboard, transformed_cols)
Testing if checking provided transformed_columns by dashboard works properly.
Testing if checking provided transformed_columns by dashboard works properly.
def test_dashboard_check_transformed_cols(dashboard, transformed_cols): """Testing if checking provided transformed_columns by dashboard works properly.""" actual_result = dashboard._check_transformed_cols(transformed_cols) assert actual_result == sorted(transformed_cols)
[ "def", "test_dashboard_check_transformed_cols", "(", "dashboard", ",", "transformed_cols", ")", ":", "actual_result", "=", "dashboard", ".", "_check_transformed_cols", "(", "transformed_cols", ")", "assert", "actual_result", "==", "sorted", "(", "transformed_cols", ")" ]
[ 213, 0 ]
[ 216, 52 ]
python
en
['en', 'en', 'en']
True
test_dashboard_check_transformed_cols_error
(dashboard, incorrect_transformed_columns)
Testing if providing incorrect transformed columns (that aren't in the provided X data) raises an error.
Testing if providing incorrect transformed columns (that aren't in the provided X data) raises an error.
def test_dashboard_check_transformed_cols_error(dashboard, incorrect_transformed_columns): """Testing if providing incorrect transformed columns (that aren't in the provided X data) raises an error.""" with pytest.raises(ValueError) as excinfo: res = dashboard._check_transformed_cols(incorrect_transform...
[ "def", "test_dashboard_check_transformed_cols_error", "(", "dashboard", ",", "incorrect_transformed_columns", ")", ":", "with", "pytest", ".", "raises", "(", "ValueError", ")", "as", "excinfo", ":", "res", "=", "dashboard", ".", "_check_transformed_cols", "(", "incorr...
[ 227, 0 ]
[ 231, 72 ]
python
en
['en', 'en', 'en']
True
MelodyOneHotEncoding.__init__
(self, min_note, max_note)
Initializes a MelodyOneHotEncoding object. Args: min_note: The minimum midi pitch the encoded melody events can have. max_note: The maximum midi pitch (exclusive) the encoded melody events can have. Raises: ValueError: If `min_note` or `max_note` are outside the midi range, or if ...
Initializes a MelodyOneHotEncoding object.
def __init__(self, min_note, max_note): """Initializes a MelodyOneHotEncoding object. Args: min_note: The minimum midi pitch the encoded melody events can have. max_note: The maximum midi pitch (exclusive) the encoded melody events can have. Raises: ValueError: If `min_note` or...
[ "def", "__init__", "(", "self", ",", "min_note", ",", "max_note", ")", ":", "if", "min_note", "<", "MIN_MIDI_PITCH", ":", "raise", "ValueError", "(", "'min_note must be >= 0. min_note is %d.'", "%", "min_note", ")", "if", "max_note", ">", "MAX_MIDI_PITCH", "+", ...
[ 52, 2 ]
[ 72, 29 ]
python
en
['en', 'ny', 'en']
True
MelodyOneHotEncoding.encode_event
(self, event)
Collapses a melody event value into a zero-based index range. Args: event: A Melody event value. -2 = no event, -1 = note-off event, [0, 127] = note-on event for that midi pitch. Returns: An int in the range [0, self.num_classes). 0 = no event, 1 = note-off event, [2, self.num_clas...
Collapses a melody event value into a zero-based index range.
def encode_event(self, event): """Collapses a melody event value into a zero-based index range. Args: event: A Melody event value. -2 = no event, -1 = note-off event, [0, 127] = note-on event for that midi pitch. Returns: An int in the range [0, self.num_classes). 0 = no event, ...
[ "def", "encode_event", "(", "self", ",", "event", ")", ":", "if", "event", "<", "-", "NUM_SPECIAL_MELODY_EVENTS", ":", "raise", "ValueError", "(", "'invalid melody event value: %d'", "%", "event", ")", "if", "0", "<=", "event", "<", "self", ".", "_min_note", ...
[ 82, 2 ]
[ 109, 61 ]
python
en
['en', 'en', 'en']
True
MelodyOneHotEncoding.decode_event
(self, index)
Expands a zero-based index value to its equivalent melody event value. Args: index: An int in the range [0, self._num_model_events). 0 = no event, 1 = note-off event, [2, self._num_model_events) = note-on event for that pitch relative to the [self._min_note, self._max_note) rang...
Expands a zero-based index value to its equivalent melody event value.
def decode_event(self, index): """Expands a zero-based index value to its equivalent melody event value. Args: index: An int in the range [0, self._num_model_events). 0 = no event, 1 = note-off event, [2, self._num_model_events) = note-on event for that pitch relative to the...
[ "def", "decode_event", "(", "self", ",", "index", ")", ":", "if", "index", "<", "NUM_SPECIAL_MELODY_EVENTS", ":", "return", "index", "-", "NUM_SPECIAL_MELODY_EVENTS", "return", "index", "-", "NUM_SPECIAL_MELODY_EVENTS", "+", "self", ".", "_min_note" ]
[ 111, 2 ]
[ 126, 61 ]
python
en
['en', 'en', 'en']
True
KeyMelodyEncoderDecoder.__init__
(self, min_note, max_note, lookback_distances=None, binary_counter_bits=7)
Initializes the KeyMelodyEncoderDecoder. Args: min_note: The minimum midi pitch the encoded melody events can have. max_note: The maximum midi pitch (exclusive) the encoded melody events can have. lookback_distances: A list of step intervals to look back in history to encode b...
Initializes the KeyMelodyEncoderDecoder.
def __init__(self, min_note, max_note, lookback_distances=None, binary_counter_bits=7): """Initializes the KeyMelodyEncoderDecoder. Args: min_note: The minimum midi pitch the encoded melody events can have. max_note: The maximum midi pitch (exclusive) the encoded melody events can ...
[ "def", "__init__", "(", "self", ",", "min_note", ",", "max_note", ",", "lookback_distances", "=", "None", ",", "binary_counter_bits", "=", "7", ")", ":", "if", "lookback_distances", "is", "None", ":", "self", ".", "_lookback_distances", "=", "DEFAULT_LOOKBACK_DI...
[ 132, 2 ]
[ 152, 42 ]
python
en
['en', 'ru-Latn', 'en']
True
KeyMelodyEncoderDecoder.events_to_input
(self, events, position)
Returns the input vector for the given position in the melody. Returns a self.input_size length list of floats. Assuming self._min_note = 48, self._note_range = 36, two lookback distances, and seven binary counters, then self.input_size = 74. Each index represents a different input signal to the model....
Returns the input vector for the given position in the melody.
def events_to_input(self, events, position): """Returns the input vector for the given position in the melody. Returns a self.input_size length list of floats. Assuming self._min_note = 48, self._note_range = 36, two lookback distances, and seven binary counters, then self.input_size = 74. Each index r...
[ "def", "events_to_input", "(", "self", ",", "events", ",", "position", ")", ":", "current_note", "=", "None", "is_attack", "=", "False", "is_ascending", "=", "None", "last_3_notes", "=", "collections", ".", "deque", "(", "maxlen", "=", "3", ")", "sub_melody"...
[ 175, 2 ]
[ 283, 17 ]
python
en
['en', 'en', 'en']
True
KeyMelodyEncoderDecoder.events_to_label
(self, events, position)
Returns the label for the given position in the melody. Returns an int in the range [0, self.num_classes). Assuming self._min_note = 48, self._note_range = 36, and two lookback distances, then self.num_classes = 40. Values [0, 39]: [0, 35]: Note-on event for midi pitch [48, 84). 36: No event. ...
Returns the label for the given position in the melody.
def events_to_label(self, events, position): """Returns the label for the given position in the melody. Returns an int in the range [0, self.num_classes). Assuming self._min_note = 48, self._note_range = 36, and two lookback distances, then self.num_classes = 40. Values [0, 39]: [0, 35]: Note-o...
[ "def", "events_to_label", "(", "self", ",", "events", ",", "position", ")", ":", "if", "(", "position", "<", "self", ".", "_lookback_distances", "[", "-", "1", "]", "and", "events", "[", "position", "]", "==", "MELODY_NO_EVENT", ")", ":", "return", "self...
[ 285, 2 ]
[ 325, 44 ]
python
en
['en', 'en', 'en']
True
KeyMelodyEncoderDecoder.class_index_to_event
(self, class_index, events)
Returns the melody event for the given class index. This is the reverse process of the self.events_to_label method. Args: class_index: An int in the range [0, self.num_classes). events: The note_seq.Melody events list of the current melody. Returns: A note_seq.Melody event value.
Returns the melody event for the given class index.
def class_index_to_event(self, class_index, events): """Returns the melody event for the given class index. This is the reverse process of the self.events_to_label method. Args: class_index: An int in the range [0, self.num_classes). events: The note_seq.Melody events list of the current melod...
[ "def", "class_index_to_event", "(", "self", ",", "class_index", ",", "events", ")", ":", "# Repeat N bars ago.", "for", "i", ",", "lookback_distance", "in", "reversed", "(", "list", "(", "enumerate", "(", "self", ".", "_lookback_distances", ")", ")", ")", ":",...
[ 327, 2 ]
[ 355, 39 ]
python
en
['en', 'en', 'en']
True
build_py.get_data_files
(self)
Generate list of '(package,src_dir,build_dir,filenames)' tuples
Generate list of '(package,src_dir,build_dir,filenames)' tuples
def get_data_files(self): """Generate list of '(package,src_dir,build_dir,filenames)' tuples""" data = [] if not self.packages: return data for package in self.packages: # Locate package source directory src_dir = self.get_package_dir(package) ...
[ "def", "get_data_files", "(", "self", ")", ":", "data", "=", "[", "]", "if", "not", "self", ".", "packages", ":", "return", "data", "for", "package", "in", "self", ".", "packages", ":", "# Locate package source directory", "src_dir", "=", "self", ".", "get...
[ 96, 4 ]
[ 118, 19 ]
python
en
['en', 'af', 'en']
True
build_py.find_data_files
(self, package, src_dir)
Return filenames for package's data files in 'src_dir
Return filenames for package's data files in 'src_dir
def find_data_files(self, package, src_dir): """Return filenames for package's data files in 'src_dir'""" globs = (self.package_data.get('', []) + self.package_data.get(package, [])) files = [] for pattern in globs: # Each pattern has to be converted to a pla...
[ "def", "find_data_files", "(", "self", ",", "package", ",", "src_dir", ")", ":", "globs", "=", "(", "self", ".", "package_data", ".", "get", "(", "''", ",", "[", "]", ")", "+", "self", ".", "package_data", ".", "get", "(", "package", ",", "[", "]",...
[ 120, 4 ]
[ 131, 20 ]
python
en
['en', 'no', 'en']
True
build_py.build_package_data
(self)
Copy data files into build directory
Copy data files into build directory
def build_package_data(self): """Copy data files into build directory""" lastdir = None for package, src_dir, build_dir, filenames in self.data_files: for filename in filenames: target = os.path.join(build_dir, filename) self.mkpath(os.path.dirname(tar...
[ "def", "build_package_data", "(", "self", ")", ":", "lastdir", "=", "None", "for", "package", ",", "src_dir", ",", "build_dir", ",", "filenames", "in", "self", ".", "data_files", ":", "for", "filename", "in", "filenames", ":", "target", "=", "os", ".", "...
[ 133, 4 ]
[ 141, 51 ]
python
en
['en', 'en', 'en']
True
build_py.get_package_dir
(self, package)
Return the directory, relative to the top of the source distribution, where package 'package' should be found (at least according to the 'package_dir' option, if any).
Return the directory, relative to the top of the source distribution, where package 'package' should be found (at least according to the 'package_dir' option, if any).
def get_package_dir(self, package): """Return the directory, relative to the top of the source distribution, where package 'package' should be found (at least according to the 'package_dir' option, if any).""" path = package.split('.') if not self.package_dir: ...
[ "def", "get_package_dir", "(", "self", ",", "package", ")", ":", "path", "=", "package", ".", "split", "(", "'.'", ")", "if", "not", "self", ".", "package_dir", ":", "if", "path", ":", "return", "os", ".", "path", ".", "join", "(", "*", "path", ")"...
[ 143, 4 ]
[ 180, 29 ]
python
en
['en', 'en', 'en']
True
build_py.find_modules
(self)
Finds individually-specified Python modules, ie. those listed by module name in 'self.py_modules'. Returns a list of tuples (package, module_base, filename): 'package' is a tuple of the path through package-space to the module; 'module_base' is the bare (no packages, no dots) module nam...
Finds individually-specified Python modules, ie. those listed by module name in 'self.py_modules'. Returns a list of tuples (package, module_base, filename): 'package' is a tuple of the path through package-space to the module; 'module_base' is the bare (no packages, no dots) module nam...
def find_modules(self): """Finds individually-specified Python modules, ie. those listed by module name in 'self.py_modules'. Returns a list of tuples (package, module_base, filename): 'package' is a tuple of the path through package-space to the module; 'module_base' is the bare (no ...
[ "def", "find_modules", "(", "self", ")", ":", "# Map package names to tuples of useful info about the package:", "# (package_dir, checked)", "# package_dir - the directory where we'll find source files for", "# this package", "# checked - true if we have checked that the package directory",...
[ 231, 4 ]
[ 281, 22 ]
python
en
['en', 'en', 'en']
True
build_py.find_all_modules
(self)
Compute the list of all modules that will be built, whether they are specified one-module-at-a-time ('self.py_modules') or by whole packages ('self.packages'). Return a list of tuples (package, module, module_file), just like 'find_modules()' and 'find_package_modules()' do.
Compute the list of all modules that will be built, whether they are specified one-module-at-a-time ('self.py_modules') or by whole packages ('self.packages'). Return a list of tuples (package, module, module_file), just like 'find_modules()' and 'find_package_modules()' do.
def find_all_modules(self): """Compute the list of all modules that will be built, whether they are specified one-module-at-a-time ('self.py_modules') or by whole packages ('self.packages'). Return a list of tuples (package, module, module_file), just like 'find_modules()' and '...
[ "def", "find_all_modules", "(", "self", ")", ":", "modules", "=", "[", "]", "if", "self", ".", "py_modules", ":", "modules", ".", "extend", "(", "self", ".", "find_modules", "(", ")", ")", "if", "self", ".", "packages", ":", "for", "package", "in", "...
[ 283, 4 ]
[ 297, 22 ]
python
en
['en', 'en', 'en']
True
del_none
(dictionary)
Recursively delete from the dictionary all entries which values are None. This function changes the input parameter in place. :param dictionary: input dictionary :type dictionary: dict :return: output dictionary :rtype: dict
Recursively delete from the dictionary all entries which values are None. This function changes the input parameter in place.
def del_none(dictionary): """ Recursively delete from the dictionary all entries which values are None. This function changes the input parameter in place. :param dictionary: input dictionary :type dictionary: dict :return: output dictionary :rtype: dict """ for key, value in list(...
[ "def", "del_none", "(", "dictionary", ")", ":", "for", "key", ",", "value", "in", "list", "(", "dictionary", ".", "items", "(", ")", ")", ":", "if", "value", "is", "None", ":", "del", "dictionary", "[", "key", "]", "elif", "isinstance", "(", "value",...
[ 9, 0 ]
[ 25, 21 ]
python
en
['en', 'error', 'th']
False
json_utf8
(func)
A decorator to turn a function's return value into JSON
A decorator to turn a function's return value into JSON
def json_utf8(func): """ A decorator to turn a function's return value into JSON """ def wrapper(*args, **kwargs): """ wrapper """ return json.dumps(func(*args, **kwargs)) return wrapper
[ "def", "json_utf8", "(", "func", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\" wrapper \"\"\"", "return", "json", ".", "dumps", "(", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", "return", "...
[ 28, 0 ]
[ 35, 18 ]
python
en
['en', 'en', 'en']
True
read_in_chunks
(stream, chunk_size)
Utility method for reading in and yielding chunks :param stream: file-like object to read audio from :type stream: io.IOBase :param chunk_size: maximum chunk size in bytes :type chunk_size: int :raises ValueError: if no data was read from the stream :return: a sequence of chunks of data...
Utility method for reading in and yielding chunks
async def read_in_chunks(stream, chunk_size): """ Utility method for reading in and yielding chunks :param stream: file-like object to read audio from :type stream: io.IOBase :param chunk_size: maximum chunk size in bytes :type chunk_size: int :raises ValueError: if no data was read from ...
[ "async", "def", "read_in_chunks", "(", "stream", ",", "chunk_size", ")", ":", "count", "=", "0", "while", "True", ":", "# Work with both async and synchronous file readers.", "if", "inspect", ".", "iscoroutinefunction", "(", "stream", ".", "read", ")", ":", "audio...
[ 38, 0 ]
[ 66, 18 ]
python
en
['en', 'error', 'th']
False
TestChoosePubDate.test_choose_date_sent_large_tot_messages
(self)
Test for a bug that was present, where specifying a large amount of messages to generate would cause each message to have date_sent set to timezone_now(), instead of the date_sents being distributed across the span of several days.
Test for a bug that was present, where specifying a large amount of messages to generate would cause each message to have date_sent set to timezone_now(), instead of the date_sents being distributed across the span of several days.
def test_choose_date_sent_large_tot_messages(self) -> None: """ Test for a bug that was present, where specifying a large amount of messages to generate would cause each message to have date_sent set to timezone_now(), instead of the date_sents being distributed across the span of severa...
[ "def", "test_choose_date_sent_large_tot_messages", "(", "self", ")", "->", "None", ":", "tot_messages", "=", "1000000", "datetimes_list", "=", "[", "choose_date_sent", "(", "i", ",", "tot_messages", ",", "1", ")", "for", "i", "in", "range", "(", "1", ",", "t...
[ 7, 4 ]
[ 23, 13 ]
python
en
['en', 'error', 'th']
False
interpret
(marker, execution_context=None)
Interpret a marker and return a result depending on environment. :param marker: The marker to interpret. :type marker: str :param execution_context: The context used for name lookup. :type execution_context: mapping
Interpret a marker and return a result depending on environment.
def interpret(marker, execution_context=None): """ Interpret a marker and return a result depending on environment. :param marker: The marker to interpret. :type marker: str :param execution_context: The context used for name lookup. :type execution_context: mapping """ try: exp...
[ "def", "interpret", "(", "marker", ",", "execution_context", "=", "None", ")", ":", "try", ":", "expr", ",", "rest", "=", "parse_marker", "(", "marker", ")", "except", "Exception", "as", "e", ":", "raise", "SyntaxError", "(", "'Unable to interpret marker synta...
[ 112, 0 ]
[ 130, 44 ]
python
en
['en', 'error', 'th']
False
Evaluator.evaluate
(self, expr, context)
Evaluate a marker expression returned by the :func:`parse_requirement` function in the specified context.
Evaluate a marker expression returned by the :func:`parse_requirement` function in the specified context.
def evaluate(self, expr, context): """ Evaluate a marker expression returned by the :func:`parse_requirement` function in the specified context. """ if isinstance(expr, string_types): if expr[0] in '\'"': result = expr[1:-1] else: ...
[ "def", "evaluate", "(", "self", ",", "expr", ",", "context", ")", ":", "if", "isinstance", "(", "expr", ",", "string_types", ")", ":", "if", "expr", "[", "0", "]", "in", "'\\'\"'", ":", "result", "=", "expr", "[", "1", ":", "-", "1", "]", "else",...
[ 49, 4 ]
[ 74, 21 ]
python
en
['en', 'error', 'th']
False
int16_samples_to_float32
(y)
Convert int16 numpy array of audio samples to float32.
Convert int16 numpy array of audio samples to float32.
def int16_samples_to_float32(y): """Convert int16 numpy array of audio samples to float32.""" if y.dtype != np.int16: raise ValueError('input samples not int16') return y.astype(np.float32) / np.iinfo(np.int16).max
[ "def", "int16_samples_to_float32", "(", "y", ")", ":", "if", "y", ".", "dtype", "!=", "np", ".", "int16", ":", "raise", "ValueError", "(", "'input samples not int16'", ")", "return", "y", ".", "astype", "(", "np", ".", "float32", ")", "/", "np", ".", "...
[ 38, 0 ]
[ 42, 54 ]
python
en
['en', 'en', 'en']
True
float_samples_to_int16
(y)
Convert floating-point numpy array of audio samples to int16.
Convert floating-point numpy array of audio samples to int16.
def float_samples_to_int16(y): """Convert floating-point numpy array of audio samples to int16.""" if not issubclass(y.dtype.type, np.floating): raise ValueError('input samples not floating-point') return (y * np.iinfo(np.int16).max).astype(np.int16)
[ "def", "float_samples_to_int16", "(", "y", ")", ":", "if", "not", "issubclass", "(", "y", ".", "dtype", ".", "type", ",", "np", ".", "floating", ")", ":", "raise", "ValueError", "(", "'input samples not floating-point'", ")", "return", "(", "y", "*", "np",...
[ 45, 0 ]
[ 49, 54 ]
python
en
['en', 'en', 'en']
True
wav_data_to_samples_pydub
(wav_data: bytes, sample_rate: int, remove_dc_bias: bool = False, num_channels: int = None, normalize_db: float = None)
Convert audio file data (in bytes) into a numpy array using Pydub. Args: wav_data: A byte stream of audio data. sample_rate: Resample recorded audio to this sample rate. remove_dc_bias: If true, will remove DC bias from audio. num_channels: If not specified, output shape will be based on the contents...
Convert audio file data (in bytes) into a numpy array using Pydub.
def wav_data_to_samples_pydub(wav_data: bytes, sample_rate: int, remove_dc_bias: bool = False, num_channels: int = None, normalize_db: float = None): """Convert audio file data (in bytes) into a num...
[ "def", "wav_data_to_samples_pydub", "(", "wav_data", ":", "bytes", ",", "sample_rate", ":", "int", ",", "remove_dc_bias", ":", "bool", "=", "False", ",", "num_channels", ":", "int", "=", "None", ",", "normalize_db", ":", "float", "=", "None", ")", ":", "# ...
[ 52, 0 ]
[ 92, 15 ]
python
en
['it', 'en', 'en']
True
wav_data_to_samples
(wav_data, sample_rate)
Read PCM-formatted WAV data and return a NumPy array of samples. Uses scipy to read and librosa to process WAV data. Audio will be converted to mono if necessary. Args: wav_data: WAV audio data to read. sample_rate: The number of samples per second at which the audio will be returned. Resampling...
Read PCM-formatted WAV data and return a NumPy array of samples.
def wav_data_to_samples(wav_data, sample_rate): """Read PCM-formatted WAV data and return a NumPy array of samples. Uses scipy to read and librosa to process WAV data. Audio will be converted to mono if necessary. Args: wav_data: WAV audio data to read. sample_rate: The number of samples per second at...
[ "def", "wav_data_to_samples", "(", "wav_data", ",", "sample_rate", ")", ":", "try", ":", "# Read the wav file, converting sample rate & number of channels.", "native_sr", ",", "y", "=", "scipy", ".", "io", ".", "wavfile", ".", "read", "(", "io", ".", "BytesIO", "(...
[ 95, 0 ]
[ 138, 10 ]
python
en
['en', 'en', 'en']
True
wav_data_to_samples_librosa
(audio_file, sample_rate)
Loads an in-memory audio file with librosa. Use this instead of wav_data_to_samples if the wav is 24-bit, as that's incompatible with wav_data_to_samples internal scipy call. Will copy to a local temp file before loading so that librosa can read a file path. Librosa does not currently read in-memory files. ...
Loads an in-memory audio file with librosa.
def wav_data_to_samples_librosa(audio_file, sample_rate): """Loads an in-memory audio file with librosa. Use this instead of wav_data_to_samples if the wav is 24-bit, as that's incompatible with wav_data_to_samples internal scipy call. Will copy to a local temp file before loading so that librosa can read a f...
[ "def", "wav_data_to_samples_librosa", "(", "audio_file", ",", "sample_rate", ")", ":", "with", "tempfile", ".", "NamedTemporaryFile", "(", "suffix", "=", "'.wav'", ")", "as", "wav_input_file", ":", "wav_input_file", ".", "write", "(", "audio_file", ")", "# Before ...
[ 141, 0 ]
[ 170, 55 ]
python
en
['en', 'en', 'en']
True
samples_to_wav_data
(samples, sample_rate)
Converts floating point samples to wav data.
Converts floating point samples to wav data.
def samples_to_wav_data(samples, sample_rate): """Converts floating point samples to wav data.""" wav_io = io.BytesIO() scipy.io.wavfile.write(wav_io, sample_rate, float_samples_to_int16(samples)) return wav_io.getvalue()
[ "def", "samples_to_wav_data", "(", "samples", ",", "sample_rate", ")", ":", "wav_io", "=", "io", ".", "BytesIO", "(", ")", "scipy", ".", "io", ".", "wavfile", ".", "write", "(", "wav_io", ",", "sample_rate", ",", "float_samples_to_int16", "(", "samples", "...
[ 173, 0 ]
[ 177, 26 ]
python
en
['en', 'en', 'en']
True
crop_samples
(samples, sample_rate, crop_beginning_seconds, total_length_seconds)
Crop WAV data. Args: samples: Numpy Array containing samples. sample_rate: The sample rate at which to interpret the samples. crop_beginning_seconds: How many seconds to crop from the beginning of the audio. total_length_seconds: The desired duration of the audio. After cropping the b...
Crop WAV data.
def crop_samples(samples, sample_rate, crop_beginning_seconds, total_length_seconds): """Crop WAV data. Args: samples: Numpy Array containing samples. sample_rate: The sample rate at which to interpret the samples. crop_beginning_seconds: How many seconds to crop from the beginning of ...
[ "def", "crop_samples", "(", "samples", ",", "sample_rate", ",", "crop_beginning_seconds", ",", "total_length_seconds", ")", ":", "samples_to_crop", "=", "int", "(", "crop_beginning_seconds", "*", "sample_rate", ")", "total_samples", "=", "int", "(", "total_length_seco...
[ 180, 0 ]
[ 199, 24 ]
python
de
['en', 'de', 'sw']
False
repeat_samples_to_duration
(samples, sample_rate, duration)
Repeat a sequence of samples until it is a given duration, trimming extra. Args: samples: The sequence to repeat sample_rate: The sample rate at which to interpret the samples. duration: The desired duration Returns: The repeated and possibly trimmed sequence.
Repeat a sequence of samples until it is a given duration, trimming extra.
def repeat_samples_to_duration(samples, sample_rate, duration): """Repeat a sequence of samples until it is a given duration, trimming extra. Args: samples: The sequence to repeat sample_rate: The sample rate at which to interpret the samples. duration: The desired duration Returns: The repeated...
[ "def", "repeat_samples_to_duration", "(", "samples", ",", "sample_rate", ",", "duration", ")", ":", "sequence_duration", "=", "len", "(", "samples", ")", "/", "sample_rate", "num_repeats", "=", "int", "(", "math", ".", "ceil", "(", "duration", "/", "sequence_d...
[ 202, 0 ]
[ 219, 16 ]
python
en
['en', 'en', 'en']
True
crop_wav_data
(wav_data, sample_rate, crop_beginning_seconds, total_length_seconds)
Crop WAV data. Args: wav_data: WAV audio data to crop. sample_rate: The sample rate at which to read the WAV data. crop_beginning_seconds: How many seconds to crop from the beginning of the audio. total_length_seconds: The desired duration of the audio. After cropping the beginning of...
Crop WAV data.
def crop_wav_data(wav_data, sample_rate, crop_beginning_seconds, total_length_seconds): """Crop WAV data. Args: wav_data: WAV audio data to crop. sample_rate: The sample rate at which to read the WAV data. crop_beginning_seconds: How many seconds to crop from the beginning of the ...
[ "def", "crop_wav_data", "(", "wav_data", ",", "sample_rate", ",", "crop_beginning_seconds", ",", "total_length_seconds", ")", ":", "y", "=", "wav_data_to_samples", "(", "wav_data", ",", "sample_rate", "=", "sample_rate", ")", "samples_to_crop", "=", "int", "(", "c...
[ 222, 0 ]
[ 242, 58 ]
python
de
['en', 'de', 'sw']
False
jitter_wav_data
(wav_data, sample_rate, jitter_seconds)
Add silence to the beginning of the file. Args: wav_data: WAV audio data to prepend with silence. sample_rate: The sample rate at which to read the WAV data. jitter_seconds: Seconds of silence to prepend. Returns: A version of the WAV audio with jitter_seconds silence prepended.
Add silence to the beginning of the file.
def jitter_wav_data(wav_data, sample_rate, jitter_seconds): """Add silence to the beginning of the file. Args: wav_data: WAV audio data to prepend with silence. sample_rate: The sample rate at which to read the WAV data. jitter_seconds: Seconds of silence to prepend. Returns: A version of th...
[ "def", "jitter_wav_data", "(", "wav_data", ",", "sample_rate", ",", "jitter_seconds", ")", ":", "y", "=", "wav_data_to_samples", "(", "wav_data", ",", "sample_rate", "=", "sample_rate", ")", "silence_samples", "=", "jitter_seconds", "*", "sample_rate", "new_y", "=...
[ 245, 0 ]
[ 260, 48 ]
python
en
['en', 'en', 'en']
True
load_audio
(audio_filename, sample_rate)
Loads an audio file. Args: audio_filename: File path to load. sample_rate: The number of samples per second at which the audio will be returned. Resampling will be performed if necessary. Returns: A numpy array of audio samples, single-channel (mono) and sampled at the specified rate, in f...
Loads an audio file.
def load_audio(audio_filename, sample_rate): """Loads an audio file. Args: audio_filename: File path to load. sample_rate: The number of samples per second at which the audio will be returned. Resampling will be performed if necessary. Returns: A numpy array of audio samples, single-channel ...
[ "def", "load_audio", "(", "audio_filename", ",", "sample_rate", ")", ":", "try", ":", "y", ",", "unused_sr", "=", "librosa", ".", "load", "(", "audio_filename", ",", "sr", "=", "sample_rate", ",", "mono", "=", "True", ")", "except", "Exception", "as", "e...
[ 263, 0 ]
[ 282, 10 ]
python
en
['en', 'ny', 'en']
True
make_stereo
(left, right)
Combine two mono signals into one stereo signal. Both signals must have the same data type. The resulting track will be the length of the longer of the two signals. Args: left: Samples for the left channel. right: Samples for the right channel. Returns: The two channels combined into a stereo sig...
Combine two mono signals into one stereo signal.
def make_stereo(left, right): """Combine two mono signals into one stereo signal. Both signals must have the same data type. The resulting track will be the length of the longer of the two signals. Args: left: Samples for the left channel. right: Samples for the right channel. Returns: The two ...
[ "def", "make_stereo", "(", "left", ",", "right", ")", ":", "if", "left", ".", "dtype", "!=", "right", ".", "dtype", ":", "raise", "AudioIODataTypeError", "(", "'left channel is of type {}, but right channel is {}'", ".", "format", "(", "left", ".", "dtype", ",",...
[ 285, 0 ]
[ 313, 14 ]
python
en
['it', 'en', 'en']
True
normalize_wav_data
(wav_data, sample_rate, norm=np.inf)
Normalizes wav data. Args: wav_data: WAV audio data to prepend with silence. sample_rate: The sample rate at which to read the WAV data. norm: See the norm argument of librosa.util.normalize. Returns: A version of the WAV audio that has been normalized.
Normalizes wav data.
def normalize_wav_data(wav_data, sample_rate, norm=np.inf): """Normalizes wav data. Args: wav_data: WAV audio data to prepend with silence. sample_rate: The sample rate at which to read the WAV data. norm: See the norm argument of librosa.util.normalize. Returns: A version of the WAV audio t...
[ "def", "normalize_wav_data", "(", "wav_data", ",", "sample_rate", ",", "norm", "=", "np", ".", "inf", ")", ":", "y", "=", "wav_data_to_samples", "(", "wav_data", ",", "sample_rate", "=", "sample_rate", ")", "new_y", "=", "librosa", ".", "util", ".", "norma...
[ 316, 0 ]
[ 330, 48 ]
python
en
['en', 'sn', 'sw']
False
Retry.from_int
(cls, retries, redirect=True, default=None)
Backwards-compatibility for the old retries format.
Backwards-compatibility for the old retries format.
def from_int(cls, retries, redirect=True, default=None): """ Backwards-compatibility for the old retries format.""" if retries is None: retries = default if default is not None else cls.DEFAULT if isinstance(retries, Retry): return retries redirect = bool(redire...
[ "def", "from_int", "(", "cls", ",", "retries", ",", "redirect", "=", "True", ",", "default", "=", "None", ")", ":", "if", "retries", "is", "None", ":", "retries", "=", "default", "if", "default", "is", "not", "None", "else", "cls", ".", "DEFAULT", "i...
[ 219, 4 ]
[ 230, 26 ]
python
en
['en', 'en', 'en']
True
Retry.get_backoff_time
(self)
Formula for computing the current backoff :rtype: float
Formula for computing the current backoff
def get_backoff_time(self): """ Formula for computing the current backoff :rtype: float """ # We want to consider only the last consecutive errors sequence (Ignore redirects). consecutive_errors_len = len( list( takewhile(lambda x: x.redirect_location...
[ "def", "get_backoff_time", "(", "self", ")", ":", "# We want to consider only the last consecutive errors sequence (Ignore redirects).", "consecutive_errors_len", "=", "len", "(", "list", "(", "takewhile", "(", "lambda", "x", ":", "x", ".", "redirect_location", "is", "Non...
[ 232, 4 ]
[ 247, 51 ]
python
en
['en', 'en', 'en']
True
Retry.get_retry_after
(self, response)
Get the value of Retry-After in seconds.
Get the value of Retry-After in seconds.
def get_retry_after(self, response): """ Get the value of Retry-After in seconds. """ retry_after = response.getheader("Retry-After") if retry_after is None: return None return self.parse_retry_after(retry_after)
[ "def", "get_retry_after", "(", "self", ",", "response", ")", ":", "retry_after", "=", "response", ".", "getheader", "(", "\"Retry-After\"", ")", "if", "retry_after", "is", "None", ":", "return", "None", "return", "self", ".", "parse_retry_after", "(", "retry_a...
[ 265, 4 ]
[ 273, 50 ]
python
en
['en', 'en', 'en']
True
Retry.sleep
(self, response=None)
Sleep between retry attempts. This method will respect a server's ``Retry-After`` response header and sleep the duration of the time requested. If that is not present, it will use an exponential backoff. By default, the backoff factor is 0 and this method will return immediately. ...
Sleep between retry attempts.
def sleep(self, response=None): """ Sleep between retry attempts. This method will respect a server's ``Retry-After`` response header and sleep the duration of the time requested. If that is not present, it will use an exponential backoff. By default, the backoff factor is 0 and ...
[ "def", "sleep", "(", "self", ",", "response", "=", "None", ")", ":", "if", "self", ".", "respect_retry_after_header", "and", "response", ":", "slept", "=", "self", ".", "sleep_for_retry", "(", "response", ")", "if", "slept", ":", "return", "self", ".", "...
[ 289, 4 ]
[ 303, 29 ]
python
en
['en', 'nl', 'en']
True
Retry._is_connection_error
(self, err)
Errors when we're fairly sure that the server did not receive the request, so it should be safe to retry.
Errors when we're fairly sure that the server did not receive the request, so it should be safe to retry.
def _is_connection_error(self, err): """ Errors when we're fairly sure that the server did not receive the request, so it should be safe to retry. """ if isinstance(err, ProxyError): err = err.original_error return isinstance(err, ConnectTimeoutError)
[ "def", "_is_connection_error", "(", "self", ",", "err", ")", ":", "if", "isinstance", "(", "err", ",", "ProxyError", ")", ":", "err", "=", "err", ".", "original_error", "return", "isinstance", "(", "err", ",", "ConnectTimeoutError", ")" ]
[ 305, 4 ]
[ 311, 51 ]
python
en
['en', 'en', 'en']
True
Retry._is_read_error
(self, err)
Errors that occur after the request has been started, so we should assume that the server began processing it.
Errors that occur after the request has been started, so we should assume that the server began processing it.
def _is_read_error(self, err): """ Errors that occur after the request has been started, so we should assume that the server began processing it. """ return isinstance(err, (ReadTimeoutError, ProtocolError))
[ "def", "_is_read_error", "(", "self", ",", "err", ")", ":", "return", "isinstance", "(", "err", ",", "(", "ReadTimeoutError", ",", "ProtocolError", ")", ")" ]
[ 313, 4 ]
[ 317, 65 ]
python
en
['en', 'en', 'en']
True
Retry._is_method_retryable
(self, method)
Checks if a given HTTP method should be retried upon, depending if it is included on the method whitelist.
Checks if a given HTTP method should be retried upon, depending if it is included on the method whitelist.
def _is_method_retryable(self, method): """ Checks if a given HTTP method should be retried upon, depending if it is included on the method whitelist. """ if self.method_whitelist and method.upper() not in self.method_whitelist: return False return True
[ "def", "_is_method_retryable", "(", "self", ",", "method", ")", ":", "if", "self", ".", "method_whitelist", "and", "method", ".", "upper", "(", ")", "not", "in", "self", ".", "method_whitelist", ":", "return", "False", "return", "True" ]
[ 319, 4 ]
[ 326, 19 ]
python
en
['en', 'en', 'en']
True
Retry.is_retry
(self, method, status_code, has_retry_after=False)
Is this method/status code retryable? (Based on whitelists and control variables such as the number of total retries to allow, whether to respect the Retry-After header, whether this header is present, and whether the returned status code is on the list of status codes to be retried upo...
Is this method/status code retryable? (Based on whitelists and control variables such as the number of total retries to allow, whether to respect the Retry-After header, whether this header is present, and whether the returned status code is on the list of status codes to be retried upo...
def is_retry(self, method, status_code, has_retry_after=False): """ Is this method/status code retryable? (Based on whitelists and control variables such as the number of total retries to allow, whether to respect the Retry-After header, whether this header is present, and whether the re...
[ "def", "is_retry", "(", "self", ",", "method", ",", "status_code", ",", "has_retry_after", "=", "False", ")", ":", "if", "not", "self", ".", "_is_method_retryable", "(", "method", ")", ":", "return", "False", "if", "self", ".", "status_forcelist", "and", "...
[ 328, 4 ]
[ 346, 9 ]
python
en
['en', 'en', 'en']
True
Retry.is_exhausted
(self)
Are we out of retries?
Are we out of retries?
def is_exhausted(self): """ Are we out of retries? """ retry_counts = (self.total, self.connect, self.read, self.redirect, self.status) retry_counts = list(filter(None, retry_counts)) if not retry_counts: return False return min(retry_counts) < 0
[ "def", "is_exhausted", "(", "self", ")", ":", "retry_counts", "=", "(", "self", ".", "total", ",", "self", ".", "connect", ",", "self", ".", "read", ",", "self", ".", "redirect", ",", "self", ".", "status", ")", "retry_counts", "=", "list", "(", "fil...
[ 348, 4 ]
[ 355, 36 ]
python
en
['en', 'en', 'en']
True
Retry.increment
( self, method=None, url=None, response=None, error=None, _pool=None, _stacktrace=None, )
Return a new Retry object with incremented retry counters. :param response: A response object, or None, if the server did not return a response. :type response: :class:`~urllib3.response.HTTPResponse` :param Exception error: An error encountered during the request, or N...
Return a new Retry object with incremented retry counters.
def increment( self, method=None, url=None, response=None, error=None, _pool=None, _stacktrace=None, ): """ Return a new Retry object with incremented retry counters. :param response: A response object, or None, if the server did not ...
[ "def", "increment", "(", "self", ",", "method", "=", "None", ",", "url", "=", "None", ",", "response", "=", "None", ",", "error", "=", "None", ",", "_pool", "=", "None", ",", "_stacktrace", "=", "None", ",", ")", ":", "if", "self", ".", "total", ...
[ 357, 4 ]
[ 442, 24 ]
python
en
['en', 'en', 'en']
True
parse_tag
(tag)
Parses the provided tag (e.g. `py3-none-any`) into a frozenset of Tag instances. Returning a set is required due to the possibility that the tag is a compressed tag set.
Parses the provided tag (e.g. `py3-none-any`) into a frozenset of Tag instances.
def parse_tag(tag): # type: (str) -> FrozenSet[Tag] """ Parses the provided tag (e.g. `py3-none-any`) into a frozenset of Tag instances. Returning a set is required due to the possibility that the tag is a compressed tag set. """ tags = set() interpreters, abis, platforms = tag.split("-...
[ "def", "parse_tag", "(", "tag", ")", ":", "# type: (str) -> FrozenSet[Tag]", "tags", "=", "set", "(", ")", "interpreters", ",", "abis", ",", "platforms", "=", "tag", ".", "split", "(", "\"-\"", ")", "for", "interpreter", "in", "interpreters", ".", "split", ...
[ 116, 0 ]
[ 130, 26 ]
python
en
['en', 'error', 'th']
False
_warn_keyword_parameter
(func_name, kwargs)
Backwards-compatibility with Python 2.7 to allow treating 'warn' as keyword-only.
Backwards-compatibility with Python 2.7 to allow treating 'warn' as keyword-only.
def _warn_keyword_parameter(func_name, kwargs): # type: (str, Dict[str, bool]) -> bool """ Backwards-compatibility with Python 2.7 to allow treating 'warn' as keyword-only. """ if not kwargs: return False elif len(kwargs) > 1 or "warn" not in kwargs: kwargs.pop("warn", None) ...
[ "def", "_warn_keyword_parameter", "(", "func_name", ",", "kwargs", ")", ":", "# type: (str, Dict[str, bool]) -> bool", "if", "not", "kwargs", ":", "return", "False", "elif", "len", "(", "kwargs", ")", ">", "1", "or", "\"warn\"", "not", "in", "kwargs", ":", "kw...
[ 133, 0 ]
[ 146, 25 ]
python
en
['en', 'error', 'th']
False
_abi3_applies
(python_version)
Determine if the Python version supports abi3. PEP 384 was first implemented in Python 3.2.
Determine if the Python version supports abi3.
def _abi3_applies(python_version): # type: (PythonVersion) -> bool """ Determine if the Python version supports abi3. PEP 384 was first implemented in Python 3.2. """ return len(python_version) > 1 and tuple(python_version) >= (3, 2)
[ "def", "_abi3_applies", "(", "python_version", ")", ":", "# type: (PythonVersion) -> bool", "return", "len", "(", "python_version", ")", ">", "1", "and", "tuple", "(", "python_version", ")", ">=", "(", "3", ",", "2", ")" ]
[ 164, 0 ]
[ 171, 70 ]
python
en
['en', 'error', 'th']
False
cpython_tags
( python_version=None, # type: Optional[PythonVersion] abis=None, # type: Optional[Iterable[str]] platforms=None, # type: Optional[Iterable[str]] **kwargs # type: bool )
Yields the tags for a CPython interpreter. The tags consist of: - cp<python_version>-<abi>-<platform> - cp<python_version>-abi3-<platform> - cp<python_version>-none-<platform> - cp<less than python_version>-abi3-<platform> # Older Python versions down to 3.2. If python_version only speci...
Yields the tags for a CPython interpreter.
def cpython_tags( python_version=None, # type: Optional[PythonVersion] abis=None, # type: Optional[Iterable[str]] platforms=None, # type: Optional[Iterable[str]] **kwargs # type: bool ): # type: (...) -> Iterator[Tag] """ Yields the tags for a CPython interpreter. The tags consist o...
[ "def", "cpython_tags", "(", "python_version", "=", "None", ",", "# type: Optional[PythonVersion]", "abis", "=", "None", ",", "# type: Optional[Iterable[str]]", "platforms", "=", "None", ",", "# type: Optional[Iterable[str]]", "*", "*", "kwargs", "# type: bool", ")", ":"...
[ 211, 0 ]
[ 268, 57 ]
python
en
['en', 'error', 'th']
False
generic_tags
( interpreter=None, # type: Optional[str] abis=None, # type: Optional[Iterable[str]] platforms=None, # type: Optional[Iterable[str]] **kwargs # type: bool )
Yields the tags for a generic interpreter. The tags consist of: - <interpreter>-<abi>-<platform> The "none" ABI will be added if it was not explicitly provided.
Yields the tags for a generic interpreter.
def generic_tags( interpreter=None, # type: Optional[str] abis=None, # type: Optional[Iterable[str]] platforms=None, # type: Optional[Iterable[str]] **kwargs # type: bool ): # type: (...) -> Iterator[Tag] """ Yields the tags for a generic interpreter. The tags consist of: - <int...
[ "def", "generic_tags", "(", "interpreter", "=", "None", ",", "# type: Optional[str]", "abis", "=", "None", ",", "# type: Optional[Iterable[str]]", "platforms", "=", "None", ",", "# type: Optional[Iterable[str]]", "*", "*", "kwargs", "# type: bool", ")", ":", "# type: ...
[ 278, 0 ]
[ 306, 50 ]
python
en
['en', 'error', 'th']
False
_py_interpreter_range
(py_version)
Yields Python versions in descending order. After the latest version, the major-only version will be yielded, and then all previous versions of that major version.
Yields Python versions in descending order.
def _py_interpreter_range(py_version): # type: (PythonVersion) -> Iterator[str] """ Yields Python versions in descending order. After the latest version, the major-only version will be yielded, and then all previous versions of that major version. """ if len(py_version) > 1: yield "...
[ "def", "_py_interpreter_range", "(", "py_version", ")", ":", "# type: (PythonVersion) -> Iterator[str]", "if", "len", "(", "py_version", ")", ">", "1", ":", "yield", "\"py{version}\"", ".", "format", "(", "version", "=", "_version_nodot", "(", "py_version", "[", "...
[ 309, 0 ]
[ 322, 86 ]
python
en
['en', 'error', 'th']
False
compatible_tags
( python_version=None, # type: Optional[PythonVersion] interpreter=None, # type: Optional[str] platforms=None, # type: Optional[Iterable[str]] )
Yields the sequence of tags that are compatible with a specific version of Python. The tags consist of: - py*-none-<platform> - <interpreter>-none-any # ... if `interpreter` is provided. - py*-none-any
Yields the sequence of tags that are compatible with a specific version of Python.
def compatible_tags( python_version=None, # type: Optional[PythonVersion] interpreter=None, # type: Optional[str] platforms=None, # type: Optional[Iterable[str]] ): # type: (...) -> Iterator[Tag] """ Yields the sequence of tags that are compatible with a specific version of Python. The t...
[ "def", "compatible_tags", "(", "python_version", "=", "None", ",", "# type: Optional[PythonVersion]", "interpreter", "=", "None", ",", "# type: Optional[str]", "platforms", "=", "None", ",", "# type: Optional[Iterable[str]]", ")", ":", "# type: (...) -> Iterator[Tag]", "if"...
[ 325, 0 ]
[ 348, 41 ]
python
en
['en', 'error', 'th']
False
mac_platforms
(version=None, arch=None)
Yields the platform tags for a macOS system. The `version` parameter is a two-item tuple specifying the macOS version to generate platform tags for. The `arch` parameter is the CPU architecture to generate platform tags for. Both parameters default to the appropriate value for the current system. ...
Yields the platform tags for a macOS system.
def mac_platforms(version=None, arch=None): # type: (Optional[MacVersion], Optional[str]) -> Iterator[str] """ Yields the platform tags for a macOS system. The `version` parameter is a two-item tuple specifying the macOS version to generate platform tags for. The `arch` parameter is the CPU archite...
[ "def", "mac_platforms", "(", "version", "=", "None", ",", "arch", "=", "None", ")", ":", "# type: (Optional[MacVersion], Optional[str]) -> Iterator[str]", "version_str", ",", "_", ",", "cpu_arch", "=", "platform", ".", "mac_ver", "(", ")", "# type: ignore", "if", ...
[ 390, 0 ]
[ 417, 13 ]
python
en
['en', 'error', 'th']
False
_glibc_version_string_confstr
()
Primary implementation of glibc_version_string using os.confstr.
Primary implementation of glibc_version_string using os.confstr.
def _glibc_version_string_confstr(): # type: () -> Optional[str] """ Primary implementation of glibc_version_string using os.confstr. """ # os.confstr is quite a bit faster than ctypes.DLL. It's also less likely # to be broken or missing. This strategy is used in the standard library # platf...
[ "def", "_glibc_version_string_confstr", "(", ")", ":", "# type: () -> Optional[str]", "# os.confstr is quite a bit faster than ctypes.DLL. It's also less likely", "# to be broken or missing. This strategy is used in the standard library", "# platform module.", "# https://github.com/python/cpython/...
[ 441, 0 ]
[ 460, 18 ]
python
en
['en', 'error', 'th']
False
_glibc_version_string_ctypes
()
Fallback implementation of glibc_version_string using ctypes.
Fallback implementation of glibc_version_string using ctypes.
def _glibc_version_string_ctypes(): # type: () -> Optional[str] """ Fallback implementation of glibc_version_string using ctypes. """ try: import ctypes except ImportError: return None # ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen # manpage says, "...
[ "def", "_glibc_version_string_ctypes", "(", ")", ":", "# type: () -> Optional[str]", "try", ":", "import", "ctypes", "except", "ImportError", ":", "return", "None", "# ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen", "# manpage says, \"If filename is NULL, then th...
[ 463, 0 ]
[ 494, 22 ]
python
en
['en', 'error', 'th']
False
_platform_tags
()
Provides the platform tags for this installation.
Provides the platform tags for this installation.
def _platform_tags(): # type: () -> Iterator[str] """ Provides the platform tags for this installation. """ if platform.system() == "Darwin": return mac_platforms() elif platform.system() == "Linux": return _linux_platforms() else: return _generic_platforms()
[ "def", "_platform_tags", "(", ")", ":", "# type: () -> Iterator[str]", "if", "platform", ".", "system", "(", ")", "==", "\"Darwin\"", ":", "return", "mac_platforms", "(", ")", "elif", "platform", ".", "system", "(", ")", "==", "\"Linux\"", ":", "return", "_l...
[ 684, 0 ]
[ 694, 35 ]
python
en
['en', 'error', 'th']
False
interpreter_name
()
Returns the name of the running interpreter.
Returns the name of the running interpreter.
def interpreter_name(): # type: () -> str """ Returns the name of the running interpreter. """ try: name = sys.implementation.name # type: ignore except AttributeError: # pragma: no cover # Python 2.7 compatibility. name = platform.python_implementation().lower() re...
[ "def", "interpreter_name", "(", ")", ":", "# type: () -> str", "try", ":", "name", "=", "sys", ".", "implementation", ".", "name", "# type: ignore", "except", "AttributeError", ":", "# pragma: no cover", "# Python 2.7 compatibility.", "name", "=", "platform", ".", "...
[ 697, 0 ]
[ 707, 52 ]
python
en
['en', 'error', 'th']
False
interpreter_version
(**kwargs)
Returns the version of the running interpreter.
Returns the version of the running interpreter.
def interpreter_version(**kwargs): # type: (bool) -> str """ Returns the version of the running interpreter. """ warn = _warn_keyword_parameter("interpreter_version", kwargs) version = _get_config_var("py_version_nodot", warn=warn) if version: version = str(version) else: ...
[ "def", "interpreter_version", "(", "*", "*", "kwargs", ")", ":", "# type: (bool) -> str", "warn", "=", "_warn_keyword_parameter", "(", "\"interpreter_version\"", ",", "kwargs", ")", "version", "=", "_get_config_var", "(", "\"py_version_nodot\"", ",", "warn", "=", "w...
[ 710, 0 ]
[ 721, 18 ]
python
en
['en', 'error', 'th']
False
sys_tags
(**kwargs)
Returns the sequence of tag triples for the running interpreter. The order of the sequence corresponds to priority order for the interpreter, from most to least important.
Returns the sequence of tag triples for the running interpreter.
def sys_tags(**kwargs): # type: (bool) -> Iterator[Tag] """ Returns the sequence of tag triples for the running interpreter. The order of the sequence corresponds to priority order for the interpreter, from most to least important. """ warn = _warn_keyword_parameter("sys_tags", kwargs) ...
[ "def", "sys_tags", "(", "*", "*", "kwargs", ")", ":", "# type: (bool) -> Iterator[Tag]", "warn", "=", "_warn_keyword_parameter", "(", "\"sys_tags\"", ",", "kwargs", ")", "interp_name", "=", "interpreter_name", "(", ")", "if", "interp_name", "==", "\"cp\"", ":", ...
[ 733, 0 ]
[ 752, 17 ]
python
en
['en', 'error', 'th']
False
api_dev_fetch_api_key
(request: HttpRequest, username: str = REQ())
This function allows logging in without a password on the Zulip mobile apps when connecting to a Zulip development environment. It requires DevAuthBackend to be included in settings.AUTHENTICATION_BACKENDS.
This function allows logging in without a password on the Zulip mobile apps when connecting to a Zulip development environment. It requires DevAuthBackend to be included in settings.AUTHENTICATION_BACKENDS.
def api_dev_fetch_api_key(request: HttpRequest, username: str = REQ()) -> HttpResponse: """This function allows logging in without a password on the Zulip mobile apps when connecting to a Zulip development environment. It requires DevAuthBackend to be included in settings.AUTHENTICATION_BACKENDS. """ ...
[ "def", "api_dev_fetch_api_key", "(", "request", ":", "HttpRequest", ",", "username", ":", "str", "=", "REQ", "(", ")", ")", "->", "HttpResponse", ":", "check_dev_auth_backend", "(", ")", "# Django invokes authenticate methods by matching arguments, and this", "# authentic...
[ 91, 0 ]
[ 124, 83 ]
python
en
['en', 'en', 'en']
True
_basic_auth_str
(username, password)
Returns a Basic Auth string.
Returns a Basic Auth string.
def _basic_auth_str(username, password): """Returns a Basic Auth string.""" # "I want us to put a big-ol' comment on top of it that # says that this behaviour is dumb but we need to preserve # it because people are relying on it." # - Lukasa # # These are here solely to maintain backward...
[ "def", "_basic_auth_str", "(", "username", ",", "password", ")", ":", "# \"I want us to put a big-ol' comment on top of it that", "# says that this behaviour is dumb but we need to preserve", "# it because people are relying on it.\"", "# - Lukasa", "#", "# These are here solely to main...
[ 27, 0 ]
[ 68, 18 ]
python
en
['en', 'en', 'en']
True
HTTPDigestAuth.build_digest_header
(self, method, url)
:rtype: str
:rtype: str
def build_digest_header(self, method, url): """ :rtype: str """ realm = self._thread_local.chal['realm'] nonce = self._thread_local.chal['nonce'] qop = self._thread_local.chal.get('qop') algorithm = self._thread_local.chal.get('algorithm') opaque = self._...
[ "def", "build_digest_header", "(", "self", ",", "method", ",", "url", ")", ":", "realm", "=", "self", ".", "_thread_local", ".", "chal", "[", "'realm'", "]", "nonce", "=", "self", ".", "_thread_local", ".", "chal", "[", "'nonce'", "]", "qop", "=", "sel...
[ 126, 4 ]
[ 226, 35 ]
python
en
['en', 'error', 'th']
False
HTTPDigestAuth.handle_redirect
(self, r, **kwargs)
Reset num_401_calls counter on redirects.
Reset num_401_calls counter on redirects.
def handle_redirect(self, r, **kwargs): """Reset num_401_calls counter on redirects.""" if r.is_redirect: self._thread_local.num_401_calls = 1
[ "def", "handle_redirect", "(", "self", ",", "r", ",", "*", "*", "kwargs", ")", ":", "if", "r", ".", "is_redirect", ":", "self", ".", "_thread_local", ".", "num_401_calls", "=", "1" ]
[ 228, 4 ]
[ 231, 48 ]
python
en
['en', 'en', 'en']
True
HTTPDigestAuth.handle_401
(self, r, **kwargs)
Takes the given response and tries digest-auth, if needed. :rtype: requests.Response
Takes the given response and tries digest-auth, if needed.
def handle_401(self, r, **kwargs): """ Takes the given response and tries digest-auth, if needed. :rtype: requests.Response """ # If response is not 4xx, do not auth # See https://github.com/psf/requests/issues/3772 if not 400 <= r.status_code < 500: ...
[ "def", "handle_401", "(", "self", ",", "r", ",", "*", "*", "kwargs", ")", ":", "# If response is not 4xx, do not auth", "# See https://github.com/psf/requests/issues/3772", "if", "not", "400", "<=", "r", ".", "status_code", "<", "500", ":", "self", ".", "_thread_l...
[ 233, 4 ]
[ 275, 16 ]
python
en
['en', 'error', 'th']
False
Preprocessor.run
(self, lines)
Each subclass of Preprocessor should override the `run` method, which takes the document as a list of strings split by newlines and returns the (possibly modified) list of lines.
Each subclass of Preprocessor should override the `run` method, which takes the document as a list of strings split by newlines and returns the (possibly modified) list of lines.
def run(self, lines): """ Each subclass of Preprocessor should override the `run` method, which takes the document as a list of strings split by newlines and returns the (possibly modified) list of lines. """ pass
[ "def", "run", "(", "self", ",", "lines", ")", ":", "pass" ]
[ 31, 4 ]
[ 38, 12 ]
python
en
['en', 'error', 'th']
False
HtmlStash.__init__
(self)
Create a HtmlStash.
Create a HtmlStash.
def __init__ (self): """ Create a HtmlStash. """ self.html_counter = 0 # for counting inline html segments self.rawHtmlBlocks=[]
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "html_counter", "=", "0", "# for counting inline html segments", "self", ".", "rawHtmlBlocks", "=", "[", "]" ]
[ 46, 4 ]
[ 49, 29 ]
python
en
['en', 'st', 'en']
True
HtmlStash.store
(self, html, safe=False)
Saves an HTML segment for later reinsertion. Returns a placeholder string that needs to be inserted into the document. Keyword arguments: * html: an html segment * safe: label an html segment as safe for safemode Returns : a placeholder string
Saves an HTML segment for later reinsertion. Returns a placeholder string that needs to be inserted into the document.
def store(self, html, safe=False): """ Saves an HTML segment for later reinsertion. Returns a placeholder string that needs to be inserted into the document. Keyword arguments: * html: an html segment * safe: label an html segment as safe for safemode ...
[ "def", "store", "(", "self", ",", "html", ",", "safe", "=", "False", ")", ":", "self", ".", "rawHtmlBlocks", ".", "append", "(", "(", "html", ",", "safe", ")", ")", "placeholder", "=", "HTML_PLACEHOLDER", "%", "self", ".", "html_counter", "self", ".", ...
[ 51, 4 ]
[ 68, 26 ]
python
en
['en', 'error', 'th']
False
download_from_url
(url, path)
Download file, with logic (from tensor2tensor) for Google Drive
Download file, with logic (from tensor2tensor) for Google Drive
def download_from_url(url, path): """Download file, with logic (from tensor2tensor) for Google Drive""" if 'drive.google.com' not in url: print('Downloading %s; may take a few minutes' % url) r = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'}) with open(path, "wb") as file: ...
[ "def", "download_from_url", "(", "url", ",", "path", ")", ":", "if", "'drive.google.com'", "not", "in", "url", ":", "print", "(", "'Downloading %s; may take a few minutes'", "%", "url", ")", "r", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", ...
[ 2, 0 ]
[ 26, 30 ]
python
en
['en', 'en', 'en']
True
Encoder.needsEncoding
(self, s)
Get whether string I{s} contains special characters. @param s: A string to check. @type s: str @return: True if needs encoding. @rtype: boolean
Get whether string I{s} contains special characters.
def needsEncoding(self, s): """ Get whether string I{s} contains special characters. @param s: A string to check. @type s: str @return: True if needs encoding. @rtype: boolean """ if isinstance(s, basestring): for c in self.special: ...
[ "def", "needsEncoding", "(", "self", ",", "s", ")", ":", "if", "isinstance", "(", "s", ",", "basestring", ")", ":", "for", "c", "in", "self", ".", "special", ":", "if", "c", "in", "s", ":", "return", "True", "return", "False" ]
[ 40, 4 ]
[ 52, 20 ]
python
en
['en', 'error', 'th']
False
Encoder.encode
(self, s)
Encode special characters found in string I{s}. @param s: A string to encode. @type s: str @return: The encoded string. @rtype: str
Encode special characters found in string I{s}.
def encode(self, s): """ Encode special characters found in string I{s}. @param s: A string to encode. @type s: str @return: The encoded string. @rtype: str """ if isinstance(s, basestring) and self.needsEncoding(s): for x in self.encodings: ...
[ "def", "encode", "(", "self", ",", "s", ")", ":", "if", "isinstance", "(", "s", ",", "basestring", ")", "and", "self", ".", "needsEncoding", "(", "s", ")", ":", "for", "x", "in", "self", ".", "encodings", ":", "s", "=", "re", ".", "sub", "(", "...
[ 54, 4 ]
[ 65, 16 ]
python
en
['en', 'error', 'th']
False
Encoder.decode
(self, s)
Decode special characters encodings found in string I{s}. @param s: A string to decode. @type s: str @return: The decoded string. @rtype: str
Decode special characters encodings found in string I{s}.
def decode(self, s): """ Decode special characters encodings found in string I{s}. @param s: A string to decode. @type s: str @return: The decoded string. @rtype: str """ if isinstance(s, basestring) and '&' in s: for x in self.decodings: ...
[ "def", "decode", "(", "self", ",", "s", ")", ":", "if", "isinstance", "(", "s", ",", "basestring", ")", "and", "'&'", "in", "s", ":", "for", "x", "in", "self", ".", "decodings", ":", "s", "=", "s", ".", "replace", "(", "x", "[", "0", "]", ","...
[ 67, 4 ]
[ 78, 16 ]
python
en
['en', 'error', 'th']
False
tostring
(element)
Serialize an element and its child nodes to a string
Serialize an element and its child nodes to a string
def tostring(element): """Serialize an element and its child nodes to a string""" rv = [] def serializeElement(element): if not hasattr(element, "tag"): if element.docinfo.internalDTD: if element.docinfo.doctype: dtd_str = element.docinfo.doctype ...
[ "def", "tostring", "(", "element", ")", ":", "rv", "=", "[", "]", "def", "serializeElement", "(", "element", ")", ":", "if", "not", "hasattr", "(", "element", ",", "\"tag\"", ")", ":", "if", "element", ".", "docinfo", ".", "internalDTD", ":", "if", "...
[ 143, 0 ]
[ 181, 22 ]
python
en
['en', 'en', 'en']
True
main
()
Script entry point.
Script entry point.
def main(): """Script entry point.""" cfg = parse_args() return run(cfg)
[ "def", "main", "(", ")", ":", "cfg", "=", "parse_args", "(", ")", "return", "run", "(", "cfg", ")" ]
[ 124, 0 ]
[ 127, 19 ]
python
en
['en', 'en', 'en']
True
test_analyzer_numeric_describe
(fixture_features, numerical_features)
Testing if numerical_describe dataframe returned by the Analyzer is correct.
Testing if numerical_describe dataframe returned by the Analyzer is correct.
def test_analyzer_numeric_describe(fixture_features, numerical_features): """Testing if numerical_describe dataframe returned by the Analyzer is correct.""" expected_df = pd.DataFrame({ "count": [99.0, 98], "mean": [179.98, 40], "std": [5.40, 30], "min": [165.30, 1.53], "...
[ "def", "test_analyzer_numeric_describe", "(", "fixture_features", ",", "numerical_features", ")", ":", "expected_df", "=", "pd", ".", "DataFrame", "(", "{", "\"count\"", ":", "[", "99.0", ",", "98", "]", ",", "\"mean\"", ":", "[", "179.98", ",", "40", "]", ...
[ 6, 0 ]
[ 23, 40 ]
python
en
['en', 'en', 'en']
True
test_analyzer_numeric_describe_no_numerical_features
(data_classification_balanced)
Testing if numeric_describe() returns None when there are no numerical columns present.
Testing if numeric_describe() returns None when there are no numerical columns present.
def test_analyzer_numeric_describe_no_numerical_features(data_classification_balanced): """Testing if numeric_describe() returns None when there are no numerical columns present.""" numerical_cols = ["Price", "Height"] X, y = data_classification_balanced X = X.drop(numerical_cols, axis=1) f = Featu...
[ "def", "test_analyzer_numeric_describe_no_numerical_features", "(", "data_classification_balanced", ")", ":", "numerical_cols", "=", "[", "\"Price\"", ",", "\"Height\"", "]", "X", ",", "y", "=", "data_classification_balanced", "X", "=", "X", ".", "drop", "(", "numeric...
[ 26, 0 ]
[ 36, 32 ]
python
en
['en', 'it', 'en']
True
test_analyzer_categorical_describe_no_categorical_features
(data_classification_balanced)
Testing if categorical_describe() returns None when there are no categorical columns present.
Testing if categorical_describe() returns None when there are no categorical columns present.
def test_analyzer_categorical_describe_no_categorical_features(data_classification_balanced): """Testing if categorical_describe() returns None when there are no categorical columns present.""" numerical_cols = ["Price", "Height"] # its easier to provide numerical columns instead of dropping all categorical ...
[ "def", "test_analyzer_categorical_describe_no_categorical_features", "(", "data_classification_balanced", ")", ":", "numerical_cols", "=", "[", "\"Price\"", ",", "\"Height\"", "]", "# its easier to provide numerical columns instead of dropping all categorical", "data", "=", "data_cla...
[ 39, 0 ]
[ 50, 32 ]
python
en
['en', 'en', 'en']
True
test_analyzer_categorical_describe
(fixture_features, categorical_features)
Testing if categorical_describe dataframe returned by the Analyzer is correct.
Testing if categorical_describe dataframe returned by the Analyzer is correct.
def test_analyzer_categorical_describe(fixture_features, categorical_features): """Testing if categorical_describe dataframe returned by the Analyzer is correct.""" expected_df = pd.DataFrame({ "count": [100.0, 100.0, 99.0, 99.0, 100], "mean": [4.73, 1.53, 5.34, 1.51, 1.60], "std": [2.55...
[ "def", "test_analyzer_categorical_describe", "(", "fixture_features", ",", "categorical_features", ")", ":", "expected_df", "=", "pd", ".", "DataFrame", "(", "{", "\"count\"", ":", "[", "100.0", ",", "100.0", ",", "99.0", ",", "99.0", ",", "100", "]", ",", "...
[ 53, 0 ]
[ 70, 40 ]
python
en
['en', 'en', 'en']
True
test_analyzer_head_dataframe
(data_classification_balanced, fixture_features, expected_raw_mapping)
Testing if .df_head() returns correct dataframe.
Testing if .df_head() returns correct dataframe.
def test_analyzer_head_dataframe(data_classification_balanced, fixture_features, expected_raw_mapping): """Testing if .df_head() returns correct dataframe.""" X = data_classification_balanced[0] y = data_classification_balanced[1] df = pd.concat([X, y], axis=1) cols = sorted(["Sex", "AgeGroup", "Hei...
[ "def", "test_analyzer_head_dataframe", "(", "data_classification_balanced", ",", "fixture_features", ",", "expected_raw_mapping", ")", ":", "X", "=", "data_classification_balanced", "[", "0", "]", "y", "=", "data_classification_balanced", "[", "1", "]", "df", "=", "pd...
[ 73, 0 ]
[ 84, 40 ]
python
en
['fr', 'ja', 'en']
False
test_analyzer_summary_statistics
( data_classification_balanced, fixture_features, expected_mapping, feature, desc, missing, category )
Testing if _summary_statistics() method generates correct output.
Testing if _summary_statistics() method generates correct output.
def test_analyzer_summary_statistics( data_classification_balanced, fixture_features, expected_mapping, feature, desc, missing, category ): """Testing if _summary_statistics() method generates correct output.""" df = fixture_features.data() describe_dict = df.describe().round(4).to_dict() print(...
[ "def", "test_analyzer_summary_statistics", "(", "data_classification_balanced", ",", "fixture_features", ",", "expected_mapping", ",", "feature", ",", "desc", ",", "missing", ",", "category", ")", ":", "df", "=", "fixture_features", ".", "data", "(", ")", "describe_...
[ 99, 0 ]
[ 126, 39 ]
python
de
['de', 'zu', 'en']
False
test_analyzer_histogram_data
(fixture_features, feature_name, expected_number_of_bins)
Testing if ._histogram_data() method returns correct values. Checking only number of bins for every feature, as edges were 1) tested elsewhere 2) assuming that np.histogram works correctly 3) would be cumbersome to calculate all of that by hand.
Testing if ._histogram_data() method returns correct values. Checking only number of bins for every feature, as edges were 1) tested elsewhere 2) assuming that np.histogram works correctly 3) would be cumbersome to calculate all of that by hand.
def test_analyzer_histogram_data(fixture_features, feature_name, expected_number_of_bins): """Testing if ._histogram_data() method returns correct values. Checking only number of bins for every feature, as edges were 1) tested elsewhere 2) assuming that np.histogram works correctly 3) would be cumbe...
[ "def", "test_analyzer_histogram_data", "(", "fixture_features", ",", "feature_name", ",", "expected_number_of_bins", ")", ":", "analyzer", "=", "Analyzer", "(", "fixture_features", ")", "histogram_output", "=", "analyzer", ".", "histogram_data", "(", ")", "# number of b...
[ 141, 0 ]
[ 152, 59 ]
python
en
['en', 'zu', 'en']
True
test_analyzer_correlation_data
(fixture_features, feature, expected_result)
Testing if correlations between features are calculated correctly.
Testing if correlations between features are calculated correctly.
def test_analyzer_correlation_data(fixture_features, feature, expected_result): """Testing if correlations between features are calculated correctly.""" cols_in_order = ["Sex", "AgeGroup", "Height", "Product", "Price", "bool", "Target"] rs = 1 analyzer = Analyzer(fixture_features) corr = analyzer.co...
[ "def", "test_analyzer_correlation_data", "(", "fixture_features", ",", "feature", ",", "expected_result", ")", ":", "cols_in_order", "=", "[", "\"Sex\"", ",", "\"AgeGroup\"", ",", "\"Height\"", ",", "\"Product\"", ",", "\"Price\"", ",", "\"bool\"", ",", "\"Target\""...
[ 167, 0 ]
[ 176, 53 ]
python
en
['en', 'en', 'en']
True
test_analyzer_correlation_data_raw
(fixture_features, feature, expected_result)
Testing if correlations between features are calculated correctly.
Testing if correlations between features are calculated correctly.
def test_analyzer_correlation_data_raw(fixture_features, feature, expected_result): """Testing if correlations between features are calculated correctly.""" cols_in_order = ["Sex", "AgeGroup", "Height", "Product", "Price", "bool", "Target"] analyzer = Analyzer(fixture_features) corr = analyzer.correlati...
[ "def", "test_analyzer_correlation_data_raw", "(", "fixture_features", ",", "feature", ",", "expected_result", ")", ":", "cols_in_order", "=", "[", "\"Sex\"", ",", "\"AgeGroup\"", ",", "\"Height\"", ",", "\"Product\"", ",", "\"Price\"", ",", "\"bool\"", ",", "\"Targe...
[ 191, 0 ]
[ 199, 53 ]
python
en
['en', 'en', 'en']
True
test_analyzer_scatter_data
( fixture_features, data_classification_balanced, expected_raw_mapping, categorical_features )
Testing if ._scatter_data() returns correct values.
Testing if ._scatter_data() returns correct values.
def test_analyzer_scatter_data( fixture_features, data_classification_balanced, expected_raw_mapping, categorical_features ): """Testing if ._scatter_data() returns correct values.""" analyzer = Analyzer(fixture_features) X = data_classification_balanced[0] y = data_classification_balanced[1] ...
[ "def", "test_analyzer_scatter_data", "(", "fixture_features", ",", "data_classification_balanced", ",", "expected_raw_mapping", ",", "categorical_features", ")", ":", "analyzer", "=", "Analyzer", "(", "fixture_features", ")", "X", "=", "data_classification_balanced", "[", ...
[ 202, 0 ]
[ 221, 29 ]
python
en
['en', 'no', 'en']
True
VolumesFilterAction.filter
(self, table, volumes, filter_string)
Naive case-insensitive search.
Naive case-insensitive search.
def filter(self, table, volumes, filter_string): """Naive case-insensitive search.""" q = filter_string.lower() return [volume for volume in volumes if q in volume.name.lower()]
[ "def", "filter", "(", "self", ",", "table", ",", "volumes", ",", "filter_string", ")", ":", "q", "=", "filter_string", ".", "lower", "(", ")", "return", "[", "volume", "for", "volume", "in", "volumes", "if", "q", "in", "volume", ".", "name", ".", "lo...
[ 521, 4 ]
[ 525, 44 ]
python
en
['en', 'it', 'en']
True
RateLimiterBackendBase.api_calls_left_from_history
( self, history: List[float], max_window: int, max_calls: int, now: float )
This depends on the algorithm used in the backend, and should be defined by the test class.
This depends on the algorithm used in the backend, and should be defined by the test class.
def api_calls_left_from_history( self, history: List[float], max_window: int, max_calls: int, now: float ) -> Tuple[int, float]: """ This depends on the algorithm used in the backend, and should be defined by the test class. """ raise NotImplementedError()
[ "def", "api_calls_left_from_history", "(", "self", ",", "history", ":", "List", "[", "float", "]", ",", "max_window", ":", "int", ",", "max_calls", ":", "int", ",", "now", ":", "float", ")", "->", "Tuple", "[", "int", ",", "float", "]", ":", "raise", ...
[ 85, 4 ]
[ 91, 35 ]
python
en
['en', 'error', 'th']
False
RedisRateLimiterBackendTest.test_block_access
(self)
This test cannot verify that the user will get unblocked after the correct amount of time, because that event happens inside Redis, so we're not able to mock the timer. Making the test sleep for 1s is also too costly to be worth it.
This test cannot verify that the user will get unblocked after the correct amount of time, because that event happens inside Redis, so we're not able to mock the timer. Making the test sleep for 1s is also too costly to be worth it.
def test_block_access(self) -> None: """ This test cannot verify that the user will get unblocked after the correct amount of time, because that event happens inside Redis, so we're not able to mock the timer. Making the test sleep for 1s is also too costly to be worth it. ...
[ "def", "test_block_access", "(", "self", ")", "->", "None", ":", "obj", "=", "self", ".", "create_object", "(", "\"test\"", ",", "[", "(", "2", ",", "5", ")", "]", ")", "obj", ".", "block_access", "(", "1", ")", "self", ".", "make_request", "(", "o...
[ 164, 4 ]
[ 174, 84 ]
python
en
['en', 'error', 'th']
False
APPO.init_subset
(self, indices, actor_queues)
Initialize a subset of actor workers (rollout workers) and wait until the first reset() is completed for all envs on these workers. This function will retry if the worker process crashes during the initial reset. :param indices: indices of actor workers to initialize :param ac...
Initialize a subset of actor workers (rollout workers) and wait until the first reset() is completed for all envs on these workers.
def init_subset(self, indices, actor_queues): """ Initialize a subset of actor workers (rollout workers) and wait until the first reset() is completed for all envs on these workers. This function will retry if the worker process crashes during the initial reset. :param indices:...
[ "def", "init_subset", "(", "self", ",", "indices", ",", "actor_queues", ")", ":", "reset_timelimit_seconds", "=", "self", ".", "cfg", ".", "reset_timeout_seconds", "# fail worker if not a single env was reset in that time", "workers", "=", "dict", "(", ")", "last_env_in...
[ 332, 4 ]
[ 404, 31 ]
python
en
['en', 'error', 'th']
False
APPO.init_workers
(self)
Initialize all types of workers and start their worker processes.
Initialize all types of workers and start their worker processes.
def init_workers(self): """ Initialize all types of workers and start their worker processes. """ actor_queues = [MpQueue(2 * 1000 * 1000) for _ in range(self.cfg.num_workers)] policy_worker_queues = dict() for policy_id in range(self.cfg.num_policies): poli...
[ "def", "init_workers", "(", "self", ")", ":", "actor_queues", "=", "[", "MpQueue", "(", "2", "*", "1000", "*", "1000", ")", "for", "_", "in", "range", "(", "self", ".", "cfg", ".", "num_workers", ")", "]", "policy_worker_queues", "=", "dict", "(", ")...
[ 407, 4 ]
[ 466, 46 ]
python
en
['en', 'error', 'th']
False
APPO.finish_initialization
(self)
Wait until policy workers are fully initialized.
Wait until policy workers are fully initialized.
def finish_initialization(self): """Wait until policy workers are fully initialized.""" for policy_id, workers in self.policy_workers.items(): for w in workers: log.debug('Waiting for policy worker %d-%d to finish initialization...', policy_id, w.worker_idx) w...
[ "def", "finish_initialization", "(", "self", ")", ":", "for", "policy_id", ",", "workers", "in", "self", ".", "policy_workers", ".", "items", "(", ")", ":", "for", "w", "in", "workers", ":", "log", ".", "debug", "(", "'Waiting for policy worker %d-%d to finish...
[ 472, 4 ]
[ 478, 86 ]
python
en
['en', 'en', 'en']
True
APPO.process_report
(self, report)
Process stats from various types of workers.
Process stats from various types of workers.
def process_report(self, report): """Process stats from various types of workers.""" if 'policy_id' in report: policy_id = report['policy_id'] if 'learner_env_steps' in report: if policy_id in self.env_steps: delta = report['learner_env_steps...
[ "def", "process_report", "(", "self", ",", "report", ")", ":", "if", "'policy_id'", "in", "report", ":", "policy_id", "=", "report", "[", "'policy_id'", "]", "if", "'learner_env_steps'", "in", "report", ":", "if", "policy_id", "in", "self", ".", "env_steps",...
[ 484, 4 ]
[ 520, 46 ]
python
en
['en', 'en', 'en']
True
APPO.report
(self)
Called periodically (every X seconds, see report_interval). Print experiment stats (FPS, avg rewards) to console and dump TF summaries collected from workers to disk.
Called periodically (every X seconds, see report_interval). Print experiment stats (FPS, avg rewards) to console and dump TF summaries collected from workers to disk.
def report(self): """ Called periodically (every X seconds, see report_interval). Print experiment stats (FPS, avg rewards) to console and dump TF summaries collected from workers to disk. """ if len(self.env_steps) < self.cfg.num_policies: return now = time...
[ "def", "report", "(", "self", ")", ":", "if", "len", "(", "self", ".", "env_steps", ")", "<", "self", ".", "cfg", ".", "num_policies", ":", "return", "now", "=", "time", ".", "time", "(", ")", "self", ".", "fps_stats", ".", "append", "(", "(", "n...
[ 522, 4 ]
[ 555, 56 ]
python
en
['en', 'error', 'th']
False