repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
salu133445/pypianoroll | pypianoroll/multitrack.py | Multitrack.transpose | 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 | 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... | [
"def",
"transpose",
"(",
"self",
",",
"semitone",
")",
":",
"for",
"track",
"in",
"self",
".",
"tracks",
":",
"if",
"not",
"track",
".",
"is_drum",
":",
"track",
".",
"transpose",
"(",
"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
The number of semitones to transpose the pianorolls. | [
"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",
... | train | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/multitrack.py#L954-L968 |
salu133445/pypianoroll | pypianoroll/multitrack.py | Multitrack.trim_trailing_silence | 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 | 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] | [
"def",
"trim_trailing_silence",
"(",
"self",
")",
":",
"active_length",
"=",
"self",
".",
"get_active_length",
"(",
")",
"for",
"track",
"in",
"self",
".",
"tracks",
":",
"track",
".",
"pianoroll",
"=",
"track",
".",
"pianoroll",
"[",
":",
"active_length",
... | Trim the trailing silences of the pianorolls of all tracks. Trailing
silences are considered globally. | [
"Trim",
"the",
"trailing",
"silences",
"of",
"the",
"pianorolls",
"of",
"all",
"tracks",
".",
"Trailing",
"silences",
"are",
"considered",
"globally",
"."
] | train | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/multitrack.py#L970-L975 |
salu133445/pypianoroll | pypianoroll/multitrack.py | Multitrack.write | 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 | 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... | [
"def",
"write",
"(",
"self",
",",
"filename",
")",
":",
"if",
"not",
"filename",
".",
"endswith",
"(",
"(",
"'.mid'",
",",
"'.midi'",
",",
"'.MID'",
",",
"'.MIDI'",
")",
")",
":",
"filename",
"=",
"filename",
"+",
"'.mid'",
"pm",
"=",
"self",
".",
... | Write the multitrack pianoroll to a MIDI file.
Parameters
----------
filename : str
The name of the MIDI file to which the multitrack pianoroll is
written. | [
"Write",
"the",
"multitrack",
"pianoroll",
"to",
"a",
"MIDI",
"file",
"."
] | train | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/multitrack.py#L977-L991 |
salu133445/pypianoroll | pypianoroll/utilities.py | check_pianoroll | 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 | 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... | [
"def",
"check_pianoroll",
"(",
"arr",
")",
":",
"if",
"not",
"isinstance",
"(",
"arr",
",",
"np",
".",
"ndarray",
")",
":",
"raise",
"TypeError",
"(",
"\"`arr` must be of np.ndarray type\"",
")",
"if",
"not",
"(",
"np",
".",
"issubdtype",
"(",
"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. | [
"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",
"."
] | train | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/utilities.py#L20-L35 |
salu133445/pypianoroll | pypianoroll/utilities.py | binarize | def binarize(obj, threshold=0):
"""
Return a copy of the object with binarized piano-roll(s).
Parameters
----------
threshold : int or float
Threshold to binarize the piano-roll(s). Default to zero.
"""
_check_supported(obj)
copied = deepcopy(obj)
copied.binarize(threshold)... | python | def binarize(obj, threshold=0):
"""
Return a copy of the object with binarized piano-roll(s).
Parameters
----------
threshold : int or float
Threshold to binarize the piano-roll(s). Default to zero.
"""
_check_supported(obj)
copied = deepcopy(obj)
copied.binarize(threshold)... | [
"def",
"binarize",
"(",
"obj",
",",
"threshold",
"=",
"0",
")",
":",
"_check_supported",
"(",
"obj",
")",
"copied",
"=",
"deepcopy",
"(",
"obj",
")",
"copied",
".",
"binarize",
"(",
"threshold",
")",
"return",
"copied"
] | Return a copy of the object with binarized piano-roll(s).
Parameters
----------
threshold : int or float
Threshold to binarize the piano-roll(s). Default to zero. | [
"Return",
"a",
"copy",
"of",
"the",
"object",
"with",
"binarized",
"piano",
"-",
"roll",
"(",
"s",
")",
"."
] | train | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/utilities.py#L53-L66 |
salu133445/pypianoroll | pypianoroll/utilities.py | clip | def clip(obj, lower=0, upper=127):
"""
Return a copy of the object with piano-roll(s) clipped by a lower bound
and an upper bound specified by `lower` and `upper`, respectively.
Parameters
----------
lower : int or float
The lower bound to clip the piano-roll. Default to 0.
upper : ... | python | def clip(obj, lower=0, upper=127):
"""
Return a copy of the object with piano-roll(s) clipped by a lower bound
and an upper bound specified by `lower` and `upper`, respectively.
Parameters
----------
lower : int or float
The lower bound to clip the piano-roll. Default to 0.
upper : ... | [
"def",
"clip",
"(",
"obj",
",",
"lower",
"=",
"0",
",",
"upper",
"=",
"127",
")",
":",
"_check_supported",
"(",
"obj",
")",
"copied",
"=",
"deepcopy",
"(",
"obj",
")",
"copied",
".",
"clip",
"(",
"lower",
",",
"upper",
")",
"return",
"copied"
] | Return a copy of the object with piano-roll(s) clipped by a lower bound
and an upper bound specified by `lower` and `upper`, respectively.
Parameters
----------
lower : int or float
The lower bound to clip the piano-roll. Default to 0.
upper : int or float
The upper bound to clip th... | [
"Return",
"a",
"copy",
"of",
"the",
"object",
"with",
"piano",
"-",
"roll",
"(",
"s",
")",
"clipped",
"by",
"a",
"lower",
"bound",
"and",
"an",
"upper",
"bound",
"specified",
"by",
"lower",
"and",
"upper",
"respectively",
"."
] | train | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/utilities.py#L68-L84 |
salu133445/pypianoroll | pypianoroll/utilities.py | pad | 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 | 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... | [
"def",
"pad",
"(",
"obj",
",",
"pad_length",
")",
":",
"_check_supported",
"(",
"obj",
")",
"copied",
"=",
"deepcopy",
"(",
"obj",
")",
"copied",
".",
"pad",
"(",
"pad_length",
")",
"return",
"copied"
] | 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. | [
"Return",
"a",
"copy",
"of",
"the",
"object",
"with",
"piano",
"-",
"roll",
"padded",
"with",
"zeros",
"at",
"the",
"end",
"along",
"the",
"time",
"axis",
"."
] | train | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/utilities.py#L107-L121 |
salu133445/pypianoroll | pypianoroll/utilities.py | pad_to_multiple | 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 | 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 ... | [
"def",
"pad_to_multiple",
"(",
"obj",
",",
"factor",
")",
":",
"_check_supported",
"(",
"obj",
")",
"copied",
"=",
"deepcopy",
"(",
"obj",
")",
"copied",
".",
"pad_to_multiple",
"(",
"factor",
")",
"return",
"copied"
] | 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 the length of the resulting piano-roll will be... | [
"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... | train | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/utilities.py#L123-L139 |
salu133445/pypianoroll | pypianoroll/utilities.py | pad_to_same | 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 | 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... | [
"def",
"pad_to_same",
"(",
"obj",
")",
":",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"Multitrack",
")",
":",
"raise",
"TypeError",
"(",
"\"Support only `pypianoroll.Multitrack` class objects\"",
")",
"copied",
"=",
"deepcopy",
"(",
"obj",
")",
"copied",
".",
... | 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. | [
"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",
"... | train | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/utilities.py#L141-L152 |
salu133445/pypianoroll | pypianoroll/utilities.py | parse | def parse(filepath, beat_resolution=24, name='unknown'):
"""
Return a :class:`pypianoroll.Multitrack` object loaded from a MIDI
(.mid, .midi, .MID, .MIDI) file.
Parameters
----------
filepath : str
The file path to the MIDI file.
"""
if not filepath.endswith(('.mid', '.midi', '... | python | def parse(filepath, beat_resolution=24, name='unknown'):
"""
Return a :class:`pypianoroll.Multitrack` object loaded from a MIDI
(.mid, .midi, .MID, .MIDI) file.
Parameters
----------
filepath : str
The file path to the MIDI file.
"""
if not filepath.endswith(('.mid', '.midi', '... | [
"def",
"parse",
"(",
"filepath",
",",
"beat_resolution",
"=",
"24",
",",
"name",
"=",
"'unknown'",
")",
":",
"if",
"not",
"filepath",
".",
"endswith",
"(",
"(",
"'.mid'",
",",
"'.midi'",
",",
"'.MID'",
",",
"'.MIDI'",
")",
")",
":",
"raise",
"ValueErro... | Return a :class:`pypianoroll.Multitrack` object loaded from a MIDI
(.mid, .midi, .MID, .MIDI) file.
Parameters
----------
filepath : str
The file path to the MIDI file. | [
"Return",
"a",
":",
"class",
":",
"pypianoroll",
".",
"Multitrack",
"object",
"loaded",
"from",
"a",
"MIDI",
"(",
".",
"mid",
".",
"midi",
".",
"MID",
".",
"MIDI",
")",
"file",
"."
] | train | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/utilities.py#L154-L167 |
salu133445/pypianoroll | pypianoroll/utilities.py | save | 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 | 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... | [
"def",
"save",
"(",
"filepath",
",",
"obj",
",",
"compressed",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"Multitrack",
")",
":",
"raise",
"TypeError",
"(",
"\"Support only `pypianoroll.Multitrack` class objects\"",
")",
"obj",
".",
"sa... | 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. | [
"Save",
"the",
"object",
"to",
"a",
".",
"npz",
"file",
"."
] | train | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/utilities.py#L178-L192 |
salu133445/pypianoroll | pypianoroll/utilities.py | transpose | def transpose(obj, semitone):
"""
Return a copy of the object with piano-roll(s) transposed by `semitones`
semitones.
Parameters
----------
semitone : int
Number of semitones to transpose the piano-roll(s).
"""
_check_supported(obj)
copied = deepcopy(obj)
copied.transpo... | python | def transpose(obj, semitone):
"""
Return a copy of the object with piano-roll(s) transposed by `semitones`
semitones.
Parameters
----------
semitone : int
Number of semitones to transpose the piano-roll(s).
"""
_check_supported(obj)
copied = deepcopy(obj)
copied.transpo... | [
"def",
"transpose",
"(",
"obj",
",",
"semitone",
")",
":",
"_check_supported",
"(",
"obj",
")",
"copied",
"=",
"deepcopy",
"(",
"obj",
")",
"copied",
".",
"transpose",
"(",
"semitone",
")",
"return",
"copied"
] | Return a copy of the object with piano-roll(s) transposed by `semitones`
semitones.
Parameters
----------
semitone : int
Number of semitones to transpose the piano-roll(s). | [
"Return",
"a",
"copy",
"of",
"the",
"object",
"with",
"piano",
"-",
"roll",
"(",
"s",
")",
"transposed",
"by",
"semitones",
"semitones",
"."
] | train | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/utilities.py#L194-L208 |
salu133445/pypianoroll | pypianoroll/utilities.py | trim_trailing_silence | def trim_trailing_silence(obj):
"""
Return a copy of the object with trimmed trailing silence of the
piano-roll(s).
"""
_check_supported(obj)
copied = deepcopy(obj)
length = copied.get_active_length()
copied.pianoroll = copied.pianoroll[:length]
return copied | python | def trim_trailing_silence(obj):
"""
Return a copy of the object with trimmed trailing silence of the
piano-roll(s).
"""
_check_supported(obj)
copied = deepcopy(obj)
length = copied.get_active_length()
copied.pianoroll = copied.pianoroll[:length]
return copied | [
"def",
"trim_trailing_silence",
"(",
"obj",
")",
":",
"_check_supported",
"(",
"obj",
")",
"copied",
"=",
"deepcopy",
"(",
"obj",
")",
"length",
"=",
"copied",
".",
"get_active_length",
"(",
")",
"copied",
".",
"pianoroll",
"=",
"copied",
".",
"pianoroll",
... | Return a copy of the object with trimmed trailing silence of the
piano-roll(s). | [
"Return",
"a",
"copy",
"of",
"the",
"object",
"with",
"trimmed",
"trailing",
"silence",
"of",
"the",
"piano",
"-",
"roll",
"(",
"s",
")",
"."
] | train | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/utilities.py#L210-L220 |
salu133445/pypianoroll | pypianoroll/utilities.py | write | 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 | 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) | [
"def",
"write",
"(",
"obj",
",",
"filepath",
")",
":",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"Multitrack",
")",
":",
"raise",
"TypeError",
"(",
"\"Support only `pypianoroll.Multitrack` class objects\"",
")",
"obj",
".",
"write",
"(",
"filepath",
")"
] | Write the object to a MIDI file.
Parameters
----------
filepath : str
The path to write the MIDI file. | [
"Write",
"the",
"object",
"to",
"a",
"MIDI",
"file",
"."
] | train | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/utilities.py#L222-L234 |
salu133445/pypianoroll | pypianoroll/metrics.py | _validate_pianoroll | 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 | 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,... | [
"def",
"_validate_pianoroll",
"(",
"pianoroll",
")",
":",
"if",
"not",
"isinstance",
"(",
"pianoroll",
",",
"np",
".",
"ndarray",
")",
":",
"raise",
"TypeError",
"(",
"\"`pianoroll` must be of np.ndarray type.\"",
")",
"if",
"not",
"(",
"np",
".",
"issubdtype",
... | Raise an error if the input array is not a standard pianoroll. | [
"Raise",
"an",
"error",
"if",
"the",
"input",
"array",
"is",
"not",
"a",
"standard",
"pianoroll",
"."
] | train | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/metrics.py#L7-L19 |
salu133445/pypianoroll | pypianoroll/metrics.py | _to_chroma | 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 | 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) | [
"def",
"_to_chroma",
"(",
"pianoroll",
")",
":",
"_validate_pianoroll",
"(",
"pianoroll",
")",
"reshaped",
"=",
"pianoroll",
"[",
":",
",",
":",
"120",
"]",
".",
"reshape",
"(",
"-",
"1",
",",
"12",
",",
"10",
")",
"reshaped",
"[",
"...",
",",
":",
... | Return the unnormalized chroma features of a pianoroll. | [
"Return",
"the",
"unnormalized",
"chroma",
"features",
"of",
"a",
"pianoroll",
"."
] | train | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/metrics.py#L21-L26 |
salu133445/pypianoroll | pypianoroll/metrics.py | empty_beat_rate | 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 | 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... | [
"def",
"empty_beat_rate",
"(",
"pianoroll",
",",
"beat_resolution",
")",
":",
"_validate_pianoroll",
"(",
"pianoroll",
")",
"reshaped",
"=",
"pianoroll",
".",
"reshape",
"(",
"-",
"1",
",",
"beat_resolution",
"*",
"pianoroll",
".",
"shape",
"[",
"1",
"]",
")... | Return the ratio of empty beats to the total number of beats in a
pianoroll. | [
"Return",
"the",
"ratio",
"of",
"empty",
"beats",
"to",
"the",
"total",
"number",
"of",
"beats",
"in",
"a",
"pianoroll",
"."
] | train | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/metrics.py#L28-L34 |
salu133445/pypianoroll | pypianoroll/metrics.py | n_pitche_classes_used | 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 | 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)) | [
"def",
"n_pitche_classes_used",
"(",
"pianoroll",
")",
":",
"_validate_pianoroll",
"(",
"pianoroll",
")",
"chroma",
"=",
"_to_chroma",
"(",
"pianoroll",
")",
"return",
"np",
".",
"count_nonzero",
"(",
"np",
".",
"any",
"(",
"chroma",
",",
"0",
")",
")"
] | Return the number of unique pitch classes used in a pianoroll. | [
"Return",
"the",
"number",
"of",
"unique",
"pitch",
"classes",
"used",
"in",
"a",
"pianoroll",
"."
] | train | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/metrics.py#L41-L45 |
salu133445/pypianoroll | pypianoroll/metrics.py | qualified_note_rate | def qualified_note_rate(pianoroll, threshold=2):
"""Return the ratio of the number of the qualified notes (notes longer than
`threshold` (in time step)) to the total number of notes in a pianoroll."""
_validate_pianoroll(pianoroll)
if np.issubdtype(pianoroll.dtype, np.bool_):
pianoroll = pianoro... | python | def qualified_note_rate(pianoroll, threshold=2):
"""Return the ratio of the number of the qualified notes (notes longer than
`threshold` (in time step)) to the total number of notes in a pianoroll."""
_validate_pianoroll(pianoroll)
if np.issubdtype(pianoroll.dtype, np.bool_):
pianoroll = pianoro... | [
"def",
"qualified_note_rate",
"(",
"pianoroll",
",",
"threshold",
"=",
"2",
")",
":",
"_validate_pianoroll",
"(",
"pianoroll",
")",
"if",
"np",
".",
"issubdtype",
"(",
"pianoroll",
".",
"dtype",
",",
"np",
".",
"bool_",
")",
":",
"pianoroll",
"=",
"pianoro... | Return the ratio of the number of the qualified notes (notes longer than
`threshold` (in time step)) to the total number of notes in a pianoroll. | [
"Return",
"the",
"ratio",
"of",
"the",
"number",
"of",
"the",
"qualified",
"notes",
"(",
"notes",
"longer",
"than",
"threshold",
"(",
"in",
"time",
"step",
"))",
"to",
"the",
"total",
"number",
"of",
"notes",
"in",
"a",
"pianoroll",
"."
] | train | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/metrics.py#L47-L58 |
salu133445/pypianoroll | pypianoroll/metrics.py | polyphonic_rate | 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 | 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... | [
"def",
"polyphonic_rate",
"(",
"pianoroll",
",",
"threshold",
"=",
"2",
")",
":",
"_validate_pianoroll",
"(",
"pianoroll",
")",
"n_poly",
"=",
"np",
".",
"count_nonzero",
"(",
"np",
".",
"count_nonzero",
"(",
"pianoroll",
",",
"1",
")",
">",
"threshold",
"... | 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. | [
"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",
"."
] | train | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/metrics.py#L60-L66 |
salu133445/pypianoroll | pypianoroll/metrics.py | drum_in_pattern_rate | def drum_in_pattern_rate(pianoroll, beat_resolution, tolerance=0.1):
"""Return the ratio of the number of drum notes that lie on the drum
pattern (i.e., at certain time steps) to the total number of drum notes."""
if beat_resolution not in (4, 6, 8, 9, 12, 16, 18, 24):
raise ValueError("Unsupported ... | python | def drum_in_pattern_rate(pianoroll, beat_resolution, tolerance=0.1):
"""Return the ratio of the number of drum notes that lie on the drum
pattern (i.e., at certain time steps) to the total number of drum notes."""
if beat_resolution not in (4, 6, 8, 9, 12, 16, 18, 24):
raise ValueError("Unsupported ... | [
"def",
"drum_in_pattern_rate",
"(",
"pianoroll",
",",
"beat_resolution",
",",
"tolerance",
"=",
"0.1",
")",
":",
"if",
"beat_resolution",
"not",
"in",
"(",
"4",
",",
"6",
",",
"8",
",",
"9",
",",
"12",
",",
"16",
",",
"18",
",",
"24",
")",
":",
"ra... | Return the ratio of the number of drum notes that lie on the drum
pattern (i.e., at certain time steps) to the total number of drum notes. | [
"Return",
"the",
"ratio",
"of",
"the",
"number",
"of",
"drum",
"notes",
"that",
"lie",
"on",
"the",
"drum",
"pattern",
"(",
"i",
".",
"e",
".",
"at",
"certain",
"time",
"steps",
")",
"to",
"the",
"total",
"number",
"of",
"drum",
"notes",
"."
] | train | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/metrics.py#L68-L98 |
salu133445/pypianoroll | pypianoroll/metrics.py | in_scale_rate | 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 | 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... | [
"def",
"in_scale_rate",
"(",
"pianoroll",
",",
"key",
"=",
"3",
",",
"kind",
"=",
"'major'",
")",
":",
"if",
"not",
"isinstance",
"(",
"key",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"\"`key` must an integer.\"",
")",
"if",
"key",
">",
"11",
"o... | 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. | [
"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",
"... | train | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/metrics.py#L100-L123 |
salu133445/pypianoroll | pypianoroll/metrics.py | tonal_distance | def tonal_distance(pianoroll_1, pianoroll_2, beat_resolution, r1=1.0, r2=1.0,
r3=0.5):
"""Return the tonal distance [1] between the two input pianorolls.
[1] Christopher Harte, Mark Sandler, and Martin Gasser. Detecting
harmonic change in musical audio. In Proc. ACM Workshop on Audio... | python | def tonal_distance(pianoroll_1, pianoroll_2, beat_resolution, r1=1.0, r2=1.0,
r3=0.5):
"""Return the tonal distance [1] between the two input pianorolls.
[1] Christopher Harte, Mark Sandler, and Martin Gasser. Detecting
harmonic change in musical audio. In Proc. ACM Workshop on Audio... | [
"def",
"tonal_distance",
"(",
"pianoroll_1",
",",
"pianoroll_2",
",",
"beat_resolution",
",",
"r1",
"=",
"1.0",
",",
"r2",
"=",
"1.0",
",",
"r3",
"=",
"0.5",
")",
":",
"_validate_pianoroll",
"(",
"pianoroll_1",
")",
"_validate_pianoroll",
"(",
"pianoroll_2",
... | Return the tonal distance [1] between the two input pianorolls.
[1] Christopher Harte, Mark Sandler, and Martin Gasser. Detecting
harmonic change in musical audio. In Proc. ACM Workshop on Audio and
Music Computing Multimedia, 2006. | [
"Return",
"the",
"tonal",
"distance",
"[",
"1",
"]",
"between",
"the",
"two",
"input",
"pianorolls",
"."
] | train | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/metrics.py#L125-L160 |
salu133445/pypianoroll | pypianoroll/track.py | Track.assign_constant | 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 | 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
---------
... | [
"def",
"assign_constant",
"(",
"self",
",",
"value",
",",
"dtype",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"is_binarized",
"(",
")",
":",
"self",
".",
"pianoroll",
"[",
"self",
".",
"pianoroll",
".",
"nonzero",
"(",
")",
"]",
"=",
"value",
... | 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
---------
value : int or float
The constant value to be as... | [
"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"... | train | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/track.py#L76-L99 |
salu133445/pypianoroll | pypianoroll/track.py | Track.binarize | 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 | 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 > ... | [
"def",
"binarize",
"(",
"self",
",",
"threshold",
"=",
"0",
")",
":",
"if",
"not",
"self",
".",
"is_binarized",
"(",
")",
":",
"self",
".",
"pianoroll",
"=",
"(",
"self",
".",
"pianoroll",
">",
"threshold",
")"
] | Binarize the pianoroll.
Parameters
----------
threshold : int or float
A threshold used to binarize the pianorolls. Defaults to zero. | [
"Binarize",
"the",
"pianoroll",
"."
] | train | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/track.py#L101-L112 |
salu133445/pypianoroll | pypianoroll/track.py | Track.check_validity | 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 | 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... | [
"def",
"check_validity",
"(",
"self",
")",
":",
"# pianoroll",
"if",
"not",
"isinstance",
"(",
"self",
".",
"pianoroll",
",",
"np",
".",
"ndarray",
")",
":",
"raise",
"TypeError",
"(",
"\"`pianoroll` must be a numpy array.\"",
")",
"if",
"not",
"(",
"np",
".... | Raise error if any invalid attribute found. | [
"Raise",
"error",
"if",
"any",
"invalid",
"attribute",
"found",
"."
] | train | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/track.py#L114-L138 |
salu133445/pypianoroll | pypianoroll/track.py | Track.clip | 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 | 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... | [
"def",
"clip",
"(",
"self",
",",
"lower",
"=",
"0",
",",
"upper",
"=",
"127",
")",
":",
"self",
".",
"pianoroll",
"=",
"self",
".",
"pianoroll",
".",
"clip",
"(",
"lower",
",",
"upper",
")"
] | 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 pianoroll. Defaults to 127. | [
"Clip",
"the",
"pianoroll",
"by",
"the",
"given",
"lower",
"and",
"upper",
"bounds",
"."
] | train | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/track.py#L140-L152 |
salu133445/pypianoroll | pypianoroll/track.py | Track.get_active_length | def get_active_length(self):
"""
Return the active length (i.e., without trailing silence) of the
pianoroll. The unit is time step.
Returns
-------
active_length : int
The active length (i.e., without trailing silence) of the pianoroll.
"""
n... | python | def get_active_length(self):
"""
Return the active length (i.e., without trailing silence) of the
pianoroll. The unit is time step.
Returns
-------
active_length : int
The active length (i.e., without trailing silence) of the pianoroll.
"""
n... | [
"def",
"get_active_length",
"(",
"self",
")",
":",
"nonzero_steps",
"=",
"np",
".",
"any",
"(",
"self",
".",
"pianoroll",
",",
"axis",
"=",
"1",
")",
"inv_last_nonzero_step",
"=",
"np",
".",
"argmax",
"(",
"np",
".",
"flip",
"(",
"nonzero_steps",
",",
... | Return the active length (i.e., without trailing silence) of the
pianoroll. The unit is time step.
Returns
-------
active_length : int
The active length (i.e., without trailing silence) of the pianoroll. | [
"Return",
"the",
"active",
"length",
"(",
"i",
".",
"e",
".",
"without",
"trailing",
"silence",
")",
"of",
"the",
"pianoroll",
".",
"The",
"unit",
"is",
"time",
"step",
"."
] | train | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/track.py#L167-L181 |
salu133445/pypianoroll | pypianoroll/track.py | Track.get_active_pitch_range | def get_active_pitch_range(self):
"""
Return the active pitch range as a tuple (lowest, highest).
Returns
-------
lowest : int
The lowest active pitch in the pianoroll.
highest : int
The highest active pitch in the pianoroll.
"""
... | python | def get_active_pitch_range(self):
"""
Return the active pitch range as a tuple (lowest, highest).
Returns
-------
lowest : int
The lowest active pitch in the pianoroll.
highest : int
The highest active pitch in the pianoroll.
"""
... | [
"def",
"get_active_pitch_range",
"(",
"self",
")",
":",
"if",
"self",
".",
"pianoroll",
".",
"shape",
"[",
"1",
"]",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"\"Cannot compute the active pitch range for an \"",
"\"empty pianoroll\"",
")",
"lowest",
"=",
"0",
"... | Return the active pitch range as a tuple (lowest, highest).
Returns
-------
lowest : int
The lowest active pitch in the pianoroll.
highest : int
The highest active pitch in the pianoroll. | [
"Return",
"the",
"active",
"pitch",
"range",
"as",
"a",
"tuple",
"(",
"lowest",
"highest",
")",
"."
] | train | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/track.py#L183-L210 |
salu133445/pypianoroll | pypianoroll/track.py | Track.is_binarized | 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 | 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... | [
"def",
"is_binarized",
"(",
"self",
")",
":",
"is_binarized",
"=",
"np",
".",
"issubdtype",
"(",
"self",
".",
"pianoroll",
".",
"dtype",
",",
"np",
".",
"bool_",
")",
"return",
"is_binarized"
] | Return True if the pianoroll is already binarized. Otherwise, return
False.
Returns
-------
is_binarized : bool
True if the pianoroll is already binarized; otherwise, False. | [
"Return",
"True",
"if",
"the",
"pianoroll",
"is",
"already",
"binarized",
".",
"Otherwise",
"return",
"False",
"."
] | train | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/track.py#L225-L237 |
salu133445/pypianoroll | pypianoroll/track.py | Track.pad | 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 | 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... | [
"def",
"pad",
"(",
"self",
",",
"pad_length",
")",
":",
"self",
".",
"pianoroll",
"=",
"np",
".",
"pad",
"(",
"self",
".",
"pianoroll",
",",
"(",
"(",
"0",
",",
"pad_length",
")",
",",
"(",
"0",
",",
"0",
")",
")",
",",
"'constant'",
")"
] | 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. | [
"Pad",
"the",
"pianoroll",
"with",
"zeros",
"at",
"the",
"end",
"along",
"the",
"time",
"axis",
"."
] | train | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/track.py#L239-L250 |
salu133445/pypianoroll | pypianoroll/track.py | Track.pad_to_multiple | 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 | 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 ... | [
"def",
"pad_to_multiple",
"(",
"self",
",",
"factor",
")",
":",
"remainder",
"=",
"self",
".",
"pianoroll",
".",
"shape",
"[",
"0",
"]",
"%",
"factor",
"if",
"remainder",
":",
"pad_width",
"=",
"(",
"(",
"0",
",",
"(",
"factor",
"-",
"remainder",
")"... | 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 of the resulting pianoroll will be
a multip... | [
"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",
"."
] | train | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/track.py#L252-L268 |
salu133445/pypianoroll | pypianoroll/track.py | Track.transpose | 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 | 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.
... | [
"def",
"transpose",
"(",
"self",
",",
"semitone",
")",
":",
"if",
"semitone",
">",
"0",
"and",
"semitone",
"<",
"128",
":",
"self",
".",
"pianoroll",
"[",
":",
",",
"semitone",
":",
"]",
"=",
"self",
".",
"pianoroll",
"[",
":",
",",
":",
"(",
"12... | 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. | [
"Transpose",
"the",
"pianoroll",
"by",
"a",
"number",
"of",
"semitones",
"where",
"positive",
"values",
"are",
"for",
"higher",
"key",
"while",
"negative",
"values",
"are",
"for",
"lower",
"key",
"."
] | train | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/track.py#L275-L291 |
salu133445/pypianoroll | pypianoroll/track.py | Track.trim_trailing_silence | def trim_trailing_silence(self):
"""Trim the trailing silence of the pianoroll."""
length = self.get_active_length()
self.pianoroll = self.pianoroll[:length] | python | def trim_trailing_silence(self):
"""Trim the trailing silence of the pianoroll."""
length = self.get_active_length()
self.pianoroll = self.pianoroll[:length] | [
"def",
"trim_trailing_silence",
"(",
"self",
")",
":",
"length",
"=",
"self",
".",
"get_active_length",
"(",
")",
"self",
".",
"pianoroll",
"=",
"self",
".",
"pianoroll",
"[",
":",
"length",
"]"
] | Trim the trailing silence of the pianoroll. | [
"Trim",
"the",
"trailing",
"silence",
"of",
"the",
"pianoroll",
"."
] | train | https://github.com/salu133445/pypianoroll/blob/6224dc1e29222de2124d249acb80f3d072166917/pypianoroll/track.py#L293-L296 |
dnouri/nolearn | nolearn/lasagne/visualize.py | plot_conv_weights | 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 | 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)
... | [
"def",
"plot_conv_weights",
"(",
"layer",
",",
"figsize",
"=",
"(",
"6",
",",
"6",
")",
")",
":",
"W",
"=",
"layer",
".",
"W",
".",
"get_value",
"(",
")",
"shape",
"=",
"W",
".",
"shape",
"nrows",
"=",
"np",
".",
"ceil",
"(",
"np",
".",
"sqrt",... | Plot the weights of a specific layer.
Only really makes sense with convolutional layers.
Parameters
----------
layer : lasagne.layers.Layer | [
"Plot",
"the",
"weights",
"of",
"a",
"specific",
"layer",
"."
] | train | https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/visualize.py#L26-L54 |
dnouri/nolearn | nolearn/lasagne/visualize.py | plot_conv_activity | 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 | 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 ... | [
"def",
"plot_conv_activity",
"(",
"layer",
",",
"x",
",",
"figsize",
"=",
"(",
"6",
",",
"8",
")",
")",
":",
"if",
"x",
".",
"shape",
"[",
"0",
"]",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"\"Only one sample can be plotted at a time.\"",
")",
"# comp... | 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 sample at a time, i.e. x.shape[0] == 1. | [
"Plot",
"the",
"acitivities",
"of",
"a",
"specific",
"layer",
"."
] | train | https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/visualize.py#L57-L102 |
dnouri/nolearn | nolearn/lasagne/visualize.py | occlusion_heatmap | 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 | 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... | [
"def",
"occlusion_heatmap",
"(",
"net",
",",
"x",
",",
"target",
",",
"square_length",
"=",
"7",
")",
":",
"if",
"(",
"x",
".",
"ndim",
"!=",
"4",
")",
"or",
"x",
".",
"shape",
"[",
"0",
"]",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"\"This fu... | 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 propensity shrinks of
critical parts of the image are occluded.... | [
"An",
"occlusion",
"test",
"that",
"checks",
"an",
"image",
"for",
"its",
"critical",
"parts",
"."
] | train | https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/visualize.py#L105-L180 |
dnouri/nolearn | nolearn/lasagne/visualize.py | plot_occlusion | 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 | 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... | [
"def",
"plot_occlusion",
"(",
"net",
",",
"X",
",",
"target",
",",
"square_length",
"=",
"7",
",",
"figsize",
"=",
"(",
"9",
",",
"None",
")",
")",
":",
"return",
"_plot_heat_map",
"(",
"net",
",",
"X",
",",
"figsize",
",",
"lambda",
"net",
",",
"X... | 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 : numpy.array
The input data, should be of shape (b, c, 0, 1). Only makes
... | [
"Plot",
"which",
"parts",
"of",
"an",
"image",
"are",
"particularly",
"import",
"for",
"the",
"net",
"to",
"classify",
"the",
"image",
"correctly",
"."
] | train | https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/visualize.py#L214-L250 |
dnouri/nolearn | nolearn/lasagne/visualize.py | get_hex_color | def get_hex_color(layer_type):
"""
Determines the hex color for a layer.
:parameters:
- layer_type : string
Class name of the layer
:returns:
- color : string containing a hex color for filling block.
"""
COLORS = ['#4A88B3', '#98C1DE', '#6CA2C8', '#3173A2', '#17649B'... | python | def get_hex_color(layer_type):
"""
Determines the hex color for a layer.
:parameters:
- layer_type : string
Class name of the layer
:returns:
- color : string containing a hex color for filling block.
"""
COLORS = ['#4A88B3', '#98C1DE', '#6CA2C8', '#3173A2', '#17649B'... | [
"def",
"get_hex_color",
"(",
"layer_type",
")",
":",
"COLORS",
"=",
"[",
"'#4A88B3'",
",",
"'#98C1DE'",
",",
"'#6CA2C8'",
",",
"'#3173A2'",
",",
"'#17649B'",
",",
"'#FFBB60'",
",",
"'#FFDAA9'",
",",
"'#FFC981'",
",",
"'#FCAC41'",
",",
"'#F29416'",
",",
"'#C5... | Determines the hex color for a layer.
:parameters:
- layer_type : string
Class name of the layer
:returns:
- color : string containing a hex color for filling block. | [
"Determines",
"the",
"hex",
"color",
"for",
"a",
"layer",
".",
":",
"parameters",
":",
"-",
"layer_type",
":",
"string",
"Class",
"name",
"of",
"the",
"layer",
":",
"returns",
":",
"-",
"color",
":",
"string",
"containing",
"a",
"hex",
"color",
"for",
... | train | https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/visualize.py#L270-L293 |
dnouri/nolearn | nolearn/lasagne/visualize.py | make_pydot_graph | def make_pydot_graph(layers, output_shape=True, verbose=False):
"""
:parameters:
- layers : list
List of the layers, as obtained from lasagne.layers.get_all_layers
- output_shape: (default `True`)
If `True`, the output shape of each layer will be displayed.
- verb... | python | def make_pydot_graph(layers, output_shape=True, verbose=False):
"""
:parameters:
- layers : list
List of the layers, as obtained from lasagne.layers.get_all_layers
- output_shape: (default `True`)
If `True`, the output shape of each layer will be displayed.
- verb... | [
"def",
"make_pydot_graph",
"(",
"layers",
",",
"output_shape",
"=",
"True",
",",
"verbose",
"=",
"False",
")",
":",
"import",
"pydotplus",
"as",
"pydot",
"pydot_graph",
"=",
"pydot",
".",
"Dot",
"(",
"'Network'",
",",
"graph_type",
"=",
"'digraph'",
")",
"... | :parameters:
- layers : list
List of the layers, as obtained from lasagne.layers.get_all_layers
- output_shape: (default `True`)
If `True`, the output shape of each layer will be displayed.
- verbose: (default `False`)
If `True`, layer attributes like filter s... | [
":",
"parameters",
":",
"-",
"layers",
":",
"list",
"List",
"of",
"the",
"layers",
"as",
"obtained",
"from",
"lasagne",
".",
"layers",
".",
"get_all_layers",
"-",
"output_shape",
":",
"(",
"default",
"True",
")",
"If",
"True",
"the",
"output",
"shape",
"... | train | https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/visualize.py#L296-L352 |
dnouri/nolearn | nolearn/lasagne/visualize.py | draw_to_file | def draw_to_file(layers, filename, **kwargs):
"""
Draws a network diagram to a file
:parameters:
- layers : list or NeuralNet instance
List of layers or the neural net to draw.
- filename : string
The filename to save output to
- **kwargs: see docstring of mak... | python | def draw_to_file(layers, filename, **kwargs):
"""
Draws a network diagram to a file
:parameters:
- layers : list or NeuralNet instance
List of layers or the neural net to draw.
- filename : string
The filename to save output to
- **kwargs: see docstring of mak... | [
"def",
"draw_to_file",
"(",
"layers",
",",
"filename",
",",
"*",
"*",
"kwargs",
")",
":",
"layers",
"=",
"(",
"layers",
".",
"get_all_layers",
"(",
")",
"if",
"hasattr",
"(",
"layers",
",",
"'get_all_layers'",
")",
"else",
"layers",
")",
"dot",
"=",
"m... | Draws a network diagram to a file
:parameters:
- layers : list or NeuralNet instance
List of layers or the neural net to draw.
- filename : string
The filename to save output to
- **kwargs: see docstring of make_pydot_graph for other options | [
"Draws",
"a",
"network",
"diagram",
"to",
"a",
"file",
":",
"parameters",
":",
"-",
"layers",
":",
"list",
"or",
"NeuralNet",
"instance",
"List",
"of",
"layers",
"or",
"the",
"neural",
"net",
"to",
"draw",
".",
"-",
"filename",
":",
"string",
"The",
"f... | train | https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/visualize.py#L355-L370 |
dnouri/nolearn | nolearn/lasagne/visualize.py | draw_to_notebook | def draw_to_notebook(layers, **kwargs):
"""
Draws a network diagram in an IPython notebook
:parameters:
- layers : list or NeuralNet instance
List of layers or the neural net to draw.
- **kwargs : see the docstring of make_pydot_graph for other options
"""
from IPython.di... | python | def draw_to_notebook(layers, **kwargs):
"""
Draws a network diagram in an IPython notebook
:parameters:
- layers : list or NeuralNet instance
List of layers or the neural net to draw.
- **kwargs : see the docstring of make_pydot_graph for other options
"""
from IPython.di... | [
"def",
"draw_to_notebook",
"(",
"layers",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"IPython",
".",
"display",
"import",
"Image",
"layers",
"=",
"(",
"layers",
".",
"get_all_layers",
"(",
")",
"if",
"hasattr",
"(",
"layers",
",",
"'get_all_layers'",
")",
... | Draws a network diagram in an IPython notebook
:parameters:
- layers : list or NeuralNet instance
List of layers or the neural net to draw.
- **kwargs : see the docstring of make_pydot_graph for other options | [
"Draws",
"a",
"network",
"diagram",
"in",
"an",
"IPython",
"notebook",
":",
"parameters",
":",
"-",
"layers",
":",
"list",
"or",
"NeuralNet",
"instance",
"List",
"of",
"layers",
"or",
"the",
"neural",
"net",
"to",
"draw",
".",
"-",
"**",
"kwargs",
":",
... | train | https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/visualize.py#L373-L385 |
dnouri/nolearn | nolearn/lasagne/util.py | get_real_filter | def get_real_filter(layers, img_size):
"""Get the real filter sizes of each layer involved in
convoluation. See Xudong Cao:
https://www.kaggle.com/c/datasciencebowl/forums/t/13166/happy-lantern-festival-report-and-code
This does not yet take into consideration feature pooling,
padding, striding and ... | python | def get_real_filter(layers, img_size):
"""Get the real filter sizes of each layer involved in
convoluation. See Xudong Cao:
https://www.kaggle.com/c/datasciencebowl/forums/t/13166/happy-lantern-festival-report-and-code
This does not yet take into consideration feature pooling,
padding, striding and ... | [
"def",
"get_real_filter",
"(",
"layers",
",",
"img_size",
")",
":",
"real_filter",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"layers",
")",
",",
"2",
")",
")",
"conv_mode",
"=",
"True",
"first_conv_layer",
"=",
"True",
"expon",
"=",
"np",
".",
"... | Get the real filter sizes of each layer involved in
convoluation. See Xudong Cao:
https://www.kaggle.com/c/datasciencebowl/forums/t/13166/happy-lantern-festival-report-and-code
This does not yet take into consideration feature pooling,
padding, striding and similar gimmicks. | [
"Get",
"the",
"real",
"filter",
"sizes",
"of",
"each",
"layer",
"involved",
"in",
"convoluation",
".",
"See",
"Xudong",
"Cao",
":",
"https",
":",
"//",
"www",
".",
"kaggle",
".",
"com",
"/",
"c",
"/",
"datasciencebowl",
"/",
"forums",
"/",
"t",
"/",
... | train | https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/util.py#L57-L91 |
dnouri/nolearn | nolearn/lasagne/util.py | get_receptive_field | def get_receptive_field(layers, img_size):
"""Get the real filter sizes of each layer involved in
convoluation. See Xudong Cao:
https://www.kaggle.com/c/datasciencebowl/forums/t/13166/happy-lantern-festival-report-and-code
This does not yet take into consideration feature pooling,
padding, striding ... | python | def get_receptive_field(layers, img_size):
"""Get the real filter sizes of each layer involved in
convoluation. See Xudong Cao:
https://www.kaggle.com/c/datasciencebowl/forums/t/13166/happy-lantern-festival-report-and-code
This does not yet take into consideration feature pooling,
padding, striding ... | [
"def",
"get_receptive_field",
"(",
"layers",
",",
"img_size",
")",
":",
"receptive_field",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"layers",
")",
",",
"2",
")",
")",
"conv_mode",
"=",
"True",
"first_conv_layer",
"=",
"True",
"expon",
"=",
"np",
... | Get the real filter sizes of each layer involved in
convoluation. See Xudong Cao:
https://www.kaggle.com/c/datasciencebowl/forums/t/13166/happy-lantern-festival-report-and-code
This does not yet take into consideration feature pooling,
padding, striding and similar gimmicks. | [
"Get",
"the",
"real",
"filter",
"sizes",
"of",
"each",
"layer",
"involved",
"in",
"convoluation",
".",
"See",
"Xudong",
"Cao",
":",
"https",
":",
"//",
"www",
".",
"kaggle",
".",
"com",
"/",
"c",
"/",
"datasciencebowl",
"/",
"forums",
"/",
"t",
"/",
... | train | https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/util.py#L94-L129 |
dnouri/nolearn | nolearn/decaf.py | ConvNetFeatures.prepare_image | def prepare_image(self, image):
"""Returns image of shape `(256, 256, 3)`, as expected by
`transform` when `classify_direct = True`.
"""
from decaf.util import transform # soft dep
_JEFFNET_FLIP = True
# first, extract the 256x256 center.
image = transform.scale... | python | def prepare_image(self, image):
"""Returns image of shape `(256, 256, 3)`, as expected by
`transform` when `classify_direct = True`.
"""
from decaf.util import transform # soft dep
_JEFFNET_FLIP = True
# first, extract the 256x256 center.
image = transform.scale... | [
"def",
"prepare_image",
"(",
"self",
",",
"image",
")",
":",
"from",
"decaf",
".",
"util",
"import",
"transform",
"# soft dep",
"_JEFFNET_FLIP",
"=",
"True",
"# first, extract the 256x256 center.",
"image",
"=",
"transform",
".",
"scale_and_extract",
"(",
"transform... | Returns image of shape `(256, 256, 3)`, as expected by
`transform` when `classify_direct = True`. | [
"Returns",
"image",
"of",
"shape",
"(",
"256",
"256",
"3",
")",
"as",
"expected",
"by",
"transform",
"when",
"classify_direct",
"=",
"True",
"."
] | train | https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/decaf.py#L138-L154 |
dnouri/nolearn | nolearn/metrics.py | multiclass_logloss | 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 | 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:... | [
"def",
"multiclass_logloss",
"(",
"actual",
",",
"predicted",
",",
"eps",
"=",
"1e-15",
")",
":",
"# Convert 'actual' to a binary array if it's not already:",
"if",
"len",
"(",
"actual",
".",
"shape",
")",
"==",
"1",
":",
"actual2",
"=",
"np",
".",
"zeros",
"(... | 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 | [
"Multi",
"class",
"version",
"of",
"Logarithmic",
"Loss",
"metric",
"."
] | train | https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/metrics.py#L8-L24 |
dnouri/nolearn | nolearn/lasagne/base.py | objective | 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 | 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... | [
"def",
"objective",
"(",
"layers",
",",
"loss_function",
",",
"target",
",",
"aggregate",
"=",
"aggregate",
",",
"deterministic",
"=",
"False",
",",
"l1",
"=",
"0",
",",
"l2",
"=",
"0",
",",
"get_output_kw",
"=",
"None",
")",
":",
"if",
"get_output_kw",
... | Default implementation of the NeuralNet objective.
:param layers: The underlying layers of the NeuralNetwork
:param loss_function: The callable loss function to use
:param target: the expected output
:param aggregate: the aggregation function to use
:param deterministic: Whether or not to get a de... | [
"Default",
"implementation",
"of",
"the",
"NeuralNet",
"objective",
"."
] | train | https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/base.py#L166-L202 |
dnouri/nolearn | nolearn/lasagne/base.py | NeuralNet.initialize | 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 | 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'... | [
"def",
"initialize",
"(",
"self",
")",
":",
"if",
"getattr",
"(",
"self",
",",
"'_initialized'",
",",
"False",
")",
":",
"return",
"out",
"=",
"getattr",
"(",
"self",
",",
"'_output_layers'",
",",
"None",
")",
"if",
"out",
"is",
"None",
":",
"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. | [
"Initializes",
"the",
"network",
".",
"Checks",
"that",
"no",
"extra",
"kwargs",
"were",
"passed",
"to",
"the",
"constructor",
"and",
"compiles",
"the",
"train",
"predict",
"and",
"evaluation",
"functions",
"."
] | train | https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/base.py#L473-L493 |
dnouri/nolearn | nolearn/lasagne/base.py | NeuralNet.initialize_layers | def initialize_layers(self, layers=None):
"""Sets up the Lasagne layers
:param layers: The dictionary of layers, or a
:class:`lasagne.Layers` instance, describing the underlying
network
:return: the output layer of the underlying lasagne network.
:seealso: :ref:`layer-... | python | def initialize_layers(self, layers=None):
"""Sets up the Lasagne layers
:param layers: The dictionary of layers, or a
:class:`lasagne.Layers` instance, describing the underlying
network
:return: the output layer of the underlying lasagne network.
:seealso: :ref:`layer-... | [
"def",
"initialize_layers",
"(",
"self",
",",
"layers",
"=",
"None",
")",
":",
"if",
"layers",
"is",
"not",
"None",
":",
"self",
".",
"layers",
"=",
"layers",
"self",
".",
"layers_",
"=",
"Layers",
"(",
")",
"#If a Layer, or a list of Layers was passed in",
... | Sets up the Lasagne layers
:param layers: The dictionary of layers, or a
:class:`lasagne.Layers` instance, describing the underlying
network
:return: the output layer of the underlying lasagne network.
:seealso: :ref:`layer-def` | [
"Sets",
"up",
"the",
"Lasagne",
"layers"
] | train | https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/base.py#L512-L616 |
dnouri/nolearn | nolearn/lasagne/base.py | NeuralNet.fit | 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 | 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:... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
",",
"epochs",
"=",
"None",
")",
":",
"if",
"self",
".",
"check_input",
":",
"X",
",",
"y",
"=",
"self",
".",
"_check_good_input",
"(",
"X",
",",
"y",
")",
"if",
"self",
".",
"use_label_encoder",
":"... | 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: This instance | [
"Runs",
"the",
"training",
"loop",
"for",
"a",
"given",
"number",
"of",
"epochs"
] | train | https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/base.py#L680-L703 |
dnouri/nolearn | nolearn/lasagne/base.py | NeuralNet.partial_fit | 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 | 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) | [
"def",
"partial_fit",
"(",
"self",
",",
"X",
",",
"y",
",",
"classes",
"=",
"None",
")",
":",
"return",
"self",
".",
"fit",
"(",
"X",
",",
"y",
",",
"epochs",
"=",
"1",
")"
] | Runs a single epoch using the provided data
:return: This instance | [
"Runs",
"a",
"single",
"epoch",
"using",
"the",
"provided",
"data"
] | train | https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/base.py#L705-L711 |
pennersr/django-trackstats | trackstats/models.py | RegisterLazilyManagerMixin._register | def _register(self, defaults=None, **kwargs):
"""Fetch (update or create) an instance, lazily.
We're doing this lazily, so that it becomes possible to define
custom enums in your code, even before the Django ORM is fully
initialized.
Domain.objects.SHOPPING = Domain.objects.re... | python | def _register(self, defaults=None, **kwargs):
"""Fetch (update or create) an instance, lazily.
We're doing this lazily, so that it becomes possible to define
custom enums in your code, even before the Django ORM is fully
initialized.
Domain.objects.SHOPPING = Domain.objects.re... | [
"def",
"_register",
"(",
"self",
",",
"defaults",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"f",
"=",
"lambda",
":",
"self",
".",
"update_or_create",
"(",
"defaults",
"=",
"defaults",
",",
"*",
"*",
"kwargs",
")",
"[",
"0",
"]",
"ret",
"=",
... | Fetch (update or create) an instance, lazily.
We're doing this lazily, so that it becomes possible to define
custom enums in your code, even before the Django ORM is fully
initialized.
Domain.objects.SHOPPING = Domain.objects.register(
ref='shopping',
name='Web... | [
"Fetch",
"(",
"update",
"or",
"create",
")",
"an",
"instance",
"lazily",
"."
] | train | https://github.com/pennersr/django-trackstats/blob/4c36e769cb02017675a86de405afcd4e10ed3356/trackstats/models.py#L28-L45 |
pennersr/django-trackstats | trackstats/models.py | ByDateQuerySetMixin.narrow | 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 | 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... | [
"def",
"narrow",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"from_date",
"=",
"kwargs",
".",
"pop",
"(",
"'from_date'",
",",
"None",
")",
"to_date",
"=",
"kwargs",
".",
"pop",
"(",
"'to_date'",
",",
"None",
")",
"date",
"=",
"kwargs",
".",
"po... | Up-to including | [
"Up",
"-",
"to",
"including"
] | train | https://github.com/pennersr/django-trackstats/blob/4c36e769cb02017675a86de405afcd4e10ed3356/trackstats/models.py#L230-L242 |
HDE/python-lambda-local | lambda_local/environment_variables.py | set_environment_variables | 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 | 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:
```
... | [
"def",
"set_environment_variables",
"(",
"json_file_path",
")",
":",
"if",
"json_file_path",
":",
"with",
"open",
"(",
"json_file_path",
")",
"as",
"json_file",
":",
"env_vars",
"=",
"json",
".",
"loads",
"(",
"json_file",
".",
"read",
"(",
")",
")",
"export... | 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:
```
{
"FOO": "bar",
"BAZ": true
}
``... | [
"Read",
"and",
"set",
"environment",
"variables",
"from",
"a",
"flat",
"json",
"file",
"."
] | train | https://github.com/HDE/python-lambda-local/blob/49ad011a039974f1d8f904435eb8db895558d2d9/lambda_local/environment_variables.py#L10-L33 |
HDE/python-lambda-local | lambda_local/context.py | millis_interval | 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 | 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 | [
"def",
"millis_interval",
"(",
"start",
",",
"end",
")",
":",
"diff",
"=",
"end",
"-",
"start",
"millis",
"=",
"diff",
".",
"days",
"*",
"24",
"*",
"60",
"*",
"60",
"*",
"1000",
"millis",
"+=",
"diff",
".",
"seconds",
"*",
"1000",
"millis",
"+=",
... | start and end are datetime instances | [
"start",
"and",
"end",
"are",
"datetime",
"instances"
] | train | https://github.com/HDE/python-lambda-local/blob/49ad011a039974f1d8f904435eb8db895558d2d9/lambda_local/context.py#L49-L55 |
locationlabs/mockredis | mockredis/script.py | Script._execute_lua | def _execute_lua(self, keys, args, client):
"""
Sets KEYS and ARGV alongwith redis.call() function in lua globals
and executes the lua redis script
"""
lua, lua_globals = Script._import_lua(self.load_dependencies)
lua_globals.KEYS = self._python_to_lua(keys)
lua_g... | python | def _execute_lua(self, keys, args, client):
"""
Sets KEYS and ARGV alongwith redis.call() function in lua globals
and executes the lua redis script
"""
lua, lua_globals = Script._import_lua(self.load_dependencies)
lua_globals.KEYS = self._python_to_lua(keys)
lua_g... | [
"def",
"_execute_lua",
"(",
"self",
",",
"keys",
",",
"args",
",",
"client",
")",
":",
"lua",
",",
"lua_globals",
"=",
"Script",
".",
"_import_lua",
"(",
"self",
".",
"load_dependencies",
")",
"lua_globals",
".",
"KEYS",
"=",
"self",
".",
"_python_to_lua",... | Sets KEYS and ARGV alongwith redis.call() function in lua globals
and executes the lua redis script | [
"Sets",
"KEYS",
"and",
"ARGV",
"alongwith",
"redis",
".",
"call",
"()",
"function",
"in",
"lua",
"globals",
"and",
"executes",
"the",
"lua",
"redis",
"script"
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/script.py#L29-L51 |
locationlabs/mockredis | mockredis/script.py | Script._import_lua | 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 | 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... | [
"def",
"_import_lua",
"(",
"load_dependencies",
"=",
"True",
")",
":",
"try",
":",
"import",
"lua",
"except",
"ImportError",
":",
"raise",
"RuntimeError",
"(",
"\"Lua not installed\"",
")",
"lua_globals",
"=",
"lua",
".",
"globals",
"(",
")",
"if",
"load_depen... | Import lua and dependencies.
:param load_dependencies: should Lua library dependencies be loaded?
:raises: RuntimeError if Lua is not available | [
"Import",
"lua",
"and",
"dependencies",
"."
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/script.py#L54-L69 |
locationlabs/mockredis | mockredis/script.py | Script._import_lua_dependencies | 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 | 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 ... | [
"def",
"_import_lua_dependencies",
"(",
"lua",
",",
"lua_globals",
")",
":",
"if",
"sys",
".",
"platform",
"not",
"in",
"(",
"'darwin'",
",",
"'windows'",
")",
":",
"import",
"ctypes",
"ctypes",
".",
"CDLL",
"(",
"'liblua5.2.so'",
",",
"mode",
"=",
"ctypes... | 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 lib.
Pending:
- base lib.
- table li... | [
"Imports",
"lua",
"dependencies",
"that",
"are",
"supported",
"by",
"redis",
"lua",
"scripts",
"."
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/script.py#L72-L96 |
locationlabs/mockredis | mockredis/script.py | Script._lua_to_python | def _lua_to_python(lval, return_status=False):
"""
Convert Lua object(s) into Python object(s), as at times Lua object(s)
are not compatible with Python functions
"""
import lua
lua_globals = lua.globals()
if lval is None:
# Lua None --> Python None
... | python | def _lua_to_python(lval, return_status=False):
"""
Convert Lua object(s) into Python object(s), as at times Lua object(s)
are not compatible with Python functions
"""
import lua
lua_globals = lua.globals()
if lval is None:
# Lua None --> Python None
... | [
"def",
"_lua_to_python",
"(",
"lval",
",",
"return_status",
"=",
"False",
")",
":",
"import",
"lua",
"lua_globals",
"=",
"lua",
".",
"globals",
"(",
")",
"if",
"lval",
"is",
"None",
":",
"# Lua None --> Python None",
"return",
"None",
"if",
"lua_globals",
".... | Convert Lua object(s) into Python object(s), as at times Lua object(s)
are not compatible with Python functions | [
"Convert",
"Lua",
"object",
"(",
"s",
")",
"into",
"Python",
"object",
"(",
"s",
")",
"as",
"at",
"times",
"Lua",
"object",
"(",
"s",
")",
"are",
"not",
"compatible",
"with",
"Python",
"functions"
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/script.py#L99-L135 |
locationlabs/mockredis | mockredis/script.py | Script._python_to_lua | def _python_to_lua(pval):
"""
Convert Python object(s) into Lua object(s), as at times Python object(s)
are not compatible with Lua functions
"""
import lua
if pval is None:
# Python None --> Lua None
return lua.eval("")
if isinstance(pval,... | python | def _python_to_lua(pval):
"""
Convert Python object(s) into Lua object(s), as at times Python object(s)
are not compatible with Lua functions
"""
import lua
if pval is None:
# Python None --> Lua None
return lua.eval("")
if isinstance(pval,... | [
"def",
"_python_to_lua",
"(",
"pval",
")",
":",
"import",
"lua",
"if",
"pval",
"is",
"None",
":",
"# Python None --> Lua None",
"return",
"lua",
".",
"eval",
"(",
"\"\"",
")",
"if",
"isinstance",
"(",
"pval",
",",
"(",
"list",
",",
"tuple",
",",
"set",
... | Convert Python object(s) into Lua object(s), as at times Python object(s)
are not compatible with Lua functions | [
"Convert",
"Python",
"object",
"(",
"s",
")",
"into",
"Lua",
"object",
"(",
"s",
")",
"as",
"at",
"times",
"Python",
"object",
"(",
"s",
")",
"are",
"not",
"compatible",
"with",
"Lua",
"functions"
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/script.py#L138-L179 |
locationlabs/mockredis | mockredis/client.py | MockRedis.lock | def lock(self, key, timeout=0, sleep=0):
"""Emulate lock."""
return MockRedisLock(self, key, timeout, sleep) | python | def lock(self, key, timeout=0, sleep=0):
"""Emulate lock."""
return MockRedisLock(self, key, timeout, sleep) | [
"def",
"lock",
"(",
"self",
",",
"key",
",",
"timeout",
"=",
"0",
",",
"sleep",
"=",
"0",
")",
":",
"return",
"MockRedisLock",
"(",
"self",
",",
"key",
",",
"timeout",
",",
"sleep",
")"
] | Emulate lock. | [
"Emulate",
"lock",
"."
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L77-L79 |
locationlabs/mockredis | mockredis/client.py | MockRedis.keys | 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 | 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... | [
"def",
"keys",
"(",
"self",
",",
"pattern",
"=",
"'*'",
")",
":",
"# 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 ... | Emulate keys. | [
"Emulate",
"keys",
"."
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L154-L169 |
locationlabs/mockredis | mockredis/client.py | MockRedis.delete | 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 | 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... | [
"def",
"delete",
"(",
"self",
",",
"*",
"keys",
")",
":",
"key_counter",
"=",
"0",
"for",
"key",
"in",
"map",
"(",
"self",
".",
"_encode",
",",
"keys",
")",
":",
"if",
"key",
"in",
"self",
".",
"redis",
":",
"del",
"self",
".",
"redis",
"[",
"k... | Emulate delete. | [
"Emulate",
"delete",
"."
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L171-L180 |
locationlabs/mockredis | mockredis/client.py | MockRedis.expire | def expire(self, key, delta):
"""Emulate expire"""
delta = delta if isinstance(delta, timedelta) else timedelta(seconds=delta)
return self._expire(self._encode(key), delta) | python | def expire(self, key, delta):
"""Emulate expire"""
delta = delta if isinstance(delta, timedelta) else timedelta(seconds=delta)
return self._expire(self._encode(key), delta) | [
"def",
"expire",
"(",
"self",
",",
"key",
",",
"delta",
")",
":",
"delta",
"=",
"delta",
"if",
"isinstance",
"(",
"delta",
",",
"timedelta",
")",
"else",
"timedelta",
"(",
"seconds",
"=",
"delta",
")",
"return",
"self",
".",
"_expire",
"(",
"self",
"... | Emulate expire | [
"Emulate",
"expire"
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L199-L202 |
locationlabs/mockredis | mockredis/client.py | MockRedis.pexpire | def pexpire(self, key, milliseconds):
"""Emulate pexpire"""
return self._expire(self._encode(key), timedelta(milliseconds=milliseconds)) | python | def pexpire(self, key, milliseconds):
"""Emulate pexpire"""
return self._expire(self._encode(key), timedelta(milliseconds=milliseconds)) | [
"def",
"pexpire",
"(",
"self",
",",
"key",
",",
"milliseconds",
")",
":",
"return",
"self",
".",
"_expire",
"(",
"self",
".",
"_encode",
"(",
"key",
")",
",",
"timedelta",
"(",
"milliseconds",
"=",
"milliseconds",
")",
")"
] | Emulate pexpire | [
"Emulate",
"pexpire"
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L204-L206 |
locationlabs/mockredis | mockredis/client.py | MockRedis.expireat | def expireat(self, key, when):
"""Emulate expireat"""
expire_time = datetime.fromtimestamp(when)
key = self._encode(key)
if key in self.redis:
self.timeouts[key] = expire_time
return True
return False | python | def expireat(self, key, when):
"""Emulate expireat"""
expire_time = datetime.fromtimestamp(when)
key = self._encode(key)
if key in self.redis:
self.timeouts[key] = expire_time
return True
return False | [
"def",
"expireat",
"(",
"self",
",",
"key",
",",
"when",
")",
":",
"expire_time",
"=",
"datetime",
".",
"fromtimestamp",
"(",
"when",
")",
"key",
"=",
"self",
".",
"_encode",
"(",
"key",
")",
"if",
"key",
"in",
"self",
".",
"redis",
":",
"self",
".... | Emulate expireat | [
"Emulate",
"expireat"
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L208-L215 |
locationlabs/mockredis | mockredis/client.py | MockRedis.ttl | def ttl(self, key):
"""
Emulate ttl
Even though the official redis commands documentation at http://redis.io/commands/ttl
states "Return value: Integer reply: TTL in seconds, -2 when key does not exist or -1
when key does not have a timeout." the redis-py lib returns None for bo... | python | def ttl(self, key):
"""
Emulate ttl
Even though the official redis commands documentation at http://redis.io/commands/ttl
states "Return value: Integer reply: TTL in seconds, -2 when key does not exist or -1
when key does not have a timeout." the redis-py lib returns None for bo... | [
"def",
"ttl",
"(",
"self",
",",
"key",
")",
":",
"value",
"=",
"self",
".",
"pttl",
"(",
"key",
")",
"if",
"value",
"is",
"None",
"or",
"value",
"<",
"0",
":",
"return",
"value",
"return",
"value",
"//",
"1000"
] | Emulate ttl
Even though the official redis commands documentation at http://redis.io/commands/ttl
states "Return value: Integer reply: TTL in seconds, -2 when key does not exist or -1
when key does not have a timeout." the redis-py lib returns None for both these cases.
The lib behavior... | [
"Emulate",
"ttl"
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L217-L233 |
locationlabs/mockredis | mockredis/client.py | MockRedis.pttl | def pttl(self, key):
"""
Emulate pttl
:param key: key for which pttl is requested.
:returns: the number of milliseconds till timeout, None if the key does not exist or if the
key has no timeout(as per the redis-py lib behavior).
"""
"""
Returns ... | python | def pttl(self, key):
"""
Emulate pttl
:param key: key for which pttl is requested.
:returns: the number of milliseconds till timeout, None if the key does not exist or if the
key has no timeout(as per the redis-py lib behavior).
"""
"""
Returns ... | [
"def",
"pttl",
"(",
"self",
",",
"key",
")",
":",
"\"\"\"\n Returns time to live in milliseconds if output_ms is True, else returns seconds.\n \"\"\"",
"key",
"=",
"self",
".",
"_encode",
"(",
"key",
")",
"if",
"key",
"not",
"in",
"self",
".",
"redis",
"... | Emulate pttl
:param key: key for which pttl is requested.
:returns: the number of milliseconds till timeout, None if the key does not exist or if the
key has no timeout(as per the redis-py lib behavior). | [
"Emulate",
"pttl"
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L235-L256 |
locationlabs/mockredis | mockredis/client.py | MockRedis.do_expire | 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 | 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):
... | [
"def",
"do_expire",
"(",
"self",
")",
":",
"# Deep copy to avoid RuntimeError: dictionary changed size during iteration",
"_timeouts",
"=",
"deepcopy",
"(",
"self",
".",
"timeouts",
")",
"for",
"key",
",",
"value",
"in",
"_timeouts",
".",
"items",
"(",
")",
":",
"... | Expire objects assuming now == time | [
"Expire",
"objects",
"assuming",
"now",
"==",
"time"
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L258-L269 |
locationlabs/mockredis | mockredis/client.py | MockRedis.set | 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 | 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... | [
"def",
"set",
"(",
"self",
",",
"key",
",",
"value",
",",
"ex",
"=",
"None",
",",
"px",
"=",
"None",
",",
"nx",
"=",
"False",
",",
"xx",
"=",
"False",
")",
":",
"key",
"=",
"self",
".",
"_encode",
"(",
"key",
")",
"value",
"=",
"self",
".",
... | 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 set, the preference is given to px.
If the key is not set for some reason, t... | [
"Set",
"the",
"value",
"for",
"the",
"key",
"in",
"the",
"context",
"of",
"the",
"provided",
"kwargs",
"."
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L313-L342 |
locationlabs/mockredis | mockredis/client.py | MockRedis._should_set | 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 | 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 ... | [
"def",
"_should_set",
"(",
"self",
",",
"key",
",",
"mode",
")",
":",
"if",
"mode",
"is",
"None",
"or",
"mode",
"not",
"in",
"[",
"\"nx\"",
",",
"\"xx\"",
"]",
":",
"return",
"True",
"if",
"mode",
"==",
"\"nx\"",
":",
"if",
"key",
"in",
"self",
"... | 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). | [
"Determine",
"if",
"it",
"is",
"okay",
"to",
"set",
"a",
"key",
"."
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L359-L381 |
locationlabs/mockredis | mockredis/client.py | MockRedis.setex | 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 | 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... | [
"def",
"setex",
"(",
"self",
",",
"name",
",",
"time",
",",
"value",
")",
":",
"if",
"not",
"self",
".",
"strict",
":",
"# when not strict mode swap value and time args order",
"time",
",",
"value",
"=",
"value",
",",
"time",
"return",
"self",
".",
"set",
... | Set the value of ``name`` to ``value`` that expires in ``time``
seconds. ``time`` can be represented by an integer or a Python
timedelta object. | [
"Set",
"the",
"value",
"of",
"name",
"to",
"value",
"that",
"expires",
"in",
"time",
"seconds",
".",
"time",
"can",
"be",
"represented",
"by",
"an",
"integer",
"or",
"a",
"Python",
"timedelta",
"object",
"."
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L383-L392 |
locationlabs/mockredis | mockredis/client.py | MockRedis.psetex | 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 | 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) | [
"def",
"psetex",
"(",
"self",
",",
"key",
",",
"time",
",",
"value",
")",
":",
"return",
"self",
".",
"set",
"(",
"key",
",",
"value",
",",
"px",
"=",
"time",
")"
] | Set the value of ``key`` to ``value`` that expires in ``time``
milliseconds. ``time`` can be represented by an integer or a Python
timedelta object. | [
"Set",
"the",
"value",
"of",
"key",
"to",
"value",
"that",
"expires",
"in",
"time",
"milliseconds",
".",
"time",
"can",
"be",
"represented",
"by",
"an",
"integer",
"or",
"a",
"Python",
"timedelta",
"object",
"."
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L394-L400 |
locationlabs/mockredis | mockredis/client.py | MockRedis.setnx | 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 | def setnx(self, key, value):
"""Set the value of ``key`` to ``value`` if key doesn't exist"""
return self.set(key, value, nx=True) | [
"def",
"setnx",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"return",
"self",
".",
"set",
"(",
"key",
",",
"value",
",",
"nx",
"=",
"True",
")"
] | Set the value of ``key`` to ``value`` if key doesn't exist | [
"Set",
"the",
"value",
"of",
"key",
"to",
"value",
"if",
"key",
"doesn",
"t",
"exist"
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L402-L404 |
locationlabs/mockredis | mockredis/client.py | MockRedis.mset | def mset(self, *args, **kwargs):
"""
Sets key/values based on a mapping. Mapping can be supplied as a single
dictionary argument or as kwargs.
"""
mapping = kwargs
if args:
if len(args) != 1 or not isinstance(args[0], dict):
raise RedisError('M... | python | def mset(self, *args, **kwargs):
"""
Sets key/values based on a mapping. Mapping can be supplied as a single
dictionary argument or as kwargs.
"""
mapping = kwargs
if args:
if len(args) != 1 or not isinstance(args[0], dict):
raise RedisError('M... | [
"def",
"mset",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"mapping",
"=",
"kwargs",
"if",
"args",
":",
"if",
"len",
"(",
"args",
")",
"!=",
"1",
"or",
"not",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"dict",
")",
"... | Sets key/values based on a mapping. Mapping can be supplied as a single
dictionary argument or as kwargs. | [
"Sets",
"key",
"/",
"values",
"based",
"on",
"a",
"mapping",
".",
"Mapping",
"can",
"be",
"supplied",
"as",
"a",
"single",
"dictionary",
"argument",
"or",
"as",
"kwargs",
"."
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L406-L422 |
locationlabs/mockredis | mockredis/client.py | MockRedis.msetnx | def msetnx(self, *args, **kwargs):
"""
Sets key/values based on a mapping if none of the keys are already set.
Mapping can be supplied as a single dictionary argument or as kwargs.
Returns a boolean indicating if the operation was successful.
"""
if args:
if l... | python | def msetnx(self, *args, **kwargs):
"""
Sets key/values based on a mapping if none of the keys are already set.
Mapping can be supplied as a single dictionary argument or as kwargs.
Returns a boolean indicating if the operation was successful.
"""
if args:
if l... | [
"def",
"msetnx",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"args",
":",
"if",
"len",
"(",
"args",
")",
"!=",
"1",
"or",
"not",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"dict",
")",
":",
"raise",
"RedisError",... | Sets key/values based on a mapping if none of the keys are already set.
Mapping can be supplied as a single dictionary argument or as kwargs.
Returns a boolean indicating if the operation was successful. | [
"Sets",
"key",
"/",
"values",
"based",
"on",
"a",
"mapping",
"if",
"none",
"of",
"the",
"keys",
"are",
"already",
"set",
".",
"Mapping",
"can",
"be",
"supplied",
"as",
"a",
"single",
"dictionary",
"argument",
"or",
"as",
"kwargs",
".",
"Returns",
"a",
... | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L424-L446 |
locationlabs/mockredis | mockredis/client.py | MockRedis.setbit | 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 | 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)))
... | [
"def",
"setbit",
"(",
"self",
",",
"key",
",",
"offset",
",",
"value",
")",
":",
"key",
"=",
"self",
".",
"_encode",
"(",
"key",
")",
"index",
",",
"bits",
",",
"mask",
"=",
"self",
".",
"_get_bits_and_offset",
"(",
"key",
",",
"offset",
")",
"if",... | Set the bit at ``offset`` in ``key`` to ``value``. | [
"Set",
"the",
"bit",
"at",
"offset",
"in",
"key",
"to",
"value",
"."
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L465-L484 |
locationlabs/mockredis | mockredis/client.py | MockRedis.getbit | 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 | 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 | [
"def",
"getbit",
"(",
"self",
",",
"key",
",",
"offset",
")",
":",
"key",
"=",
"self",
".",
"_encode",
"(",
"key",
")",
"index",
",",
"bits",
",",
"mask",
"=",
"self",
".",
"_get_bits_and_offset",
"(",
"key",
",",
"offset",
")",
"if",
"index",
">="... | Returns the bit value at ``offset`` in ``key``. | [
"Returns",
"the",
"bit",
"value",
"at",
"offset",
"in",
"key",
"."
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L486-L496 |
locationlabs/mockredis | mockredis/client.py | MockRedis.hexists | def hexists(self, hashkey, attribute):
"""Emulate hexists."""
redis_hash = self._get_hash(hashkey, 'HEXISTS')
return self._encode(attribute) in redis_hash | python | def hexists(self, hashkey, attribute):
"""Emulate hexists."""
redis_hash = self._get_hash(hashkey, 'HEXISTS')
return self._encode(attribute) in redis_hash | [
"def",
"hexists",
"(",
"self",
",",
"hashkey",
",",
"attribute",
")",
":",
"redis_hash",
"=",
"self",
".",
"_get_hash",
"(",
"hashkey",
",",
"'HEXISTS'",
")",
"return",
"self",
".",
"_encode",
"(",
"attribute",
")",
"in",
"redis_hash"
] | Emulate hexists. | [
"Emulate",
"hexists",
"."
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L506-L510 |
locationlabs/mockredis | mockredis/client.py | MockRedis.hget | def hget(self, hashkey, attribute):
"""Emulate hget."""
redis_hash = self._get_hash(hashkey, 'HGET')
return redis_hash.get(self._encode(attribute)) | python | def hget(self, hashkey, attribute):
"""Emulate hget."""
redis_hash = self._get_hash(hashkey, 'HGET')
return redis_hash.get(self._encode(attribute)) | [
"def",
"hget",
"(",
"self",
",",
"hashkey",
",",
"attribute",
")",
":",
"redis_hash",
"=",
"self",
".",
"_get_hash",
"(",
"hashkey",
",",
"'HGET'",
")",
"return",
"redis_hash",
".",
"get",
"(",
"self",
".",
"_encode",
"(",
"attribute",
")",
")"
] | Emulate hget. | [
"Emulate",
"hget",
"."
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L512-L516 |
locationlabs/mockredis | mockredis/client.py | MockRedis.hdel | def hdel(self, hashkey, *keys):
"""Emulate hdel"""
redis_hash = self._get_hash(hashkey, 'HDEL')
count = 0
for key in keys:
attribute = self._encode(key)
if attribute in redis_hash:
count += 1
del redis_hash[attribute]
... | python | def hdel(self, hashkey, *keys):
"""Emulate hdel"""
redis_hash = self._get_hash(hashkey, 'HDEL')
count = 0
for key in keys:
attribute = self._encode(key)
if attribute in redis_hash:
count += 1
del redis_hash[attribute]
... | [
"def",
"hdel",
"(",
"self",
",",
"hashkey",
",",
"*",
"keys",
")",
":",
"redis_hash",
"=",
"self",
".",
"_get_hash",
"(",
"hashkey",
",",
"'HDEL'",
")",
"count",
"=",
"0",
"for",
"key",
"in",
"keys",
":",
"attribute",
"=",
"self",
".",
"_encode",
"... | Emulate hdel | [
"Emulate",
"hdel"
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L524-L536 |
locationlabs/mockredis | mockredis/client.py | MockRedis.hmset | 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 | 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 | [
"def",
"hmset",
"(",
"self",
",",
"hashkey",
",",
"value",
")",
":",
"redis_hash",
"=",
"self",
".",
"_get_hash",
"(",
"hashkey",
",",
"'HMSET'",
",",
"create",
"=",
"True",
")",
"for",
"key",
",",
"value",
"in",
"value",
".",
"items",
"(",
")",
":... | Emulate hmset. | [
"Emulate",
"hmset",
"."
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L543-L550 |
locationlabs/mockredis | mockredis/client.py | MockRedis.hmget | 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 | 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] | [
"def",
"hmget",
"(",
"self",
",",
"hashkey",
",",
"keys",
",",
"*",
"args",
")",
":",
"redis_hash",
"=",
"self",
".",
"_get_hash",
"(",
"hashkey",
",",
"'HMGET'",
")",
"attributes",
"=",
"self",
".",
"_list_or_args",
"(",
"keys",
",",
"args",
")",
"r... | Emulate hmget. | [
"Emulate",
"hmget",
"."
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L552-L557 |
locationlabs/mockredis | mockredis/client.py | MockRedis.hset | 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 | 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... | [
"def",
"hset",
"(",
"self",
",",
"hashkey",
",",
"attribute",
",",
"value",
")",
":",
"redis_hash",
"=",
"self",
".",
"_get_hash",
"(",
"hashkey",
",",
"'HSET'",
",",
"create",
"=",
"True",
")",
"attribute",
"=",
"self",
".",
"_encode",
"(",
"attribute... | Emulate hset. | [
"Emulate",
"hset",
"."
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L559-L566 |
locationlabs/mockredis | mockredis/client.py | MockRedis.hsetnx | 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 | 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)... | [
"def",
"hsetnx",
"(",
"self",
",",
"hashkey",
",",
"attribute",
",",
"value",
")",
":",
"redis_hash",
"=",
"self",
".",
"_get_hash",
"(",
"hashkey",
",",
"'HSETNX'",
",",
"create",
"=",
"True",
")",
"attribute",
"=",
"self",
".",
"_encode",
"(",
"attri... | Emulate hsetnx. | [
"Emulate",
"hsetnx",
"."
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L568-L577 |
locationlabs/mockredis | mockredis/client.py | MockRedis.hincrby | def hincrby(self, hashkey, attribute, increment=1):
"""Emulate hincrby."""
return self._hincrby(hashkey, attribute, 'HINCRBY', long, increment) | python | def hincrby(self, hashkey, attribute, increment=1):
"""Emulate hincrby."""
return self._hincrby(hashkey, attribute, 'HINCRBY', long, increment) | [
"def",
"hincrby",
"(",
"self",
",",
"hashkey",
",",
"attribute",
",",
"increment",
"=",
"1",
")",
":",
"return",
"self",
".",
"_hincrby",
"(",
"hashkey",
",",
"attribute",
",",
"'HINCRBY'",
",",
"long",
",",
"increment",
")"
] | Emulate hincrby. | [
"Emulate",
"hincrby",
"."
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L579-L582 |
locationlabs/mockredis | mockredis/client.py | MockRedis.hincrbyfloat | def hincrbyfloat(self, hashkey, attribute, increment=1.0):
"""Emulate hincrbyfloat."""
return self._hincrby(hashkey, attribute, 'HINCRBYFLOAT', float, increment) | python | def hincrbyfloat(self, hashkey, attribute, increment=1.0):
"""Emulate hincrbyfloat."""
return self._hincrby(hashkey, attribute, 'HINCRBYFLOAT', float, increment) | [
"def",
"hincrbyfloat",
"(",
"self",
",",
"hashkey",
",",
"attribute",
",",
"increment",
"=",
"1.0",
")",
":",
"return",
"self",
".",
"_hincrby",
"(",
"hashkey",
",",
"attribute",
",",
"'HINCRBYFLOAT'",
",",
"float",
",",
"increment",
")"
] | Emulate hincrbyfloat. | [
"Emulate",
"hincrbyfloat",
"."
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L584-L587 |
locationlabs/mockredis | mockredis/client.py | MockRedis._hincrby | def _hincrby(self, hashkey, attribute, command, type_, increment):
"""Shared hincrby and hincrbyfloat routine"""
redis_hash = self._get_hash(hashkey, command, create=True)
attribute = self._encode(attribute)
previous_value = type_(redis_hash.get(attribute, '0'))
redis_hash[attrib... | python | def _hincrby(self, hashkey, attribute, command, type_, increment):
"""Shared hincrby and hincrbyfloat routine"""
redis_hash = self._get_hash(hashkey, command, create=True)
attribute = self._encode(attribute)
previous_value = type_(redis_hash.get(attribute, '0'))
redis_hash[attrib... | [
"def",
"_hincrby",
"(",
"self",
",",
"hashkey",
",",
"attribute",
",",
"command",
",",
"type_",
",",
"increment",
")",
":",
"redis_hash",
"=",
"self",
".",
"_get_hash",
"(",
"hashkey",
",",
"command",
",",
"create",
"=",
"True",
")",
"attribute",
"=",
... | Shared hincrby and hincrbyfloat routine | [
"Shared",
"hincrby",
"and",
"hincrbyfloat",
"routine"
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L589-L595 |
locationlabs/mockredis | mockredis/client.py | MockRedis.lrange | def lrange(self, key, start, stop):
"""Emulate lrange."""
redis_list = self._get_list(key, 'LRANGE')
start, stop = self._translate_range(len(redis_list), start, stop)
return redis_list[start:stop + 1] | python | def lrange(self, key, start, stop):
"""Emulate lrange."""
redis_list = self._get_list(key, 'LRANGE')
start, stop = self._translate_range(len(redis_list), start, stop)
return redis_list[start:stop + 1] | [
"def",
"lrange",
"(",
"self",
",",
"key",
",",
"start",
",",
"stop",
")",
":",
"redis_list",
"=",
"self",
".",
"_get_list",
"(",
"key",
",",
"'LRANGE'",
")",
"start",
",",
"stop",
"=",
"self",
".",
"_translate_range",
"(",
"len",
"(",
"redis_list",
"... | Emulate lrange. | [
"Emulate",
"lrange",
"."
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L611-L615 |
locationlabs/mockredis | mockredis/client.py | MockRedis.lindex | def lindex(self, key, index):
"""Emulate lindex."""
redis_list = self._get_list(key, 'LINDEX')
if self._encode(key) not in self.redis:
return None
try:
return redis_list[index]
except (IndexError):
# Redis returns nil if the index doesn't ex... | python | def lindex(self, key, index):
"""Emulate lindex."""
redis_list = self._get_list(key, 'LINDEX')
if self._encode(key) not in self.redis:
return None
try:
return redis_list[index]
except (IndexError):
# Redis returns nil if the index doesn't ex... | [
"def",
"lindex",
"(",
"self",
",",
"key",
",",
"index",
")",
":",
"redis_list",
"=",
"self",
".",
"_get_list",
"(",
"key",
",",
"'LINDEX'",
")",
"if",
"self",
".",
"_encode",
"(",
"key",
")",
"not",
"in",
"self",
".",
"redis",
":",
"return",
"None"... | Emulate lindex. | [
"Emulate",
"lindex",
"."
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L617-L629 |
locationlabs/mockredis | mockredis/client.py | MockRedis._blocking_pop | def _blocking_pop(self, pop_func, keys, timeout):
"""Emulate blocking pop functionality"""
if not isinstance(timeout, (int, long)):
raise RuntimeError('timeout is not an integer or out of range')
if timeout is None or timeout == 0:
timeout = self.blocking_timeout
... | python | def _blocking_pop(self, pop_func, keys, timeout):
"""Emulate blocking pop functionality"""
if not isinstance(timeout, (int, long)):
raise RuntimeError('timeout is not an integer or out of range')
if timeout is None or timeout == 0:
timeout = self.blocking_timeout
... | [
"def",
"_blocking_pop",
"(",
"self",
",",
"pop_func",
",",
"keys",
",",
"timeout",
")",
":",
"if",
"not",
"isinstance",
"(",
"timeout",
",",
"(",
"int",
",",
"long",
")",
")",
":",
"raise",
"RuntimeError",
"(",
"'timeout is not an integer or out of range'",
... | Emulate blocking pop functionality | [
"Emulate",
"blocking",
"pop",
"functionality"
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L638-L660 |
locationlabs/mockredis | mockredis/client.py | MockRedis.blpop | def blpop(self, keys, timeout=0):
"""Emulate blpop"""
return self._blocking_pop(self.lpop, keys, timeout) | python | def blpop(self, keys, timeout=0):
"""Emulate blpop"""
return self._blocking_pop(self.lpop, keys, timeout) | [
"def",
"blpop",
"(",
"self",
",",
"keys",
",",
"timeout",
"=",
"0",
")",
":",
"return",
"self",
".",
"_blocking_pop",
"(",
"self",
".",
"lpop",
",",
"keys",
",",
"timeout",
")"
] | Emulate blpop | [
"Emulate",
"blpop"
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L669-L671 |
locationlabs/mockredis | mockredis/client.py | MockRedis.brpop | def brpop(self, keys, timeout=0):
"""Emulate brpop"""
return self._blocking_pop(self.rpop, keys, timeout) | python | def brpop(self, keys, timeout=0):
"""Emulate brpop"""
return self._blocking_pop(self.rpop, keys, timeout) | [
"def",
"brpop",
"(",
"self",
",",
"keys",
",",
"timeout",
"=",
"0",
")",
":",
"return",
"self",
".",
"_blocking_pop",
"(",
"self",
".",
"rpop",
",",
"keys",
",",
"timeout",
")"
] | Emulate brpop | [
"Emulate",
"brpop"
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L673-L675 |
locationlabs/mockredis | mockredis/client.py | MockRedis.lpush | def lpush(self, key, *args):
"""Emulate lpush."""
redis_list = self._get_list(key, 'LPUSH', create=True)
# Creates the list at this key if it doesn't exist, and appends args to its beginning
args_reversed = [self._encode(arg) for arg in args]
args_reversed.reverse()
upda... | python | def lpush(self, key, *args):
"""Emulate lpush."""
redis_list = self._get_list(key, 'LPUSH', create=True)
# Creates the list at this key if it doesn't exist, and appends args to its beginning
args_reversed = [self._encode(arg) for arg in args]
args_reversed.reverse()
upda... | [
"def",
"lpush",
"(",
"self",
",",
"key",
",",
"*",
"args",
")",
":",
"redis_list",
"=",
"self",
".",
"_get_list",
"(",
"key",
",",
"'LPUSH'",
",",
"create",
"=",
"True",
")",
"# Creates the list at this key if it doesn't exist, and appends args to its beginning",
... | Emulate lpush. | [
"Emulate",
"lpush",
"."
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L693-L704 |
locationlabs/mockredis | mockredis/client.py | MockRedis.rpop | def rpop(self, key):
"""Emulate lpop."""
redis_list = self._get_list(key, 'RPOP')
if self._encode(key) not in self.redis:
return None
try:
value = redis_list.pop()
if len(redis_list) == 0:
self.delete(key)
return value
... | python | def rpop(self, key):
"""Emulate lpop."""
redis_list = self._get_list(key, 'RPOP')
if self._encode(key) not in self.redis:
return None
try:
value = redis_list.pop()
if len(redis_list) == 0:
self.delete(key)
return value
... | [
"def",
"rpop",
"(",
"self",
",",
"key",
")",
":",
"redis_list",
"=",
"self",
".",
"_get_list",
"(",
"key",
",",
"'RPOP'",
")",
"if",
"self",
".",
"_encode",
"(",
"key",
")",
"not",
"in",
"self",
".",
"redis",
":",
"return",
"None",
"try",
":",
"v... | Emulate lpop. | [
"Emulate",
"lpop",
"."
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L706-L720 |
locationlabs/mockredis | mockredis/client.py | MockRedis.rpush | def rpush(self, key, *args):
"""Emulate rpush."""
redis_list = self._get_list(key, 'RPUSH', create=True)
# Creates the list at this key if it doesn't exist, and appends args to it
redis_list.extend(map(self._encode, args))
# Return the length of the list after the push operatio... | python | def rpush(self, key, *args):
"""Emulate rpush."""
redis_list = self._get_list(key, 'RPUSH', create=True)
# Creates the list at this key if it doesn't exist, and appends args to it
redis_list.extend(map(self._encode, args))
# Return the length of the list after the push operatio... | [
"def",
"rpush",
"(",
"self",
",",
"key",
",",
"*",
"args",
")",
":",
"redis_list",
"=",
"self",
".",
"_get_list",
"(",
"key",
",",
"'RPUSH'",
",",
"create",
"=",
"True",
")",
"# Creates the list at this key if it doesn't exist, and appends args to it",
"redis_list... | Emulate rpush. | [
"Emulate",
"rpush",
"."
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L722-L730 |
locationlabs/mockredis | mockredis/client.py | MockRedis.lrem | def lrem(self, key, value, count=0):
"""Emulate lrem."""
value = self._encode(value)
redis_list = self._get_list(key, 'LREM')
removed_count = 0
if self._encode(key) in self.redis:
if count == 0:
# Remove all ocurrences
while redis_list.... | python | def lrem(self, key, value, count=0):
"""Emulate lrem."""
value = self._encode(value)
redis_list = self._get_list(key, 'LREM')
removed_count = 0
if self._encode(key) in self.redis:
if count == 0:
# Remove all ocurrences
while redis_list.... | [
"def",
"lrem",
"(",
"self",
",",
"key",
",",
"value",
",",
"count",
"=",
"0",
")",
":",
"value",
"=",
"self",
".",
"_encode",
"(",
"value",
")",
"redis_list",
"=",
"self",
".",
"_get_list",
"(",
"key",
",",
"'LREM'",
")",
"removed_count",
"=",
"0",... | Emulate lrem. | [
"Emulate",
"lrem",
"."
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L732-L765 |
locationlabs/mockredis | mockredis/client.py | MockRedis.ltrim | def ltrim(self, key, start, stop):
"""Emulate ltrim."""
redis_list = self._get_list(key, 'LTRIM')
if redis_list:
start, stop = self._translate_range(len(redis_list), start, stop)
self.redis[self._encode(key)] = redis_list[start:stop + 1]
return True | python | def ltrim(self, key, start, stop):
"""Emulate ltrim."""
redis_list = self._get_list(key, 'LTRIM')
if redis_list:
start, stop = self._translate_range(len(redis_list), start, stop)
self.redis[self._encode(key)] = redis_list[start:stop + 1]
return True | [
"def",
"ltrim",
"(",
"self",
",",
"key",
",",
"start",
",",
"stop",
")",
":",
"redis_list",
"=",
"self",
".",
"_get_list",
"(",
"key",
",",
"'LTRIM'",
")",
"if",
"redis_list",
":",
"start",
",",
"stop",
"=",
"self",
".",
"_translate_range",
"(",
"len... | Emulate ltrim. | [
"Emulate",
"ltrim",
"."
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L767-L773 |
locationlabs/mockredis | mockredis/client.py | MockRedis.rpoplpush | def rpoplpush(self, source, destination):
"""Emulate rpoplpush"""
transfer_item = self.rpop(source)
if transfer_item is not None:
self.lpush(destination, transfer_item)
return transfer_item | python | def rpoplpush(self, source, destination):
"""Emulate rpoplpush"""
transfer_item = self.rpop(source)
if transfer_item is not None:
self.lpush(destination, transfer_item)
return transfer_item | [
"def",
"rpoplpush",
"(",
"self",
",",
"source",
",",
"destination",
")",
":",
"transfer_item",
"=",
"self",
".",
"rpop",
"(",
"source",
")",
"if",
"transfer_item",
"is",
"not",
"None",
":",
"self",
".",
"lpush",
"(",
"destination",
",",
"transfer_item",
... | Emulate rpoplpush | [
"Emulate",
"rpoplpush"
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L775-L780 |
locationlabs/mockredis | mockredis/client.py | MockRedis.brpoplpush | def brpoplpush(self, source, destination, timeout=0):
"""Emulate brpoplpush"""
transfer_item = self.brpop(source, timeout)
if transfer_item is None:
return None
key, val = transfer_item
self.lpush(destination, val)
return val | python | def brpoplpush(self, source, destination, timeout=0):
"""Emulate brpoplpush"""
transfer_item = self.brpop(source, timeout)
if transfer_item is None:
return None
key, val = transfer_item
self.lpush(destination, val)
return val | [
"def",
"brpoplpush",
"(",
"self",
",",
"source",
",",
"destination",
",",
"timeout",
"=",
"0",
")",
":",
"transfer_item",
"=",
"self",
".",
"brpop",
"(",
"source",
",",
"timeout",
")",
"if",
"transfer_item",
"is",
"None",
":",
"return",
"None",
"key",
... | Emulate brpoplpush | [
"Emulate",
"brpoplpush"
] | train | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L782-L790 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.