id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
12,200 | optimizely/python-sdk | optimizely/helpers/condition_tree_evaluator.py | evaluate | def evaluate(conditions, leaf_evaluator):
""" Top level method to evaluate conditions.
Args:
conditions: Nested array of and/or conditions, or a single leaf condition value of any type.
Example: ['and', '0', ['or', '1', '2']]
leaf_evaluator: Function which will be called to evaluate leaf co... | python | def evaluate(conditions, leaf_evaluator):
""" Top level method to evaluate conditions.
Args:
conditions: Nested array of and/or conditions, or a single leaf condition value of any type.
Example: ['and', '0', ['or', '1', '2']]
leaf_evaluator: Function which will be called to evaluate leaf co... | [
"def",
"evaluate",
"(",
"conditions",
",",
"leaf_evaluator",
")",
":",
"if",
"isinstance",
"(",
"conditions",
",",
"list",
")",
":",
"if",
"conditions",
"[",
"0",
"]",
"in",
"list",
"(",
"EVALUATORS_BY_OPERATOR_TYPE",
".",
"keys",
"(",
")",
")",
":",
"re... | Top level method to evaluate conditions.
Args:
conditions: Nested array of and/or conditions, or a single leaf condition value of any type.
Example: ['and', '0', ['or', '1', '2']]
leaf_evaluator: Function which will be called to evaluate leaf condition values.
Returns:
Boolean: Result ... | [
"Top",
"level",
"method",
"to",
"evaluate",
"conditions",
"."
] | ec028d9efcf22498c3820f2650fa10f5c30bec90 | https://github.com/optimizely/python-sdk/blob/ec028d9efcf22498c3820f2650fa10f5c30bec90/optimizely/helpers/condition_tree_evaluator.py#L97-L119 |
12,201 | Parisson/TimeSide | timeside/core/analyzer.py | data_objet_class | def data_objet_class(data_mode='value', time_mode='framewise'):
"""
Factory function for Analyzer result
"""
classes_table = {('value', 'global'): GlobalValueObject,
('value', 'event'): EventValueObject,
('value', 'segment'): SegmentValueObject,
... | python | def data_objet_class(data_mode='value', time_mode='framewise'):
"""
Factory function for Analyzer result
"""
classes_table = {('value', 'global'): GlobalValueObject,
('value', 'event'): EventValueObject,
('value', 'segment'): SegmentValueObject,
... | [
"def",
"data_objet_class",
"(",
"data_mode",
"=",
"'value'",
",",
"time_mode",
"=",
"'framewise'",
")",
":",
"classes_table",
"=",
"{",
"(",
"'value'",
",",
"'global'",
")",
":",
"GlobalValueObject",
",",
"(",
"'value'",
",",
"'event'",
")",
":",
"EventValue... | Factory function for Analyzer result | [
"Factory",
"function",
"for",
"Analyzer",
"result"
] | 0618d75cd2f16021afcfd3d5b77f692adad76ea5 | https://github.com/Parisson/TimeSide/blob/0618d75cd2f16021afcfd3d5b77f692adad76ea5/timeside/core/analyzer.py#L511-L527 |
12,202 | Parisson/TimeSide | timeside/core/analyzer.py | JSON_NumpyArrayEncoder | def JSON_NumpyArrayEncoder(obj):
'''Define Specialize JSON encoder for numpy array'''
if isinstance(obj, np.ndarray):
return {'numpyArray': obj.tolist(),
'dtype': obj.dtype.__str__()}
elif isinstance(obj, np.generic):
return np.asscalar(obj)
else:
print type(obj)
... | python | def JSON_NumpyArrayEncoder(obj):
'''Define Specialize JSON encoder for numpy array'''
if isinstance(obj, np.ndarray):
return {'numpyArray': obj.tolist(),
'dtype': obj.dtype.__str__()}
elif isinstance(obj, np.generic):
return np.asscalar(obj)
else:
print type(obj)
... | [
"def",
"JSON_NumpyArrayEncoder",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"np",
".",
"ndarray",
")",
":",
"return",
"{",
"'numpyArray'",
":",
"obj",
".",
"tolist",
"(",
")",
",",
"'dtype'",
":",
"obj",
".",
"dtype",
".",
"__str__",
... | Define Specialize JSON encoder for numpy array | [
"Define",
"Specialize",
"JSON",
"encoder",
"for",
"numpy",
"array"
] | 0618d75cd2f16021afcfd3d5b77f692adad76ea5 | https://github.com/Parisson/TimeSide/blob/0618d75cd2f16021afcfd3d5b77f692adad76ea5/timeside/core/analyzer.py#L1047-L1056 |
12,203 | Parisson/TimeSide | timeside/core/analyzer.py | AnalyzerResult.render | def render(self):
'''Render a matplotlib figure from the analyzer result
Return the figure, use fig.show() to display if neeeded
'''
fig, ax = plt.subplots()
self.data_object._render_plot(ax)
return fig | python | def render(self):
'''Render a matplotlib figure from the analyzer result
Return the figure, use fig.show() to display if neeeded
'''
fig, ax = plt.subplots()
self.data_object._render_plot(ax)
return fig | [
"def",
"render",
"(",
"self",
")",
":",
"fig",
",",
"ax",
"=",
"plt",
".",
"subplots",
"(",
")",
"self",
".",
"data_object",
".",
"_render_plot",
"(",
"ax",
")",
"return",
"fig"
] | Render a matplotlib figure from the analyzer result
Return the figure, use fig.show() to display if neeeded | [
"Render",
"a",
"matplotlib",
"figure",
"from",
"the",
"analyzer",
"result"
] | 0618d75cd2f16021afcfd3d5b77f692adad76ea5 | https://github.com/Parisson/TimeSide/blob/0618d75cd2f16021afcfd3d5b77f692adad76ea5/timeside/core/analyzer.py#L670-L678 |
12,204 | Parisson/TimeSide | timeside/core/analyzer.py | Analyzer.new_result | def new_result(self, data_mode='value', time_mode='framewise'):
'''
Create a new result
Attributes
----------
data_object : MetadataObject
id_metadata : MetadataObject
audio_metadata : MetadataObject
frame_metadata : MetadataObject
label_metadata ... | python | def new_result(self, data_mode='value', time_mode='framewise'):
'''
Create a new result
Attributes
----------
data_object : MetadataObject
id_metadata : MetadataObject
audio_metadata : MetadataObject
frame_metadata : MetadataObject
label_metadata ... | [
"def",
"new_result",
"(",
"self",
",",
"data_mode",
"=",
"'value'",
",",
"time_mode",
"=",
"'framewise'",
")",
":",
"from",
"datetime",
"import",
"datetime",
"result",
"=",
"AnalyzerResult",
"(",
"data_mode",
"=",
"data_mode",
",",
"time_mode",
"=",
"time_mode... | Create a new result
Attributes
----------
data_object : MetadataObject
id_metadata : MetadataObject
audio_metadata : MetadataObject
frame_metadata : MetadataObject
label_metadata : MetadataObject
parameters : dict | [
"Create",
"a",
"new",
"result"
] | 0618d75cd2f16021afcfd3d5b77f692adad76ea5 | https://github.com/Parisson/TimeSide/blob/0618d75cd2f16021afcfd3d5b77f692adad76ea5/timeside/core/analyzer.py#L1279-L1324 |
12,205 | Parisson/TimeSide | timeside/core/preprocessors.py | downmix_to_mono | def downmix_to_mono(process_func):
'''
Pre-processing decorator that downmixes frames from multi-channel to mono
Downmix is achieved by averaging all channels
>>> from timeside.core.preprocessors import downmix_to_mono
>>> @downmix_to_mono
... def process(analyzer,frames,eod):
... prin... | python | def downmix_to_mono(process_func):
'''
Pre-processing decorator that downmixes frames from multi-channel to mono
Downmix is achieved by averaging all channels
>>> from timeside.core.preprocessors import downmix_to_mono
>>> @downmix_to_mono
... def process(analyzer,frames,eod):
... prin... | [
"def",
"downmix_to_mono",
"(",
"process_func",
")",
":",
"import",
"functools",
"@",
"functools",
".",
"wraps",
"(",
"process_func",
")",
"def",
"wrapper",
"(",
"analyzer",
",",
"frames",
",",
"eod",
")",
":",
"# Pre-processing",
"if",
"frames",
".",
"ndim",... | Pre-processing decorator that downmixes frames from multi-channel to mono
Downmix is achieved by averaging all channels
>>> from timeside.core.preprocessors import downmix_to_mono
>>> @downmix_to_mono
... def process(analyzer,frames,eod):
... print 'Frames, eod inside process :'
... pr... | [
"Pre",
"-",
"processing",
"decorator",
"that",
"downmixes",
"frames",
"from",
"multi",
"-",
"channel",
"to",
"mono"
] | 0618d75cd2f16021afcfd3d5b77f692adad76ea5 | https://github.com/Parisson/TimeSide/blob/0618d75cd2f16021afcfd3d5b77f692adad76ea5/timeside/core/preprocessors.py#L32-L77 |
12,206 | Parisson/TimeSide | timeside/core/preprocessors.py | frames_adapter | def frames_adapter(process_func):
'''
Pre-processing decorator that adapt frames to match input_blocksize and
input_stepsize of the decorated analyzer
>>> from timeside.core.preprocessors import frames_adapter
>>> @frames_adapter
... def process(analyzer,frames,eod):
... analyzer.frames... | python | def frames_adapter(process_func):
'''
Pre-processing decorator that adapt frames to match input_blocksize and
input_stepsize of the decorated analyzer
>>> from timeside.core.preprocessors import frames_adapter
>>> @frames_adapter
... def process(analyzer,frames,eod):
... analyzer.frames... | [
"def",
"frames_adapter",
"(",
"process_func",
")",
":",
"import",
"functools",
"import",
"numpy",
"as",
"np",
"class",
"framesBuffer",
"(",
"object",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"blocksize",
",",
"stepsize",
")",
":",
"self",
".",
"block... | Pre-processing decorator that adapt frames to match input_blocksize and
input_stepsize of the decorated analyzer
>>> from timeside.core.preprocessors import frames_adapter
>>> @frames_adapter
... def process(analyzer,frames,eod):
... analyzer.frames.append(frames)
... return frames, eod... | [
"Pre",
"-",
"processing",
"decorator",
"that",
"adapt",
"frames",
"to",
"match",
"input_blocksize",
"and",
"input_stepsize",
"of",
"the",
"decorated",
"analyzer"
] | 0618d75cd2f16021afcfd3d5b77f692adad76ea5 | https://github.com/Parisson/TimeSide/blob/0618d75cd2f16021afcfd3d5b77f692adad76ea5/timeside/core/preprocessors.py#L80-L190 |
12,207 | Parisson/TimeSide | timeside/server/models.py | Item.get_uri | def get_uri(self):
"""Return the Item source"""
if self.source_file and os.path.exists(self.source_file.path):
return self.source_file.path
elif self.source_url:
return self.source_url
return None | python | def get_uri(self):
"""Return the Item source"""
if self.source_file and os.path.exists(self.source_file.path):
return self.source_file.path
elif self.source_url:
return self.source_url
return None | [
"def",
"get_uri",
"(",
"self",
")",
":",
"if",
"self",
".",
"source_file",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"source_file",
".",
"path",
")",
":",
"return",
"self",
".",
"source_file",
".",
"path",
"elif",
"self",
".",
"sourc... | Return the Item source | [
"Return",
"the",
"Item",
"source"
] | 0618d75cd2f16021afcfd3d5b77f692adad76ea5 | https://github.com/Parisson/TimeSide/blob/0618d75cd2f16021afcfd3d5b77f692adad76ea5/timeside/server/models.py#L184-L190 |
12,208 | Parisson/TimeSide | timeside/server/models.py | Item.get_audio_duration | def get_audio_duration(self):
"""
Return item audio duration
"""
decoder = timeside.core.get_processor('file_decoder')(
uri=self.get_uri())
return decoder.uri_total_duration | python | def get_audio_duration(self):
"""
Return item audio duration
"""
decoder = timeside.core.get_processor('file_decoder')(
uri=self.get_uri())
return decoder.uri_total_duration | [
"def",
"get_audio_duration",
"(",
"self",
")",
":",
"decoder",
"=",
"timeside",
".",
"core",
".",
"get_processor",
"(",
"'file_decoder'",
")",
"(",
"uri",
"=",
"self",
".",
"get_uri",
"(",
")",
")",
"return",
"decoder",
".",
"uri_total_duration"
] | Return item audio duration | [
"Return",
"item",
"audio",
"duration"
] | 0618d75cd2f16021afcfd3d5b77f692adad76ea5 | https://github.com/Parisson/TimeSide/blob/0618d75cd2f16021afcfd3d5b77f692adad76ea5/timeside/server/models.py#L192-L198 |
12,209 | Parisson/TimeSide | timeside/server/models.py | Item.get_results_path | def get_results_path(self):
"""
Return Item result path
"""
result_path = os.path.join(RESULTS_ROOT, self.uuid)
if not os.path.exists(result_path):
os.makedirs(result_path)
return result_path | python | def get_results_path(self):
"""
Return Item result path
"""
result_path = os.path.join(RESULTS_ROOT, self.uuid)
if not os.path.exists(result_path):
os.makedirs(result_path)
return result_path | [
"def",
"get_results_path",
"(",
"self",
")",
":",
"result_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"RESULTS_ROOT",
",",
"self",
".",
"uuid",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"result_path",
")",
":",
"os",
".",
"makedir... | Return Item result path | [
"Return",
"Item",
"result",
"path"
] | 0618d75cd2f16021afcfd3d5b77f692adad76ea5 | https://github.com/Parisson/TimeSide/blob/0618d75cd2f16021afcfd3d5b77f692adad76ea5/timeside/server/models.py#L200-L207 |
12,210 | Parisson/TimeSide | timeside/plugins/decoder/utils.py | get_uri | def get_uri(source):
"""
Check a media source as a valid file or uri and return the proper uri
"""
import gst
src_info = source_info(source)
if src_info['is_file']: # Is this a file?
return get_uri(src_info['uri'])
elif gst.uri_is_valid(source): # Is this a valid URI source for... | python | def get_uri(source):
"""
Check a media source as a valid file or uri and return the proper uri
"""
import gst
src_info = source_info(source)
if src_info['is_file']: # Is this a file?
return get_uri(src_info['uri'])
elif gst.uri_is_valid(source): # Is this a valid URI source for... | [
"def",
"get_uri",
"(",
"source",
")",
":",
"import",
"gst",
"src_info",
"=",
"source_info",
"(",
"source",
")",
"if",
"src_info",
"[",
"'is_file'",
"]",
":",
"# Is this a file?",
"return",
"get_uri",
"(",
"src_info",
"[",
"'uri'",
"]",
")",
"elif",
"gst",
... | Check a media source as a valid file or uri and return the proper uri | [
"Check",
"a",
"media",
"source",
"as",
"a",
"valid",
"file",
"or",
"uri",
"and",
"return",
"the",
"proper",
"uri"
] | 0618d75cd2f16021afcfd3d5b77f692adad76ea5 | https://github.com/Parisson/TimeSide/blob/0618d75cd2f16021afcfd3d5b77f692adad76ea5/timeside/plugins/decoder/utils.py#L100-L119 |
12,211 | Parisson/TimeSide | timeside/plugins/decoder/utils.py | sha1sum_file | def sha1sum_file(filename):
'''
Return the secure hash digest with sha1 algorithm for a given file
>>> from timeside.core.tools.test_samples import samples
>>> wav_file = samples["C4_scale.wav"]
>>> print sha1sum_file(wav_file)
a598e78d0b5c90da54a77e34c083abdcd38d42ba
'''
import hashlib... | python | def sha1sum_file(filename):
'''
Return the secure hash digest with sha1 algorithm for a given file
>>> from timeside.core.tools.test_samples import samples
>>> wav_file = samples["C4_scale.wav"]
>>> print sha1sum_file(wav_file)
a598e78d0b5c90da54a77e34c083abdcd38d42ba
'''
import hashlib... | [
"def",
"sha1sum_file",
"(",
"filename",
")",
":",
"import",
"hashlib",
"import",
"io",
"sha1",
"=",
"hashlib",
".",
"sha1",
"(",
")",
"chunk_size",
"=",
"sha1",
".",
"block_size",
"*",
"io",
".",
"DEFAULT_BUFFER_SIZE",
"with",
"open",
"(",
"filename",
",",... | Return the secure hash digest with sha1 algorithm for a given file
>>> from timeside.core.tools.test_samples import samples
>>> wav_file = samples["C4_scale.wav"]
>>> print sha1sum_file(wav_file)
a598e78d0b5c90da54a77e34c083abdcd38d42ba | [
"Return",
"the",
"secure",
"hash",
"digest",
"with",
"sha1",
"algorithm",
"for",
"a",
"given",
"file"
] | 0618d75cd2f16021afcfd3d5b77f692adad76ea5 | https://github.com/Parisson/TimeSide/blob/0618d75cd2f16021afcfd3d5b77f692adad76ea5/timeside/plugins/decoder/utils.py#L180-L198 |
12,212 | Parisson/TimeSide | timeside/plugins/decoder/utils.py | sha1sum_url | def sha1sum_url(url):
'''Return the secure hash digest with sha1 algorithm for a given url
>>> url = "https://github.com/yomguy/timeside-samples/raw/master/samples/guitar.wav"
>>> print sha1sum_url(url)
08301c3f9a8d60926f31e253825cc74263e52ad1
'''
import hashlib
import urllib
from cont... | python | def sha1sum_url(url):
'''Return the secure hash digest with sha1 algorithm for a given url
>>> url = "https://github.com/yomguy/timeside-samples/raw/master/samples/guitar.wav"
>>> print sha1sum_url(url)
08301c3f9a8d60926f31e253825cc74263e52ad1
'''
import hashlib
import urllib
from cont... | [
"def",
"sha1sum_url",
"(",
"url",
")",
":",
"import",
"hashlib",
"import",
"urllib",
"from",
"contextlib",
"import",
"closing",
"sha1",
"=",
"hashlib",
".",
"sha1",
"(",
")",
"chunk_size",
"=",
"sha1",
".",
"block_size",
"*",
"8192",
"max_file_size",
"=",
... | Return the secure hash digest with sha1 algorithm for a given url
>>> url = "https://github.com/yomguy/timeside-samples/raw/master/samples/guitar.wav"
>>> print sha1sum_url(url)
08301c3f9a8d60926f31e253825cc74263e52ad1 | [
"Return",
"the",
"secure",
"hash",
"digest",
"with",
"sha1",
"algorithm",
"for",
"a",
"given",
"url"
] | 0618d75cd2f16021afcfd3d5b77f692adad76ea5 | https://github.com/Parisson/TimeSide/blob/0618d75cd2f16021afcfd3d5b77f692adad76ea5/timeside/plugins/decoder/utils.py#L201-L226 |
12,213 | Parisson/TimeSide | timeside/plugins/decoder/utils.py | sha1sum_numpy | def sha1sum_numpy(np_array):
'''
Return the secure hash digest with sha1 algorithm for a numpy array
'''
import hashlib
return hashlib.sha1(np_array.view(np.uint8)).hexdigest() | python | def sha1sum_numpy(np_array):
'''
Return the secure hash digest with sha1 algorithm for a numpy array
'''
import hashlib
return hashlib.sha1(np_array.view(np.uint8)).hexdigest() | [
"def",
"sha1sum_numpy",
"(",
"np_array",
")",
":",
"import",
"hashlib",
"return",
"hashlib",
".",
"sha1",
"(",
"np_array",
".",
"view",
"(",
"np",
".",
"uint8",
")",
")",
".",
"hexdigest",
"(",
")"
] | Return the secure hash digest with sha1 algorithm for a numpy array | [
"Return",
"the",
"secure",
"hash",
"digest",
"with",
"sha1",
"algorithm",
"for",
"a",
"numpy",
"array"
] | 0618d75cd2f16021afcfd3d5b77f692adad76ea5 | https://github.com/Parisson/TimeSide/blob/0618d75cd2f16021afcfd3d5b77f692adad76ea5/timeside/plugins/decoder/utils.py#L229-L234 |
12,214 | Parisson/TimeSide | timeside/core/tools/package.py | import_module_with_exceptions | def import_module_with_exceptions(name, package=None):
"""Wrapper around importlib.import_module to import TimeSide subpackage
and ignoring ImportError if Aubio, Yaafe and Vamp Host are not available"""
from timeside.core import _WITH_AUBIO, _WITH_YAAFE, _WITH_VAMP
if name.count('.server.'):
#... | python | def import_module_with_exceptions(name, package=None):
"""Wrapper around importlib.import_module to import TimeSide subpackage
and ignoring ImportError if Aubio, Yaafe and Vamp Host are not available"""
from timeside.core import _WITH_AUBIO, _WITH_YAAFE, _WITH_VAMP
if name.count('.server.'):
#... | [
"def",
"import_module_with_exceptions",
"(",
"name",
",",
"package",
"=",
"None",
")",
":",
"from",
"timeside",
".",
"core",
"import",
"_WITH_AUBIO",
",",
"_WITH_YAAFE",
",",
"_WITH_VAMP",
"if",
"name",
".",
"count",
"(",
"'.server.'",
")",
":",
"# TODO:",
"... | Wrapper around importlib.import_module to import TimeSide subpackage
and ignoring ImportError if Aubio, Yaafe and Vamp Host are not available | [
"Wrapper",
"around",
"importlib",
".",
"import_module",
"to",
"import",
"TimeSide",
"subpackage",
"and",
"ignoring",
"ImportError",
"if",
"Aubio",
"Yaafe",
"and",
"Vamp",
"Host",
"are",
"not",
"available"
] | 0618d75cd2f16021afcfd3d5b77f692adad76ea5 | https://github.com/Parisson/TimeSide/blob/0618d75cd2f16021afcfd3d5b77f692adad76ea5/timeside/core/tools/package.py#L50-L82 |
12,215 | Parisson/TimeSide | timeside/core/tools/package.py | check_vamp | def check_vamp():
"Check Vamp host availability"
try:
from timeside.plugins.analyzer.externals import vamp_plugin
except VampImportError:
warnings.warn('Vamp host is not available', ImportWarning,
stacklevel=2)
_WITH_VAMP = False
else:
_WITH_VAMP = ... | python | def check_vamp():
"Check Vamp host availability"
try:
from timeside.plugins.analyzer.externals import vamp_plugin
except VampImportError:
warnings.warn('Vamp host is not available', ImportWarning,
stacklevel=2)
_WITH_VAMP = False
else:
_WITH_VAMP = ... | [
"def",
"check_vamp",
"(",
")",
":",
"try",
":",
"from",
"timeside",
".",
"plugins",
".",
"analyzer",
".",
"externals",
"import",
"vamp_plugin",
"except",
"VampImportError",
":",
"warnings",
".",
"warn",
"(",
"'Vamp host is not available'",
",",
"ImportWarning",
... | Check Vamp host availability | [
"Check",
"Vamp",
"host",
"availability"
] | 0618d75cd2f16021afcfd3d5b77f692adad76ea5 | https://github.com/Parisson/TimeSide/blob/0618d75cd2f16021afcfd3d5b77f692adad76ea5/timeside/core/tools/package.py#L115-L128 |
12,216 | Parisson/TimeSide | timeside/plugins/grapher/utils.py | im_watermark | def im_watermark(im, inputtext, font=None, color=None, opacity=.6, margin=(30, 30)):
"""imprints a PIL image with the indicated text in lower-right corner"""
if im.mode != "RGBA":
im = im.convert("RGBA")
textlayer = Image.new("RGBA", im.size, (0, 0, 0, 0))
textdraw = ImageDraw.Draw(textlayer)
... | python | def im_watermark(im, inputtext, font=None, color=None, opacity=.6, margin=(30, 30)):
"""imprints a PIL image with the indicated text in lower-right corner"""
if im.mode != "RGBA":
im = im.convert("RGBA")
textlayer = Image.new("RGBA", im.size, (0, 0, 0, 0))
textdraw = ImageDraw.Draw(textlayer)
... | [
"def",
"im_watermark",
"(",
"im",
",",
"inputtext",
",",
"font",
"=",
"None",
",",
"color",
"=",
"None",
",",
"opacity",
"=",
".6",
",",
"margin",
"=",
"(",
"30",
",",
"30",
")",
")",
":",
"if",
"im",
".",
"mode",
"!=",
"\"RGBA\"",
":",
"im",
"... | imprints a PIL image with the indicated text in lower-right corner | [
"imprints",
"a",
"PIL",
"image",
"with",
"the",
"indicated",
"text",
"in",
"lower",
"-",
"right",
"corner"
] | 0618d75cd2f16021afcfd3d5b77f692adad76ea5 | https://github.com/Parisson/TimeSide/blob/0618d75cd2f16021afcfd3d5b77f692adad76ea5/timeside/plugins/grapher/utils.py#L168-L179 |
12,217 | Parisson/TimeSide | timeside/plugins/analyzer/utils.py | nextpow2 | def nextpow2(value):
"""Compute the nearest power of two greater or equal to the input value"""
if value >= 1:
return 2**np.ceil(np.log2(value)).astype(int)
elif value > 0:
return 1
elif value == 0:
return 0
else:
raise ValueError('Value must be positive') | python | def nextpow2(value):
"""Compute the nearest power of two greater or equal to the input value"""
if value >= 1:
return 2**np.ceil(np.log2(value)).astype(int)
elif value > 0:
return 1
elif value == 0:
return 0
else:
raise ValueError('Value must be positive') | [
"def",
"nextpow2",
"(",
"value",
")",
":",
"if",
"value",
">=",
"1",
":",
"return",
"2",
"**",
"np",
".",
"ceil",
"(",
"np",
".",
"log2",
"(",
"value",
")",
")",
".",
"astype",
"(",
"int",
")",
"elif",
"value",
">",
"0",
":",
"return",
"1",
"... | Compute the nearest power of two greater or equal to the input value | [
"Compute",
"the",
"nearest",
"power",
"of",
"two",
"greater",
"or",
"equal",
"to",
"the",
"input",
"value"
] | 0618d75cd2f16021afcfd3d5b77f692adad76ea5 | https://github.com/Parisson/TimeSide/blob/0618d75cd2f16021afcfd3d5b77f692adad76ea5/timeside/plugins/analyzer/utils.py#L65-L74 |
12,218 | Parisson/TimeSide | timeside/core/processor.py | FixedSizeInputAdapter.blocksize | def blocksize(self, input_totalframes):
"""Return the total number of frames that this adapter will output
according to the input_totalframes argument"""
blocksize = input_totalframes
if self.pad:
mod = input_totalframes % self.buffer_size
if mod:
... | python | def blocksize(self, input_totalframes):
"""Return the total number of frames that this adapter will output
according to the input_totalframes argument"""
blocksize = input_totalframes
if self.pad:
mod = input_totalframes % self.buffer_size
if mod:
... | [
"def",
"blocksize",
"(",
"self",
",",
"input_totalframes",
")",
":",
"blocksize",
"=",
"input_totalframes",
"if",
"self",
".",
"pad",
":",
"mod",
"=",
"input_totalframes",
"%",
"self",
".",
"buffer_size",
"if",
"mod",
":",
"blocksize",
"+=",
"self",
".",
"... | Return the total number of frames that this adapter will output
according to the input_totalframes argument | [
"Return",
"the",
"total",
"number",
"of",
"frames",
"that",
"this",
"adapter",
"will",
"output",
"according",
"to",
"the",
"input_totalframes",
"argument"
] | 0618d75cd2f16021afcfd3d5b77f692adad76ea5 | https://github.com/Parisson/TimeSide/blob/0618d75cd2f16021afcfd3d5b77f692adad76ea5/timeside/core/processor.py#L218-L228 |
12,219 | Parisson/TimeSide | timeside/core/processor.py | ProcessPipe.append_processor | def append_processor(self, proc, source_proc=None):
"Append a new processor to the pipe"
if source_proc is None and len(self.processors):
source_proc = self.processors[0]
if source_proc and not isinstance(source_proc, Processor):
raise TypeError('source_proc must be a Pr... | python | def append_processor(self, proc, source_proc=None):
"Append a new processor to the pipe"
if source_proc is None and len(self.processors):
source_proc = self.processors[0]
if source_proc and not isinstance(source_proc, Processor):
raise TypeError('source_proc must be a Pr... | [
"def",
"append_processor",
"(",
"self",
",",
"proc",
",",
"source_proc",
"=",
"None",
")",
":",
"if",
"source_proc",
"is",
"None",
"and",
"len",
"(",
"self",
".",
"processors",
")",
":",
"source_proc",
"=",
"self",
".",
"processors",
"[",
"0",
"]",
"if... | Append a new processor to the pipe | [
"Append",
"a",
"new",
"processor",
"to",
"the",
"pipe"
] | 0618d75cd2f16021afcfd3d5b77f692adad76ea5 | https://github.com/Parisson/TimeSide/blob/0618d75cd2f16021afcfd3d5b77f692adad76ea5/timeside/core/processor.py#L337-L369 |
12,220 | Parisson/TimeSide | timeside/plugins/analyzer/externals/vamp_plugin.py | simple_host_process | def simple_host_process(argslist):
"""Call vamp-simple-host"""
vamp_host = 'vamp-simple-host'
command = [vamp_host]
command.extend(argslist)
# try ?
stdout = subprocess.check_output(command,
stderr=subprocess.STDOUT).splitlines()
return stdout | python | def simple_host_process(argslist):
"""Call vamp-simple-host"""
vamp_host = 'vamp-simple-host'
command = [vamp_host]
command.extend(argslist)
# try ?
stdout = subprocess.check_output(command,
stderr=subprocess.STDOUT).splitlines()
return stdout | [
"def",
"simple_host_process",
"(",
"argslist",
")",
":",
"vamp_host",
"=",
"'vamp-simple-host'",
"command",
"=",
"[",
"vamp_host",
"]",
"command",
".",
"extend",
"(",
"argslist",
")",
"# try ?",
"stdout",
"=",
"subprocess",
".",
"check_output",
"(",
"command",
... | Call vamp-simple-host | [
"Call",
"vamp",
"-",
"simple",
"-",
"host"
] | 0618d75cd2f16021afcfd3d5b77f692adad76ea5 | https://github.com/Parisson/TimeSide/blob/0618d75cd2f16021afcfd3d5b77f692adad76ea5/timeside/plugins/analyzer/externals/vamp_plugin.py#L33-L43 |
12,221 | Parisson/TimeSide | timeside/plugins/grapher/spectrogram_lin.py | SpectrogramLinear.set_scale | def set_scale(self):
"""generate the lookup which translates y-coordinate to fft-bin"""
f_min = float(self.lower_freq)
f_max = float(self.higher_freq)
y_min = f_min
y_max = f_max
for y in range(self.image_height):
freq = y_min + y / (self.image_height - 1.0) ... | python | def set_scale(self):
"""generate the lookup which translates y-coordinate to fft-bin"""
f_min = float(self.lower_freq)
f_max = float(self.higher_freq)
y_min = f_min
y_max = f_max
for y in range(self.image_height):
freq = y_min + y / (self.image_height - 1.0) ... | [
"def",
"set_scale",
"(",
"self",
")",
":",
"f_min",
"=",
"float",
"(",
"self",
".",
"lower_freq",
")",
"f_max",
"=",
"float",
"(",
"self",
".",
"higher_freq",
")",
"y_min",
"=",
"f_min",
"y_max",
"=",
"f_max",
"for",
"y",
"in",
"range",
"(",
"self",
... | generate the lookup which translates y-coordinate to fft-bin | [
"generate",
"the",
"lookup",
"which",
"translates",
"y",
"-",
"coordinate",
"to",
"fft",
"-",
"bin"
] | 0618d75cd2f16021afcfd3d5b77f692adad76ea5 | https://github.com/Parisson/TimeSide/blob/0618d75cd2f16021afcfd3d5b77f692adad76ea5/timeside/plugins/grapher/spectrogram_lin.py#L55-L67 |
12,222 | Parisson/TimeSide | timeside/core/tools/hdf5.py | dict_from_hdf5 | def dict_from_hdf5(dict_like, h5group):
"""
Load a dictionnary-like object from a h5 file group
"""
# Read attributes
for name, value in h5group.attrs.items():
dict_like[name] = value | python | def dict_from_hdf5(dict_like, h5group):
"""
Load a dictionnary-like object from a h5 file group
"""
# Read attributes
for name, value in h5group.attrs.items():
dict_like[name] = value | [
"def",
"dict_from_hdf5",
"(",
"dict_like",
",",
"h5group",
")",
":",
"# Read attributes",
"for",
"name",
",",
"value",
"in",
"h5group",
".",
"attrs",
".",
"items",
"(",
")",
":",
"dict_like",
"[",
"name",
"]",
"=",
"value"
] | Load a dictionnary-like object from a h5 file group | [
"Load",
"a",
"dictionnary",
"-",
"like",
"object",
"from",
"a",
"h5",
"file",
"group"
] | 0618d75cd2f16021afcfd3d5b77f692adad76ea5 | https://github.com/Parisson/TimeSide/blob/0618d75cd2f16021afcfd3d5b77f692adad76ea5/timeside/core/tools/hdf5.py#L34-L40 |
12,223 | Parisson/TimeSide | timeside/plugins/decoder/array.py | ArrayDecoder.get_frames | def get_frames(self):
"Define an iterator that will return frames at the given blocksize"
nb_frames = self.input_totalframes // self.output_blocksize
if self.input_totalframes % self.output_blocksize == 0:
nb_frames -= 1 # Last frame must send eod=True
for index in xrange(... | python | def get_frames(self):
"Define an iterator that will return frames at the given blocksize"
nb_frames = self.input_totalframes // self.output_blocksize
if self.input_totalframes % self.output_blocksize == 0:
nb_frames -= 1 # Last frame must send eod=True
for index in xrange(... | [
"def",
"get_frames",
"(",
"self",
")",
":",
"nb_frames",
"=",
"self",
".",
"input_totalframes",
"//",
"self",
".",
"output_blocksize",
"if",
"self",
".",
"input_totalframes",
"%",
"self",
".",
"output_blocksize",
"==",
"0",
":",
"nb_frames",
"-=",
"1",
"# La... | Define an iterator that will return frames at the given blocksize | [
"Define",
"an",
"iterator",
"that",
"will",
"return",
"frames",
"at",
"the",
"given",
"blocksize"
] | 0618d75cd2f16021afcfd3d5b77f692adad76ea5 | https://github.com/Parisson/TimeSide/blob/0618d75cd2f16021afcfd3d5b77f692adad76ea5/timeside/plugins/decoder/array.py#L113-L125 |
12,224 | Parisson/TimeSide | timeside/core/component.py | implementations | def implementations(interface, recurse=True, abstract=False):
"""Returns the components implementing interface, and if recurse, any of
the descendants of interface. If abstract is True, also return the
abstract implementations."""
result = []
find_implementations(interface, recurse, abstract, result... | python | def implementations(interface, recurse=True, abstract=False):
"""Returns the components implementing interface, and if recurse, any of
the descendants of interface. If abstract is True, also return the
abstract implementations."""
result = []
find_implementations(interface, recurse, abstract, result... | [
"def",
"implementations",
"(",
"interface",
",",
"recurse",
"=",
"True",
",",
"abstract",
"=",
"False",
")",
":",
"result",
"=",
"[",
"]",
"find_implementations",
"(",
"interface",
",",
"recurse",
",",
"abstract",
",",
"result",
")",
"return",
"result"
] | Returns the components implementing interface, and if recurse, any of
the descendants of interface. If abstract is True, also return the
abstract implementations. | [
"Returns",
"the",
"components",
"implementing",
"interface",
"and",
"if",
"recurse",
"any",
"of",
"the",
"descendants",
"of",
"interface",
".",
"If",
"abstract",
"is",
"True",
"also",
"return",
"the",
"abstract",
"implementations",
"."
] | 0618d75cd2f16021afcfd3d5b77f692adad76ea5 | https://github.com/Parisson/TimeSide/blob/0618d75cd2f16021afcfd3d5b77f692adad76ea5/timeside/core/component.py#L65-L71 |
12,225 | Parisson/TimeSide | timeside/core/component.py | find_implementations | def find_implementations(interface, recurse, abstract, result):
"""Find implementations of an interface or of one of its descendants and
extend result with the classes found."""
for item in MetaComponent.implementations:
if (item['interface'] == interface and (abstract or not item['abstract'])):
... | python | def find_implementations(interface, recurse, abstract, result):
"""Find implementations of an interface or of one of its descendants and
extend result with the classes found."""
for item in MetaComponent.implementations:
if (item['interface'] == interface and (abstract or not item['abstract'])):
... | [
"def",
"find_implementations",
"(",
"interface",
",",
"recurse",
",",
"abstract",
",",
"result",
")",
":",
"for",
"item",
"in",
"MetaComponent",
".",
"implementations",
":",
"if",
"(",
"item",
"[",
"'interface'",
"]",
"==",
"interface",
"and",
"(",
"abstract... | Find implementations of an interface or of one of its descendants and
extend result with the classes found. | [
"Find",
"implementations",
"of",
"an",
"interface",
"or",
"of",
"one",
"of",
"its",
"descendants",
"and",
"extend",
"result",
"with",
"the",
"classes",
"found",
"."
] | 0618d75cd2f16021afcfd3d5b77f692adad76ea5 | https://github.com/Parisson/TimeSide/blob/0618d75cd2f16021afcfd3d5b77f692adad76ea5/timeside/core/component.py#L141-L152 |
12,226 | Parisson/TimeSide | timeside/core/grapher.py | Grapher.draw_peaks | def draw_peaks(self, x, peaks, line_color):
"""Draw 2 peaks at x"""
y1 = self.image_height * 0.5 - peaks[0] * (self.image_height - 4) * 0.5
y2 = self.image_height * 0.5 - peaks[1] * (self.image_height - 4) * 0.5
if self.previous_y:
self.draw.line(
[self.prev... | python | def draw_peaks(self, x, peaks, line_color):
"""Draw 2 peaks at x"""
y1 = self.image_height * 0.5 - peaks[0] * (self.image_height - 4) * 0.5
y2 = self.image_height * 0.5 - peaks[1] * (self.image_height - 4) * 0.5
if self.previous_y:
self.draw.line(
[self.prev... | [
"def",
"draw_peaks",
"(",
"self",
",",
"x",
",",
"peaks",
",",
"line_color",
")",
":",
"y1",
"=",
"self",
".",
"image_height",
"*",
"0.5",
"-",
"peaks",
"[",
"0",
"]",
"*",
"(",
"self",
".",
"image_height",
"-",
"4",
")",
"*",
"0.5",
"y2",
"=",
... | Draw 2 peaks at x | [
"Draw",
"2",
"peaks",
"at",
"x"
] | 0618d75cd2f16021afcfd3d5b77f692adad76ea5 | https://github.com/Parisson/TimeSide/blob/0618d75cd2f16021afcfd3d5b77f692adad76ea5/timeside/core/grapher.py#L193-L206 |
12,227 | Parisson/TimeSide | timeside/core/grapher.py | Grapher.draw_peaks_inverted | def draw_peaks_inverted(self, x, peaks, line_color):
"""Draw 2 inverted peaks at x"""
y1 = self.image_height * 0.5 - peaks[0] * (self.image_height - 4) * 0.5
y2 = self.image_height * 0.5 - peaks[1] * (self.image_height - 4) * 0.5
if self.previous_y and x < self.image_width - 1:
... | python | def draw_peaks_inverted(self, x, peaks, line_color):
"""Draw 2 inverted peaks at x"""
y1 = self.image_height * 0.5 - peaks[0] * (self.image_height - 4) * 0.5
y2 = self.image_height * 0.5 - peaks[1] * (self.image_height - 4) * 0.5
if self.previous_y and x < self.image_width - 1:
... | [
"def",
"draw_peaks_inverted",
"(",
"self",
",",
"x",
",",
"peaks",
",",
"line_color",
")",
":",
"y1",
"=",
"self",
".",
"image_height",
"*",
"0.5",
"-",
"peaks",
"[",
"0",
"]",
"*",
"(",
"self",
".",
"image_height",
"-",
"4",
")",
"*",
"0.5",
"y2",... | Draw 2 inverted peaks at x | [
"Draw",
"2",
"inverted",
"peaks",
"at",
"x"
] | 0618d75cd2f16021afcfd3d5b77f692adad76ea5 | https://github.com/Parisson/TimeSide/blob/0618d75cd2f16021afcfd3d5b77f692adad76ea5/timeside/core/grapher.py#L208-L224 |
12,228 | Parisson/TimeSide | timeside/core/grapher.py | Grapher.draw_anti_aliased_pixels | def draw_anti_aliased_pixels(self, x, y1, y2, color):
""" vertical anti-aliasing at y1 and y2 """
y_max = max(y1, y2)
y_max_int = int(y_max)
alpha = y_max - y_max_int
if alpha > 0.0 and alpha < 1.0 and y_max_int + 1 < self.image_height:
current_pix = self.pixel[int(... | python | def draw_anti_aliased_pixels(self, x, y1, y2, color):
""" vertical anti-aliasing at y1 and y2 """
y_max = max(y1, y2)
y_max_int = int(y_max)
alpha = y_max - y_max_int
if alpha > 0.0 and alpha < 1.0 and y_max_int + 1 < self.image_height:
current_pix = self.pixel[int(... | [
"def",
"draw_anti_aliased_pixels",
"(",
"self",
",",
"x",
",",
"y1",
",",
"y2",
",",
"color",
")",
":",
"y_max",
"=",
"max",
"(",
"y1",
",",
"y2",
")",
"y_max_int",
"=",
"int",
"(",
"y_max",
")",
"alpha",
"=",
"y_max",
"-",
"y_max_int",
"if",
"alph... | vertical anti-aliasing at y1 and y2 | [
"vertical",
"anti",
"-",
"aliasing",
"at",
"y1",
"and",
"y2"
] | 0618d75cd2f16021afcfd3d5b77f692adad76ea5 | https://github.com/Parisson/TimeSide/blob/0618d75cd2f16021afcfd3d5b77f692adad76ea5/timeside/core/grapher.py#L226-L249 |
12,229 | Parisson/TimeSide | timeside/plugins/grapher/spectrogram_log.py | SpectrogramLog.post_process | def post_process(self):
""" Apply last 2D transforms"""
self.image.putdata(self.pixels)
self.image = self.image.transpose(Image.ROTATE_90) | python | def post_process(self):
""" Apply last 2D transforms"""
self.image.putdata(self.pixels)
self.image = self.image.transpose(Image.ROTATE_90) | [
"def",
"post_process",
"(",
"self",
")",
":",
"self",
".",
"image",
".",
"putdata",
"(",
"self",
".",
"pixels",
")",
"self",
".",
"image",
"=",
"self",
".",
"image",
".",
"transpose",
"(",
"Image",
".",
"ROTATE_90",
")"
] | Apply last 2D transforms | [
"Apply",
"last",
"2D",
"transforms"
] | 0618d75cd2f16021afcfd3d5b77f692adad76ea5 | https://github.com/Parisson/TimeSide/blob/0618d75cd2f16021afcfd3d5b77f692adad76ea5/timeside/plugins/grapher/spectrogram_log.py#L105-L108 |
12,230 | Parisson/TimeSide | timeside/plugins/encoder/mp3.py | Mp3Encoder.write_metadata | def write_metadata(self):
"""Write all ID3v2.4 tags to file from self.metadata"""
import mutagen
from mutagen import id3
id3 = id3.ID3(self.filename)
for tag in self.metadata.keys():
value = self.metadata[tag]
frame = mutagen.id3.Frames[tag](3, value)
... | python | def write_metadata(self):
"""Write all ID3v2.4 tags to file from self.metadata"""
import mutagen
from mutagen import id3
id3 = id3.ID3(self.filename)
for tag in self.metadata.keys():
value = self.metadata[tag]
frame = mutagen.id3.Frames[tag](3, value)
... | [
"def",
"write_metadata",
"(",
"self",
")",
":",
"import",
"mutagen",
"from",
"mutagen",
"import",
"id3",
"id3",
"=",
"id3",
".",
"ID3",
"(",
"self",
".",
"filename",
")",
"for",
"tag",
"in",
"self",
".",
"metadata",
".",
"keys",
"(",
")",
":",
"value... | Write all ID3v2.4 tags to file from self.metadata | [
"Write",
"all",
"ID3v2",
".",
"4",
"tags",
"to",
"file",
"from",
"self",
".",
"metadata"
] | 0618d75cd2f16021afcfd3d5b77f692adad76ea5 | https://github.com/Parisson/TimeSide/blob/0618d75cd2f16021afcfd3d5b77f692adad76ea5/timeside/plugins/encoder/mp3.py#L94-L110 |
12,231 | btimby/fulltext | fulltext/__main__.py | main | def main(args=sys.argv[1:]):
"""Extract text from a file.
Commands:
extract - extract text from path
check - make sure all deps are installed
Usage:
fulltext extract [-v] [-f] <path>...
fulltext check [-t]
Options:
-f, --file Open file first.
... | python | def main(args=sys.argv[1:]):
"""Extract text from a file.
Commands:
extract - extract text from path
check - make sure all deps are installed
Usage:
fulltext extract [-v] [-f] <path>...
fulltext check [-t]
Options:
-f, --file Open file first.
... | [
"def",
"main",
"(",
"args",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
")",
":",
"opt",
"=",
"docopt",
"(",
"main",
".",
"__doc__",
".",
"strip",
"(",
")",
",",
"args",
",",
"options_first",
"=",
"True",
")",
"config_logging",
"(",
"opt",
"[",
... | Extract text from a file.
Commands:
extract - extract text from path
check - make sure all deps are installed
Usage:
fulltext extract [-v] [-f] <path>...
fulltext check [-t]
Options:
-f, --file Open file first.
-t, --title Check deps fo... | [
"Extract",
"text",
"from",
"a",
"file",
"."
] | 9234cc1e2099209430e20317649549026de283ce | https://github.com/btimby/fulltext/blob/9234cc1e2099209430e20317649549026de283ce/fulltext/__main__.py#L71-L103 |
12,232 | btimby/fulltext | fulltext/__init__.py | is_binary | def is_binary(f):
"""Return True if binary mode."""
# NOTE: order matters here. We don't bail on Python 2 just yet. Both
# codecs.open() and io.open() can open in text mode, both set the encoding
# attribute. We must do that check first.
# If it has a decoding attribute with a value, it is text mod... | python | def is_binary(f):
"""Return True if binary mode."""
# NOTE: order matters here. We don't bail on Python 2 just yet. Both
# codecs.open() and io.open() can open in text mode, both set the encoding
# attribute. We must do that check first.
# If it has a decoding attribute with a value, it is text mod... | [
"def",
"is_binary",
"(",
"f",
")",
":",
"# NOTE: order matters here. We don't bail on Python 2 just yet. Both",
"# codecs.open() and io.open() can open in text mode, both set the encoding",
"# attribute. We must do that check first.",
"# If it has a decoding attribute with a value, it is text mode... | Return True if binary mode. | [
"Return",
"True",
"if",
"binary",
"mode",
"."
] | 9234cc1e2099209430e20317649549026de283ce | https://github.com/btimby/fulltext/blob/9234cc1e2099209430e20317649549026de283ce/fulltext/__init__.py#L329-L362 |
12,233 | btimby/fulltext | fulltext/__init__.py | handle_path | def handle_path(backend_inst, path, **kwargs):
"""
Handle a path.
Called by `get()` when provided a path. This function will prefer the
backend's `handle_path()` if one is provided Otherwise, it will open the
given path then use `handle_fobj()`.
"""
if callable(getattr(backend_inst, 'handle... | python | def handle_path(backend_inst, path, **kwargs):
"""
Handle a path.
Called by `get()` when provided a path. This function will prefer the
backend's `handle_path()` if one is provided Otherwise, it will open the
given path then use `handle_fobj()`.
"""
if callable(getattr(backend_inst, 'handle... | [
"def",
"handle_path",
"(",
"backend_inst",
",",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"callable",
"(",
"getattr",
"(",
"backend_inst",
",",
"'handle_path'",
",",
"None",
")",
")",
":",
"# Prefer handle_path() if present.",
"LOGGER",
".",
"debug",
... | Handle a path.
Called by `get()` when provided a path. This function will prefer the
backend's `handle_path()` if one is provided Otherwise, it will open the
given path then use `handle_fobj()`. | [
"Handle",
"a",
"path",
"."
] | 9234cc1e2099209430e20317649549026de283ce | https://github.com/btimby/fulltext/blob/9234cc1e2099209430e20317649549026de283ce/fulltext/__init__.py#L365-L387 |
12,234 | btimby/fulltext | fulltext/__init__.py | handle_fobj | def handle_fobj(backend, f, **kwargs):
"""
Handle a file-like object.
Called by `get()` when provided a file-like. This function will prefer the
backend's `handle_fobj()` if one is provided. Otherwise, it will write the
data to a temporary file and call `handle_path()`.
"""
if not is_binary... | python | def handle_fobj(backend, f, **kwargs):
"""
Handle a file-like object.
Called by `get()` when provided a file-like. This function will prefer the
backend's `handle_fobj()` if one is provided. Otherwise, it will write the
data to a temporary file and call `handle_path()`.
"""
if not is_binary... | [
"def",
"handle_fobj",
"(",
"backend",
",",
"f",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"is_binary",
"(",
"f",
")",
":",
"raise",
"AssertionError",
"(",
"'File must be opened in binary mode.'",
")",
"if",
"callable",
"(",
"getattr",
"(",
"backend",
... | Handle a file-like object.
Called by `get()` when provided a file-like. This function will prefer the
backend's `handle_fobj()` if one is provided. Otherwise, it will write the
data to a temporary file and call `handle_path()`. | [
"Handle",
"a",
"file",
"-",
"like",
"object",
"."
] | 9234cc1e2099209430e20317649549026de283ce | https://github.com/btimby/fulltext/blob/9234cc1e2099209430e20317649549026de283ce/fulltext/__init__.py#L390-L421 |
12,235 | btimby/fulltext | fulltext/__init__.py | backend_from_mime | def backend_from_mime(mime):
"""Determine backend module object from a mime string."""
try:
mod_name = MIMETYPE_TO_BACKENDS[mime]
except KeyError:
msg = "No handler for %r, defaulting to %r" % (mime, DEFAULT_MIME)
if 'FULLTEXT_TESTING' in os.environ:
warn(msg)
el... | python | def backend_from_mime(mime):
"""Determine backend module object from a mime string."""
try:
mod_name = MIMETYPE_TO_BACKENDS[mime]
except KeyError:
msg = "No handler for %r, defaulting to %r" % (mime, DEFAULT_MIME)
if 'FULLTEXT_TESTING' in os.environ:
warn(msg)
el... | [
"def",
"backend_from_mime",
"(",
"mime",
")",
":",
"try",
":",
"mod_name",
"=",
"MIMETYPE_TO_BACKENDS",
"[",
"mime",
"]",
"except",
"KeyError",
":",
"msg",
"=",
"\"No handler for %r, defaulting to %r\"",
"%",
"(",
"mime",
",",
"DEFAULT_MIME",
")",
"if",
"'FULLTE... | Determine backend module object from a mime string. | [
"Determine",
"backend",
"module",
"object",
"from",
"a",
"mime",
"string",
"."
] | 9234cc1e2099209430e20317649549026de283ce | https://github.com/btimby/fulltext/blob/9234cc1e2099209430e20317649549026de283ce/fulltext/__init__.py#L428-L442 |
12,236 | btimby/fulltext | fulltext/__init__.py | backend_from_fname | def backend_from_fname(name):
"""Determine backend module object from a file name."""
ext = splitext(name)[1]
try:
mime = EXTS_TO_MIMETYPES[ext]
except KeyError:
try:
f = open(name, 'rb')
except IOError as e:
# The file may not exist, we are being asked... | python | def backend_from_fname(name):
"""Determine backend module object from a file name."""
ext = splitext(name)[1]
try:
mime = EXTS_TO_MIMETYPES[ext]
except KeyError:
try:
f = open(name, 'rb')
except IOError as e:
# The file may not exist, we are being asked... | [
"def",
"backend_from_fname",
"(",
"name",
")",
":",
"ext",
"=",
"splitext",
"(",
"name",
")",
"[",
"1",
"]",
"try",
":",
"mime",
"=",
"EXTS_TO_MIMETYPES",
"[",
"ext",
"]",
"except",
"KeyError",
":",
"try",
":",
"f",
"=",
"open",
"(",
"name",
",",
"... | Determine backend module object from a file name. | [
"Determine",
"backend",
"module",
"object",
"from",
"a",
"file",
"name",
"."
] | 9234cc1e2099209430e20317649549026de283ce | https://github.com/btimby/fulltext/blob/9234cc1e2099209430e20317649549026de283ce/fulltext/__init__.py#L445-L479 |
12,237 | btimby/fulltext | fulltext/__init__.py | backend_from_fobj | def backend_from_fobj(f):
"""Determine backend module object from a file object."""
if magic is None:
warn("magic lib is not installed; assuming mime type %r" % (
DEFAULT_MIME))
return backend_from_mime(DEFAULT_MIME)
else:
offset = f.tell()
try:
f.seek... | python | def backend_from_fobj(f):
"""Determine backend module object from a file object."""
if magic is None:
warn("magic lib is not installed; assuming mime type %r" % (
DEFAULT_MIME))
return backend_from_mime(DEFAULT_MIME)
else:
offset = f.tell()
try:
f.seek... | [
"def",
"backend_from_fobj",
"(",
"f",
")",
":",
"if",
"magic",
"is",
"None",
":",
"warn",
"(",
"\"magic lib is not installed; assuming mime type %r\"",
"%",
"(",
"DEFAULT_MIME",
")",
")",
"return",
"backend_from_mime",
"(",
"DEFAULT_MIME",
")",
"else",
":",
"offse... | Determine backend module object from a file object. | [
"Determine",
"backend",
"module",
"object",
"from",
"a",
"file",
"object",
"."
] | 9234cc1e2099209430e20317649549026de283ce | https://github.com/btimby/fulltext/blob/9234cc1e2099209430e20317649549026de283ce/fulltext/__init__.py#L482-L496 |
12,238 | btimby/fulltext | fulltext/__init__.py | backend_inst_from_mod | def backend_inst_from_mod(mod, encoding, encoding_errors, kwargs):
"""Given a mod and a set of opts return an instantiated
Backend class.
"""
kw = dict(encoding=encoding, encoding_errors=encoding_errors,
kwargs=kwargs)
try:
klass = getattr(mod, "Backend")
except AttributeEr... | python | def backend_inst_from_mod(mod, encoding, encoding_errors, kwargs):
"""Given a mod and a set of opts return an instantiated
Backend class.
"""
kw = dict(encoding=encoding, encoding_errors=encoding_errors,
kwargs=kwargs)
try:
klass = getattr(mod, "Backend")
except AttributeEr... | [
"def",
"backend_inst_from_mod",
"(",
"mod",
",",
"encoding",
",",
"encoding_errors",
",",
"kwargs",
")",
":",
"kw",
"=",
"dict",
"(",
"encoding",
"=",
"encoding",
",",
"encoding_errors",
"=",
"encoding_errors",
",",
"kwargs",
"=",
"kwargs",
")",
"try",
":",
... | Given a mod and a set of opts return an instantiated
Backend class. | [
"Given",
"a",
"mod",
"and",
"a",
"set",
"of",
"opts",
"return",
"an",
"instantiated",
"Backend",
"class",
"."
] | 9234cc1e2099209430e20317649549026de283ce | https://github.com/btimby/fulltext/blob/9234cc1e2099209430e20317649549026de283ce/fulltext/__init__.py#L499-L519 |
12,239 | btimby/fulltext | fulltext/__init__.py | get | def get(path_or_file, default=SENTINAL, mime=None, name=None, backend=None,
encoding=None, encoding_errors=None, kwargs=None,
_wtitle=False):
"""
Get document full text.
Accepts a path or file-like object.
* If given, `default` is returned instead of an error.
* `backend` is eithe... | python | def get(path_or_file, default=SENTINAL, mime=None, name=None, backend=None,
encoding=None, encoding_errors=None, kwargs=None,
_wtitle=False):
"""
Get document full text.
Accepts a path or file-like object.
* If given, `default` is returned instead of an error.
* `backend` is eithe... | [
"def",
"get",
"(",
"path_or_file",
",",
"default",
"=",
"SENTINAL",
",",
"mime",
"=",
"None",
",",
"name",
"=",
"None",
",",
"backend",
"=",
"None",
",",
"encoding",
"=",
"None",
",",
"encoding_errors",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"... | Get document full text.
Accepts a path or file-like object.
* If given, `default` is returned instead of an error.
* `backend` is either a module object or a string specifying which
default backend to use (e.g. "doc"); take a look at backends
directory to see a list of default backends.
... | [
"Get",
"document",
"full",
"text",
"."
] | 9234cc1e2099209430e20317649549026de283ce | https://github.com/btimby/fulltext/blob/9234cc1e2099209430e20317649549026de283ce/fulltext/__init__.py#L585-L618 |
12,240 | btimby/fulltext | fulltext/util.py | hilite | def hilite(s, ok=True, bold=False):
"""Return an highlighted version of 'string'."""
if not term_supports_colors():
return s
attr = []
if ok is None: # no color
pass
elif ok: # green
attr.append('32')
else: # red
attr.append('31')
if bold:
attr.ap... | python | def hilite(s, ok=True, bold=False):
"""Return an highlighted version of 'string'."""
if not term_supports_colors():
return s
attr = []
if ok is None: # no color
pass
elif ok: # green
attr.append('32')
else: # red
attr.append('31')
if bold:
attr.ap... | [
"def",
"hilite",
"(",
"s",
",",
"ok",
"=",
"True",
",",
"bold",
"=",
"False",
")",
":",
"if",
"not",
"term_supports_colors",
"(",
")",
":",
"return",
"s",
"attr",
"=",
"[",
"]",
"if",
"ok",
"is",
"None",
":",
"# no color",
"pass",
"elif",
"ok",
"... | Return an highlighted version of 'string'. | [
"Return",
"an",
"highlighted",
"version",
"of",
"string",
"."
] | 9234cc1e2099209430e20317649549026de283ce | https://github.com/btimby/fulltext/blob/9234cc1e2099209430e20317649549026de283ce/fulltext/util.py#L254-L267 |
12,241 | btimby/fulltext | fulltext/util.py | fobj_to_tempfile | def fobj_to_tempfile(f, suffix=''):
"""Context manager which copies a file object to disk and return its
name. When done the file is deleted.
"""
with tempfile.NamedTemporaryFile(
dir=TEMPDIR, suffix=suffix, delete=False) as t:
shutil.copyfileobj(f, t)
try:
yield t.name
... | python | def fobj_to_tempfile(f, suffix=''):
"""Context manager which copies a file object to disk and return its
name. When done the file is deleted.
"""
with tempfile.NamedTemporaryFile(
dir=TEMPDIR, suffix=suffix, delete=False) as t:
shutil.copyfileobj(f, t)
try:
yield t.name
... | [
"def",
"fobj_to_tempfile",
"(",
"f",
",",
"suffix",
"=",
"''",
")",
":",
"with",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"dir",
"=",
"TEMPDIR",
",",
"suffix",
"=",
"suffix",
",",
"delete",
"=",
"False",
")",
"as",
"t",
":",
"shutil",
".",
"copyfile... | Context manager which copies a file object to disk and return its
name. When done the file is deleted. | [
"Context",
"manager",
"which",
"copies",
"a",
"file",
"object",
"to",
"disk",
"and",
"return",
"its",
"name",
".",
"When",
"done",
"the",
"file",
"is",
"deleted",
"."
] | 9234cc1e2099209430e20317649549026de283ce | https://github.com/btimby/fulltext/blob/9234cc1e2099209430e20317649549026de283ce/fulltext/util.py#L308-L318 |
12,242 | btimby/fulltext | fulltext/data/winmake.py | rm | def rm(pattern):
"""Recursively remove a file or dir by pattern."""
paths = glob.glob(pattern)
for path in paths:
if path.startswith('.git/'):
continue
if os.path.isdir(path):
def onerror(fun, path, excinfo):
exc = excinfo[1]
if exc.err... | python | def rm(pattern):
"""Recursively remove a file or dir by pattern."""
paths = glob.glob(pattern)
for path in paths:
if path.startswith('.git/'):
continue
if os.path.isdir(path):
def onerror(fun, path, excinfo):
exc = excinfo[1]
if exc.err... | [
"def",
"rm",
"(",
"pattern",
")",
":",
"paths",
"=",
"glob",
".",
"glob",
"(",
"pattern",
")",
"for",
"path",
"in",
"paths",
":",
"if",
"path",
".",
"startswith",
"(",
"'.git/'",
")",
":",
"continue",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"... | Recursively remove a file or dir by pattern. | [
"Recursively",
"remove",
"a",
"file",
"or",
"dir",
"by",
"pattern",
"."
] | 9234cc1e2099209430e20317649549026de283ce | https://github.com/btimby/fulltext/blob/9234cc1e2099209430e20317649549026de283ce/fulltext/data/winmake.py#L106-L122 |
12,243 | btimby/fulltext | fulltext/data/winmake.py | help | def help():
"""Print this help"""
safe_print('Run "make [-p <PYTHON>] <target>" where <target> is one of:')
for name in sorted(_cmds):
safe_print(
" %-20s %s" % (name.replace('_', '-'), _cmds[name] or ''))
sys.exit(1) | python | def help():
"""Print this help"""
safe_print('Run "make [-p <PYTHON>] <target>" where <target> is one of:')
for name in sorted(_cmds):
safe_print(
" %-20s %s" % (name.replace('_', '-'), _cmds[name] or ''))
sys.exit(1) | [
"def",
"help",
"(",
")",
":",
"safe_print",
"(",
"'Run \"make [-p <PYTHON>] <target>\" where <target> is one of:'",
")",
"for",
"name",
"in",
"sorted",
"(",
"_cmds",
")",
":",
"safe_print",
"(",
"\" %-20s %s\"",
"%",
"(",
"name",
".",
"replace",
"(",
"'_'",
"... | Print this help | [
"Print",
"this",
"help"
] | 9234cc1e2099209430e20317649549026de283ce | https://github.com/btimby/fulltext/blob/9234cc1e2099209430e20317649549026de283ce/fulltext/data/winmake.py#L149-L155 |
12,244 | btimby/fulltext | fulltext/data/winmake.py | clean | def clean():
"""Deletes dev files"""
rm("$testfn*")
rm("*.bak")
rm("*.core")
rm("*.egg-info")
rm("*.orig")
rm("*.pyc")
rm("*.pyd")
rm("*.pyo")
rm("*.rej")
rm("*.so")
rm("*.~")
rm("*__pycache__")
rm(".coverage")
rm(".tox")
rm(".coverage")
rm("build")
... | python | def clean():
"""Deletes dev files"""
rm("$testfn*")
rm("*.bak")
rm("*.core")
rm("*.egg-info")
rm("*.orig")
rm("*.pyc")
rm("*.pyd")
rm("*.pyo")
rm("*.rej")
rm("*.so")
rm("*.~")
rm("*__pycache__")
rm(".coverage")
rm(".tox")
rm(".coverage")
rm("build")
... | [
"def",
"clean",
"(",
")",
":",
"rm",
"(",
"\"$testfn*\"",
")",
"rm",
"(",
"\"*.bak\"",
")",
"rm",
"(",
"\"*.core\"",
")",
"rm",
"(",
"\"*.egg-info\"",
")",
"rm",
"(",
"\"*.orig\"",
")",
"rm",
"(",
"\"*.pyc\"",
")",
"rm",
"(",
"\"*.pyd\"",
")",
"rm",
... | Deletes dev files | [
"Deletes",
"dev",
"files"
] | 9234cc1e2099209430e20317649549026de283ce | https://github.com/btimby/fulltext/blob/9234cc1e2099209430e20317649549026de283ce/fulltext/data/winmake.py#L200-L222 |
12,245 | btimby/fulltext | fulltext/data/winmake.py | lint | def lint():
"""Run flake8 against all py files"""
py_files = subprocess.check_output("git ls-files")
if PY3:
py_files = py_files.decode()
py_files = [x for x in py_files.split() if x.endswith('.py')]
py_files = ' '.join(py_files)
sh("%s -m flake8 %s" % (PYTHON, py_files), nolog=True) | python | def lint():
"""Run flake8 against all py files"""
py_files = subprocess.check_output("git ls-files")
if PY3:
py_files = py_files.decode()
py_files = [x for x in py_files.split() if x.endswith('.py')]
py_files = ' '.join(py_files)
sh("%s -m flake8 %s" % (PYTHON, py_files), nolog=True) | [
"def",
"lint",
"(",
")",
":",
"py_files",
"=",
"subprocess",
".",
"check_output",
"(",
"\"git ls-files\"",
")",
"if",
"PY3",
":",
"py_files",
"=",
"py_files",
".",
"decode",
"(",
")",
"py_files",
"=",
"[",
"x",
"for",
"x",
"in",
"py_files",
".",
"split... | Run flake8 against all py files | [
"Run",
"flake8",
"against",
"all",
"py",
"files"
] | 9234cc1e2099209430e20317649549026de283ce | https://github.com/btimby/fulltext/blob/9234cc1e2099209430e20317649549026de283ce/fulltext/data/winmake.py#L234-L241 |
12,246 | btimby/fulltext | fulltext/data/winmake.py | coverage | def coverage():
"""Run coverage tests."""
# Note: coverage options are controlled by .coveragerc file
install()
test_setup()
sh("%s -m coverage run %s" % (PYTHON, TEST_SCRIPT))
sh("%s -m coverage report" % PYTHON)
sh("%s -m coverage html" % PYTHON)
sh("%s -m webbrowser -t htmlcov/index.h... | python | def coverage():
"""Run coverage tests."""
# Note: coverage options are controlled by .coveragerc file
install()
test_setup()
sh("%s -m coverage run %s" % (PYTHON, TEST_SCRIPT))
sh("%s -m coverage report" % PYTHON)
sh("%s -m coverage html" % PYTHON)
sh("%s -m webbrowser -t htmlcov/index.h... | [
"def",
"coverage",
"(",
")",
":",
"# Note: coverage options are controlled by .coveragerc file",
"install",
"(",
")",
"test_setup",
"(",
")",
"sh",
"(",
"\"%s -m coverage run %s\"",
"%",
"(",
"PYTHON",
",",
"TEST_SCRIPT",
")",
")",
"sh",
"(",
"\"%s -m coverage report\... | Run coverage tests. | [
"Run",
"coverage",
"tests",
"."
] | 9234cc1e2099209430e20317649549026de283ce | https://github.com/btimby/fulltext/blob/9234cc1e2099209430e20317649549026de283ce/fulltext/data/winmake.py#L261-L269 |
12,247 | btimby/fulltext | fulltext/data/winmake.py | venv | def venv():
"""Install venv + deps."""
try:
import virtualenv # NOQA
except ImportError:
sh("%s -m pip install virtualenv" % PYTHON)
if not os.path.isdir("venv"):
sh("%s -m virtualenv venv" % PYTHON)
sh("venv\\Scripts\\pip install -r %s" % (REQUIREMENTS_TXT)) | python | def venv():
"""Install venv + deps."""
try:
import virtualenv # NOQA
except ImportError:
sh("%s -m pip install virtualenv" % PYTHON)
if not os.path.isdir("venv"):
sh("%s -m virtualenv venv" % PYTHON)
sh("venv\\Scripts\\pip install -r %s" % (REQUIREMENTS_TXT)) | [
"def",
"venv",
"(",
")",
":",
"try",
":",
"import",
"virtualenv",
"# NOQA",
"except",
"ImportError",
":",
"sh",
"(",
"\"%s -m pip install virtualenv\"",
"%",
"PYTHON",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"\"venv\"",
")",
":",
"sh",
"(... | Install venv + deps. | [
"Install",
"venv",
"+",
"deps",
"."
] | 9234cc1e2099209430e20317649549026de283ce | https://github.com/btimby/fulltext/blob/9234cc1e2099209430e20317649549026de283ce/fulltext/data/winmake.py#L311-L319 |
12,248 | pschmitt/pykeepass | pykeepass/kdbx_parsing/kdbx4.py | compute_header_hmac_hash | def compute_header_hmac_hash(context):
"""Compute HMAC-SHA256 hash of header.
Used to prevent header tampering."""
return hmac.new(
hashlib.sha512(
b'\xff' * 8 +
hashlib.sha512(
context._.header.value.dynamic_header.master_seed.data +
context.... | python | def compute_header_hmac_hash(context):
"""Compute HMAC-SHA256 hash of header.
Used to prevent header tampering."""
return hmac.new(
hashlib.sha512(
b'\xff' * 8 +
hashlib.sha512(
context._.header.value.dynamic_header.master_seed.data +
context.... | [
"def",
"compute_header_hmac_hash",
"(",
"context",
")",
":",
"return",
"hmac",
".",
"new",
"(",
"hashlib",
".",
"sha512",
"(",
"b'\\xff'",
"*",
"8",
"+",
"hashlib",
".",
"sha512",
"(",
"context",
".",
"_",
".",
"header",
".",
"value",
".",
"dynamic_heade... | Compute HMAC-SHA256 hash of header.
Used to prevent header tampering. | [
"Compute",
"HMAC",
"-",
"SHA256",
"hash",
"of",
"header",
".",
"Used",
"to",
"prevent",
"header",
"tampering",
"."
] | 85da3630d6e410b2a10d3e711cd69308b51d401d | https://github.com/pschmitt/pykeepass/blob/85da3630d6e410b2a10d3e711cd69308b51d401d/pykeepass/kdbx_parsing/kdbx4.py#L64-L79 |
12,249 | pschmitt/pykeepass | pykeepass/kdbx_parsing/kdbx4.py | compute_payload_block_hash | def compute_payload_block_hash(this):
"""Compute hash of each payload block.
Used to prevent payload corruption and tampering."""
return hmac.new(
hashlib.sha512(
struct.pack('<Q', this._index) +
hashlib.sha512(
this._._.header.value.dynamic_header.master_see... | python | def compute_payload_block_hash(this):
"""Compute hash of each payload block.
Used to prevent payload corruption and tampering."""
return hmac.new(
hashlib.sha512(
struct.pack('<Q', this._index) +
hashlib.sha512(
this._._.header.value.dynamic_header.master_see... | [
"def",
"compute_payload_block_hash",
"(",
"this",
")",
":",
"return",
"hmac",
".",
"new",
"(",
"hashlib",
".",
"sha512",
"(",
"struct",
".",
"pack",
"(",
"'<Q'",
",",
"this",
".",
"_index",
")",
"+",
"hashlib",
".",
"sha512",
"(",
"this",
".",
"_",
"... | Compute hash of each payload block.
Used to prevent payload corruption and tampering. | [
"Compute",
"hash",
"of",
"each",
"payload",
"block",
".",
"Used",
"to",
"prevent",
"payload",
"corruption",
"and",
"tampering",
"."
] | 85da3630d6e410b2a10d3e711cd69308b51d401d | https://github.com/pschmitt/pykeepass/blob/85da3630d6e410b2a10d3e711cd69308b51d401d/pykeepass/kdbx_parsing/kdbx4.py#L156-L171 |
12,250 | pschmitt/pykeepass | pykeepass/kdbx_parsing/pytwofish.py | Twofish.decrypt | def decrypt(self, block):
"""Decrypt blocks."""
if len(block) % 16:
raise ValueError("block size must be a multiple of 16")
plaintext = b''
while block:
a, b, c, d = struct.unpack("<4L", block[:16])
temp = [a, b, c, d]
decrypt(self.conte... | python | def decrypt(self, block):
"""Decrypt blocks."""
if len(block) % 16:
raise ValueError("block size must be a multiple of 16")
plaintext = b''
while block:
a, b, c, d = struct.unpack("<4L", block[:16])
temp = [a, b, c, d]
decrypt(self.conte... | [
"def",
"decrypt",
"(",
"self",
",",
"block",
")",
":",
"if",
"len",
"(",
"block",
")",
"%",
"16",
":",
"raise",
"ValueError",
"(",
"\"block size must be a multiple of 16\"",
")",
"plaintext",
"=",
"b''",
"while",
"block",
":",
"a",
",",
"b",
",",
"c",
... | Decrypt blocks. | [
"Decrypt",
"blocks",
"."
] | 85da3630d6e410b2a10d3e711cd69308b51d401d | https://github.com/pschmitt/pykeepass/blob/85da3630d6e410b2a10d3e711cd69308b51d401d/pykeepass/kdbx_parsing/pytwofish.py#L81-L96 |
12,251 | pschmitt/pykeepass | pykeepass/kdbx_parsing/pytwofish.py | Twofish.encrypt | def encrypt(self, block):
"""Encrypt blocks."""
if len(block) % 16:
raise ValueError("block size must be a multiple of 16")
ciphertext = b''
while block:
a, b, c, d = struct.unpack("<4L", block[0:16])
temp = [a, b, c, d]
encrypt(self.con... | python | def encrypt(self, block):
"""Encrypt blocks."""
if len(block) % 16:
raise ValueError("block size must be a multiple of 16")
ciphertext = b''
while block:
a, b, c, d = struct.unpack("<4L", block[0:16])
temp = [a, b, c, d]
encrypt(self.con... | [
"def",
"encrypt",
"(",
"self",
",",
"block",
")",
":",
"if",
"len",
"(",
"block",
")",
"%",
"16",
":",
"raise",
"ValueError",
"(",
"\"block size must be a multiple of 16\"",
")",
"ciphertext",
"=",
"b''",
"while",
"block",
":",
"a",
",",
"b",
",",
"c",
... | Encrypt blocks. | [
"Encrypt",
"blocks",
"."
] | 85da3630d6e410b2a10d3e711cd69308b51d401d | https://github.com/pschmitt/pykeepass/blob/85da3630d6e410b2a10d3e711cd69308b51d401d/pykeepass/kdbx_parsing/pytwofish.py#L99-L114 |
12,252 | pschmitt/pykeepass | pykeepass/kdbx_parsing/common.py | aes_kdf | def aes_kdf(key, rounds, password=None, keyfile=None):
"""Set up a context for AES128-ECB encryption to find transformed_key"""
cipher = AES.new(key, AES.MODE_ECB)
key_composite = compute_key_composite(
password=password,
keyfile=keyfile
)
# get the number of rounds from the header... | python | def aes_kdf(key, rounds, password=None, keyfile=None):
"""Set up a context for AES128-ECB encryption to find transformed_key"""
cipher = AES.new(key, AES.MODE_ECB)
key_composite = compute_key_composite(
password=password,
keyfile=keyfile
)
# get the number of rounds from the header... | [
"def",
"aes_kdf",
"(",
"key",
",",
"rounds",
",",
"password",
"=",
"None",
",",
"keyfile",
"=",
"None",
")",
":",
"cipher",
"=",
"AES",
".",
"new",
"(",
"key",
",",
"AES",
".",
"MODE_ECB",
")",
"key_composite",
"=",
"compute_key_composite",
"(",
"passw... | Set up a context for AES128-ECB encryption to find transformed_key | [
"Set",
"up",
"a",
"context",
"for",
"AES128",
"-",
"ECB",
"encryption",
"to",
"find",
"transformed_key"
] | 85da3630d6e410b2a10d3e711cd69308b51d401d | https://github.com/pschmitt/pykeepass/blob/85da3630d6e410b2a10d3e711cd69308b51d401d/pykeepass/kdbx_parsing/common.py#L84-L98 |
12,253 | pschmitt/pykeepass | pykeepass/kdbx_parsing/common.py | compute_key_composite | def compute_key_composite(password=None, keyfile=None):
"""Compute composite key.
Used in header verification and payload decryption."""
# hash the password
if password:
password_composite = hashlib.sha256(password.encode('utf-8')).digest()
else:
password_composite = b''
# hash ... | python | def compute_key_composite(password=None, keyfile=None):
"""Compute composite key.
Used in header verification and payload decryption."""
# hash the password
if password:
password_composite = hashlib.sha256(password.encode('utf-8')).digest()
else:
password_composite = b''
# hash ... | [
"def",
"compute_key_composite",
"(",
"password",
"=",
"None",
",",
"keyfile",
"=",
"None",
")",
":",
"# hash the password",
"if",
"password",
":",
"password_composite",
"=",
"hashlib",
".",
"sha256",
"(",
"password",
".",
"encode",
"(",
"'utf-8'",
")",
")",
... | Compute composite key.
Used in header verification and payload decryption. | [
"Compute",
"composite",
"key",
".",
"Used",
"in",
"header",
"verification",
"and",
"payload",
"decryption",
"."
] | 85da3630d6e410b2a10d3e711cd69308b51d401d | https://github.com/pschmitt/pykeepass/blob/85da3630d6e410b2a10d3e711cd69308b51d401d/pykeepass/kdbx_parsing/common.py#L101-L144 |
12,254 | pschmitt/pykeepass | pykeepass/kdbx_parsing/common.py | compute_master | def compute_master(context):
"""Computes master key from transformed key and master seed.
Used in payload decryption."""
# combine the transformed key with the header master seed to find the master_key
master_key = hashlib.sha256(
context._.header.value.dynamic_header.master_seed.data +
... | python | def compute_master(context):
"""Computes master key from transformed key and master seed.
Used in payload decryption."""
# combine the transformed key with the header master seed to find the master_key
master_key = hashlib.sha256(
context._.header.value.dynamic_header.master_seed.data +
... | [
"def",
"compute_master",
"(",
"context",
")",
":",
"# combine the transformed key with the header master seed to find the master_key",
"master_key",
"=",
"hashlib",
".",
"sha256",
"(",
"context",
".",
"_",
".",
"header",
".",
"value",
".",
"dynamic_header",
".",
"master... | Computes master key from transformed key and master seed.
Used in payload decryption. | [
"Computes",
"master",
"key",
"from",
"transformed",
"key",
"and",
"master",
"seed",
".",
"Used",
"in",
"payload",
"decryption",
"."
] | 85da3630d6e410b2a10d3e711cd69308b51d401d | https://github.com/pschmitt/pykeepass/blob/85da3630d6e410b2a10d3e711cd69308b51d401d/pykeepass/kdbx_parsing/common.py#L146-L154 |
12,255 | pschmitt/pykeepass | pykeepass/kdbx_parsing/common.py | Unprotect | def Unprotect(protected_stream_id, protected_stream_key, subcon):
"""Select stream cipher based on protected_stream_id"""
return Switch(
protected_stream_id,
{'arcfourvariant': ARCFourVariantStream(protected_stream_key, subcon),
'salsa20': Salsa20Stream(protected_stream_key, subcon),
... | python | def Unprotect(protected_stream_id, protected_stream_key, subcon):
"""Select stream cipher based on protected_stream_id"""
return Switch(
protected_stream_id,
{'arcfourvariant': ARCFourVariantStream(protected_stream_key, subcon),
'salsa20': Salsa20Stream(protected_stream_key, subcon),
... | [
"def",
"Unprotect",
"(",
"protected_stream_id",
",",
"protected_stream_key",
",",
"subcon",
")",
":",
"return",
"Switch",
"(",
"protected_stream_id",
",",
"{",
"'arcfourvariant'",
":",
"ARCFourVariantStream",
"(",
"protected_stream_key",
",",
"subcon",
")",
",",
"'s... | Select stream cipher based on protected_stream_id | [
"Select",
"stream",
"cipher",
"based",
"on",
"protected_stream_id"
] | 85da3630d6e410b2a10d3e711cd69308b51d401d | https://github.com/pschmitt/pykeepass/blob/85da3630d6e410b2a10d3e711cd69308b51d401d/pykeepass/kdbx_parsing/common.py#L231-L241 |
12,256 | pschmitt/pykeepass | pykeepass/kdbx_parsing/twofish.py | BlockCipher.encrypt | def encrypt(self,plaintext,n=''):
"""Encrypt some plaintext
plaintext = a string of binary data
n = the 'tweak' value when the chaining mode is XTS
The encrypt function will encrypt the supplied plaintext.
The behavior varies slightly depending on the chaini... | python | def encrypt(self,plaintext,n=''):
"""Encrypt some plaintext
plaintext = a string of binary data
n = the 'tweak' value when the chaining mode is XTS
The encrypt function will encrypt the supplied plaintext.
The behavior varies slightly depending on the chaini... | [
"def",
"encrypt",
"(",
"self",
",",
"plaintext",
",",
"n",
"=",
"''",
")",
":",
"#self.ed = 'e' if chain is encrypting, 'd' if decrypting,",
"# None if nothing happened with the chain yet",
"#assert self.ed in ('e',None) ",
"# makes sure you don't encrypt with a cipher that has started... | Encrypt some plaintext
plaintext = a string of binary data
n = the 'tweak' value when the chaining mode is XTS
The encrypt function will encrypt the supplied plaintext.
The behavior varies slightly depending on the chaining mode.
ECB, CBC:
---------... | [
"Encrypt",
"some",
"plaintext"
] | 85da3630d6e410b2a10d3e711cd69308b51d401d | https://github.com/pschmitt/pykeepass/blob/85da3630d6e410b2a10d3e711cd69308b51d401d/pykeepass/kdbx_parsing/twofish.py#L114-L159 |
12,257 | pschmitt/pykeepass | pykeepass/kdbx_parsing/twofish.py | BlockCipher.decrypt | def decrypt(self,ciphertext,n=''):
"""Decrypt some ciphertext
ciphertext = a string of binary data
n = the 'tweak' value when the chaining mode is XTS
The decrypt function will decrypt the supplied ciphertext.
The behavior varies slightly depending on the cha... | python | def decrypt(self,ciphertext,n=''):
"""Decrypt some ciphertext
ciphertext = a string of binary data
n = the 'tweak' value when the chaining mode is XTS
The decrypt function will decrypt the supplied ciphertext.
The behavior varies slightly depending on the cha... | [
"def",
"decrypt",
"(",
"self",
",",
"ciphertext",
",",
"n",
"=",
"''",
")",
":",
"#self.ed = 'e' if chain is encrypting, 'd' if decrypting,",
"# None if nothing happened with the chain yet",
"#assert self.ed in ('d',None)",
"# makes sure you don't decrypt with a cipher that has started... | Decrypt some ciphertext
ciphertext = a string of binary data
n = the 'tweak' value when the chaining mode is XTS
The decrypt function will decrypt the supplied ciphertext.
The behavior varies slightly depending on the chaining mode.
ECB, CBC:
-------... | [
"Decrypt",
"some",
"ciphertext"
] | 85da3630d6e410b2a10d3e711cd69308b51d401d | https://github.com/pschmitt/pykeepass/blob/85da3630d6e410b2a10d3e711cd69308b51d401d/pykeepass/kdbx_parsing/twofish.py#L161-L204 |
12,258 | pschmitt/pykeepass | pykeepass/kdbx_parsing/twofish.py | BlockCipher.final | def final(self,style='pkcs7'):
# TODO: after calling final, reset the IV? so the cipher is as good as new?
"""Finalizes the encryption by padding the cache
padfct = padding function
import from CryptoPlus.Util.padding
For ECB, CBC: the remaining bytes in the ca... | python | def final(self,style='pkcs7'):
# TODO: after calling final, reset the IV? so the cipher is as good as new?
"""Finalizes the encryption by padding the cache
padfct = padding function
import from CryptoPlus.Util.padding
For ECB, CBC: the remaining bytes in the ca... | [
"def",
"final",
"(",
"self",
",",
"style",
"=",
"'pkcs7'",
")",
":",
"# TODO: after calling final, reset the IV? so the cipher is as good as new?",
"assert",
"self",
".",
"mode",
"not",
"in",
"(",
"MODE_XTS",
",",
"MODE_CMAC",
")",
"# finalizing (=padding) doesn't make se... | Finalizes the encryption by padding the cache
padfct = padding function
import from CryptoPlus.Util.padding
For ECB, CBC: the remaining bytes in the cache will be padded and
encrypted.
For OFB,CFB, CTR: an encrypted padding will be returned, makin... | [
"Finalizes",
"the",
"encryption",
"by",
"padding",
"the",
"cache"
] | 85da3630d6e410b2a10d3e711cd69308b51d401d | https://github.com/pschmitt/pykeepass/blob/85da3630d6e410b2a10d3e711cd69308b51d401d/pykeepass/kdbx_parsing/twofish.py#L206-L237 |
12,259 | pschmitt/pykeepass | pykeepass/baseelement.py | BaseElement._datetime_to_utc | def _datetime_to_utc(self, dt):
"""Convert naive datetimes to UTC"""
if not dt.tzinfo:
dt = dt.replace(tzinfo=tz.gettz())
return dt.astimezone(tz.gettz('UTC')) | python | def _datetime_to_utc(self, dt):
"""Convert naive datetimes to UTC"""
if not dt.tzinfo:
dt = dt.replace(tzinfo=tz.gettz())
return dt.astimezone(tz.gettz('UTC')) | [
"def",
"_datetime_to_utc",
"(",
"self",
",",
"dt",
")",
":",
"if",
"not",
"dt",
".",
"tzinfo",
":",
"dt",
"=",
"dt",
".",
"replace",
"(",
"tzinfo",
"=",
"tz",
".",
"gettz",
"(",
")",
")",
"return",
"dt",
".",
"astimezone",
"(",
"tz",
".",
"gettz"... | Convert naive datetimes to UTC | [
"Convert",
"naive",
"datetimes",
"to",
"UTC"
] | 85da3630d6e410b2a10d3e711cd69308b51d401d | https://github.com/pschmitt/pykeepass/blob/85da3630d6e410b2a10d3e711cd69308b51d401d/pykeepass/baseelement.py#L92-L97 |
12,260 | pschmitt/pykeepass | pykeepass/baseelement.py | BaseElement._encode_time | def _encode_time(self, value):
"""Convert datetime to base64 or plaintext string"""
if self._kp.version >= (4, 0):
diff_seconds = int(
(
self._datetime_to_utc(value) -
datetime(
year=1,
m... | python | def _encode_time(self, value):
"""Convert datetime to base64 or plaintext string"""
if self._kp.version >= (4, 0):
diff_seconds = int(
(
self._datetime_to_utc(value) -
datetime(
year=1,
m... | [
"def",
"_encode_time",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"_kp",
".",
"version",
">=",
"(",
"4",
",",
"0",
")",
":",
"diff_seconds",
"=",
"int",
"(",
"(",
"self",
".",
"_datetime_to_utc",
"(",
"value",
")",
"-",
"datetime",
"("... | Convert datetime to base64 or plaintext string | [
"Convert",
"datetime",
"to",
"base64",
"or",
"plaintext",
"string"
] | 85da3630d6e410b2a10d3e711cd69308b51d401d | https://github.com/pschmitt/pykeepass/blob/85da3630d6e410b2a10d3e711cd69308b51d401d/pykeepass/baseelement.py#L99-L118 |
12,261 | pschmitt/pykeepass | pykeepass/baseelement.py | BaseElement._decode_time | def _decode_time(self, text):
"""Convert base64 time or plaintext time to datetime"""
if self._kp.version >= (4, 0):
# decode KDBX4 date from b64 format
try:
return (
datetime(year=1, month=1, day=1, tzinfo=tz.gettz('UTC')) +
... | python | def _decode_time(self, text):
"""Convert base64 time or plaintext time to datetime"""
if self._kp.version >= (4, 0):
# decode KDBX4 date from b64 format
try:
return (
datetime(year=1, month=1, day=1, tzinfo=tz.gettz('UTC')) +
... | [
"def",
"_decode_time",
"(",
"self",
",",
"text",
")",
":",
"if",
"self",
".",
"_kp",
".",
"version",
">=",
"(",
"4",
",",
"0",
")",
":",
"# decode KDBX4 date from b64 format",
"try",
":",
"return",
"(",
"datetime",
"(",
"year",
"=",
"1",
",",
"month",
... | Convert base64 time or plaintext time to datetime | [
"Convert",
"base64",
"time",
"or",
"plaintext",
"time",
"to",
"datetime"
] | 85da3630d6e410b2a10d3e711cd69308b51d401d | https://github.com/pschmitt/pykeepass/blob/85da3630d6e410b2a10d3e711cd69308b51d401d/pykeepass/baseelement.py#L120-L141 |
12,262 | thunder-project/thunder | thunder/images/readers.py | fromrdd | def fromrdd(rdd, dims=None, nrecords=None, dtype=None, labels=None, ordered=False):
"""
Load images from a Spark RDD.
Input RDD must be a collection of key-value pairs
where keys are singleton tuples indexing images,
and values are 2d or 3d ndarrays.
Parameters
----------
rdd : SparkRD... | python | def fromrdd(rdd, dims=None, nrecords=None, dtype=None, labels=None, ordered=False):
"""
Load images from a Spark RDD.
Input RDD must be a collection of key-value pairs
where keys are singleton tuples indexing images,
and values are 2d or 3d ndarrays.
Parameters
----------
rdd : SparkRD... | [
"def",
"fromrdd",
"(",
"rdd",
",",
"dims",
"=",
"None",
",",
"nrecords",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"ordered",
"=",
"False",
")",
":",
"from",
".",
"images",
"import",
"Images",
"from",
"bolt",
".",
"sp... | Load images from a Spark RDD.
Input RDD must be a collection of key-value pairs
where keys are singleton tuples indexing images,
and values are 2d or 3d ndarrays.
Parameters
----------
rdd : SparkRDD
An RDD containing the images.
dims : tuple or array, optional, default = None
... | [
"Load",
"images",
"from",
"a",
"Spark",
"RDD",
"."
] | 967ff8f3e7c2fabe1705743d95eb2746d4329786 | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/images/readers.py#L10-L56 |
12,263 | thunder-project/thunder | thunder/images/readers.py | fromarray | def fromarray(values, labels=None, npartitions=None, engine=None):
"""
Load images from an array.
First dimension will be used to index images,
so remaining dimensions after the first should
be the dimensions of the images,
e.g. (3, 100, 200) for 3 x (100, 200) images
Parameters
------... | python | def fromarray(values, labels=None, npartitions=None, engine=None):
"""
Load images from an array.
First dimension will be used to index images,
so remaining dimensions after the first should
be the dimensions of the images,
e.g. (3, 100, 200) for 3 x (100, 200) images
Parameters
------... | [
"def",
"fromarray",
"(",
"values",
",",
"labels",
"=",
"None",
",",
"npartitions",
"=",
"None",
",",
"engine",
"=",
"None",
")",
":",
"from",
".",
"images",
"import",
"Images",
"import",
"bolt",
"if",
"isinstance",
"(",
"values",
",",
"bolt",
".",
"spa... | Load images from an array.
First dimension will be used to index images,
so remaining dimensions after the first should
be the dimensions of the images,
e.g. (3, 100, 200) for 3 x (100, 200) images
Parameters
----------
values : array-like
The array of images. Can be a numpy array,... | [
"Load",
"images",
"from",
"an",
"array",
"."
] | 967ff8f3e7c2fabe1705743d95eb2746d4329786 | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/images/readers.py#L58-L116 |
12,264 | thunder-project/thunder | thunder/images/readers.py | fromlist | def fromlist(items, accessor=None, keys=None, dims=None, dtype=None, labels=None, npartitions=None, engine=None):
"""
Load images from a list of items using the given accessor.
Parameters
----------
accessor : function
Apply to each item from the list to yield an image.
keys : list, op... | python | def fromlist(items, accessor=None, keys=None, dims=None, dtype=None, labels=None, npartitions=None, engine=None):
"""
Load images from a list of items using the given accessor.
Parameters
----------
accessor : function
Apply to each item from the list to yield an image.
keys : list, op... | [
"def",
"fromlist",
"(",
"items",
",",
"accessor",
"=",
"None",
",",
"keys",
"=",
"None",
",",
"dims",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"npartitions",
"=",
"None",
",",
"engine",
"=",
"None",
")",
":",
"if",
... | Load images from a list of items using the given accessor.
Parameters
----------
accessor : function
Apply to each item from the list to yield an image.
keys : list, optional, default=None
An optional list of keys.
dims : tuple, optional, default=None
Specify a known image... | [
"Load",
"images",
"from",
"a",
"list",
"of",
"items",
"using",
"the",
"given",
"accessor",
"."
] | 967ff8f3e7c2fabe1705743d95eb2746d4329786 | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/images/readers.py#L119-L157 |
12,265 | thunder-project/thunder | thunder/images/readers.py | frompath | def frompath(path, accessor=None, ext=None, start=None, stop=None, recursive=False, npartitions=None, dims=None, dtype=None, labels=None, recount=False, engine=None, credentials=None):
"""
Load images from a path using the given accessor.
Supports both local and remote filesystems.
Parameters
----... | python | def frompath(path, accessor=None, ext=None, start=None, stop=None, recursive=False, npartitions=None, dims=None, dtype=None, labels=None, recount=False, engine=None, credentials=None):
"""
Load images from a path using the given accessor.
Supports both local and remote filesystems.
Parameters
----... | [
"def",
"frompath",
"(",
"path",
",",
"accessor",
"=",
"None",
",",
"ext",
"=",
"None",
",",
"start",
"=",
"None",
",",
"stop",
"=",
"None",
",",
"recursive",
"=",
"False",
",",
"npartitions",
"=",
"None",
",",
"dims",
"=",
"None",
",",
"dtype",
"="... | Load images from a path using the given accessor.
Supports both local and remote filesystems.
Parameters
----------
accessor : function
Apply to each item after loading to yield an image.
ext : str, optional, default=None
File extension.
npartitions : int, optional, default=N... | [
"Load",
"images",
"from",
"a",
"path",
"using",
"the",
"given",
"accessor",
"."
] | 967ff8f3e7c2fabe1705743d95eb2746d4329786 | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/images/readers.py#L159-L221 |
12,266 | thunder-project/thunder | thunder/images/readers.py | fromtif | def fromtif(path, ext='tif', start=None, stop=None, recursive=False, nplanes=None, npartitions=None, labels=None, engine=None, credentials=None, discard_extra=False):
"""
Loads images from single or multi-page TIF files.
Parameters
----------
path : str
Path to data files or directory, spec... | python | def fromtif(path, ext='tif', start=None, stop=None, recursive=False, nplanes=None, npartitions=None, labels=None, engine=None, credentials=None, discard_extra=False):
"""
Loads images from single or multi-page TIF files.
Parameters
----------
path : str
Path to data files or directory, spec... | [
"def",
"fromtif",
"(",
"path",
",",
"ext",
"=",
"'tif'",
",",
"start",
"=",
"None",
",",
"stop",
"=",
"None",
",",
"recursive",
"=",
"False",
",",
"nplanes",
"=",
"None",
",",
"npartitions",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"engine",
"... | Loads images from single or multi-page TIF files.
Parameters
----------
path : str
Path to data files or directory, specified as either a local filesystem path
or in a URI-like format, including scheme. May include a single '*' wildcard character.
ext : string, optional, default = 'tif... | [
"Loads",
"images",
"from",
"single",
"or",
"multi",
"-",
"page",
"TIF",
"files",
"."
] | 967ff8f3e7c2fabe1705743d95eb2746d4329786 | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/images/readers.py#L323-L397 |
12,267 | thunder-project/thunder | thunder/images/readers.py | frompng | def frompng(path, ext='png', start=None, stop=None, recursive=False, npartitions=None, labels=None, engine=None, credentials=None):
"""
Load images from PNG files.
Parameters
----------
path : str
Path to data files or directory, specified as either a local filesystem path
or in a U... | python | def frompng(path, ext='png', start=None, stop=None, recursive=False, npartitions=None, labels=None, engine=None, credentials=None):
"""
Load images from PNG files.
Parameters
----------
path : str
Path to data files or directory, specified as either a local filesystem path
or in a U... | [
"def",
"frompng",
"(",
"path",
",",
"ext",
"=",
"'png'",
",",
"start",
"=",
"None",
",",
"stop",
"=",
"None",
",",
"recursive",
"=",
"False",
",",
"npartitions",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"engine",
"=",
"None",
",",
"credentials",... | Load images from PNG files.
Parameters
----------
path : str
Path to data files or directory, specified as either a local filesystem path
or in a URI-like format, including scheme. May include a single '*' wildcard character.
ext : string, optional, default = 'tif'
Extension re... | [
"Load",
"images",
"from",
"PNG",
"files",
"."
] | 967ff8f3e7c2fabe1705743d95eb2746d4329786 | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/images/readers.py#L399-L436 |
12,268 | thunder-project/thunder | thunder/images/readers.py | fromrandom | def fromrandom(shape=(10, 50, 50), npartitions=1, seed=42, engine=None):
"""
Generate random image data.
Parameters
----------
shape : tuple, optional, default=(10, 50, 50)
Dimensions of images.
npartitions : int, optional, default=1
Number of partitions.
seed : int, optio... | python | def fromrandom(shape=(10, 50, 50), npartitions=1, seed=42, engine=None):
"""
Generate random image data.
Parameters
----------
shape : tuple, optional, default=(10, 50, 50)
Dimensions of images.
npartitions : int, optional, default=1
Number of partitions.
seed : int, optio... | [
"def",
"fromrandom",
"(",
"shape",
"=",
"(",
"10",
",",
"50",
",",
"50",
")",
",",
"npartitions",
"=",
"1",
",",
"seed",
"=",
"42",
",",
"engine",
"=",
"None",
")",
":",
"seed",
"=",
"hash",
"(",
"seed",
")",
"def",
"generate",
"(",
"v",
")",
... | Generate random image data.
Parameters
----------
shape : tuple, optional, default=(10, 50, 50)
Dimensions of images.
npartitions : int, optional, default=1
Number of partitions.
seed : int, optional, default=42
Random seed. | [
"Generate",
"random",
"image",
"data",
"."
] | 967ff8f3e7c2fabe1705743d95eb2746d4329786 | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/images/readers.py#L438-L459 |
12,269 | thunder-project/thunder | thunder/images/readers.py | fromexample | def fromexample(name=None, engine=None):
"""
Load example image data.
Data are downloaded from S3, so this method requires an internet connection.
Parameters
----------
name : str
Name of dataset, if not specified will print options.
engine : object, default = None
Computa... | python | def fromexample(name=None, engine=None):
"""
Load example image data.
Data are downloaded from S3, so this method requires an internet connection.
Parameters
----------
name : str
Name of dataset, if not specified will print options.
engine : object, default = None
Computa... | [
"def",
"fromexample",
"(",
"name",
"=",
"None",
",",
"engine",
"=",
"None",
")",
":",
"datasets",
"=",
"[",
"'mouse'",
",",
"'fish'",
"]",
"if",
"name",
"is",
"None",
":",
"print",
"(",
"'Availiable example image datasets'",
")",
"for",
"d",
"in",
"datas... | Load example image data.
Data are downloaded from S3, so this method requires an internet connection.
Parameters
----------
name : str
Name of dataset, if not specified will print options.
engine : object, default = None
Computational engine (e.g. a SparkContext for Spark) | [
"Load",
"example",
"image",
"data",
"."
] | 967ff8f3e7c2fabe1705743d95eb2746d4329786 | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/images/readers.py#L461-L497 |
12,270 | thunder-project/thunder | thunder/blocks/local.py | LocalChunks.unchunk | def unchunk(self):
"""
Reconstitute the chunked array back into a full ndarray.
Returns
-------
ndarray
"""
if self.padding != len(self.shape)*(0,):
shape = self.values.shape
arr = empty(shape, dtype=object)
for inds in product... | python | def unchunk(self):
"""
Reconstitute the chunked array back into a full ndarray.
Returns
-------
ndarray
"""
if self.padding != len(self.shape)*(0,):
shape = self.values.shape
arr = empty(shape, dtype=object)
for inds in product... | [
"def",
"unchunk",
"(",
"self",
")",
":",
"if",
"self",
".",
"padding",
"!=",
"len",
"(",
"self",
".",
"shape",
")",
"*",
"(",
"0",
",",
")",
":",
"shape",
"=",
"self",
".",
"values",
".",
"shape",
"arr",
"=",
"empty",
"(",
"shape",
",",
"dtype"... | Reconstitute the chunked array back into a full ndarray.
Returns
-------
ndarray | [
"Reconstitute",
"the",
"chunked",
"array",
"back",
"into",
"a",
"full",
"ndarray",
"."
] | 967ff8f3e7c2fabe1705743d95eb2746d4329786 | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/blocks/local.py#L54-L75 |
12,271 | thunder-project/thunder | thunder/blocks/local.py | LocalChunks.chunk | def chunk(arr, chunk_size="150", padding=None):
"""
Created a chunked array from a full array and a chunk size.
Parameters
----------
array : ndarray
Array that will be broken into chunks
chunk_size : string or tuple, default = '150'
Size of each... | python | def chunk(arr, chunk_size="150", padding=None):
"""
Created a chunked array from a full array and a chunk size.
Parameters
----------
array : ndarray
Array that will be broken into chunks
chunk_size : string or tuple, default = '150'
Size of each... | [
"def",
"chunk",
"(",
"arr",
",",
"chunk_size",
"=",
"\"150\"",
",",
"padding",
"=",
"None",
")",
":",
"plan",
",",
"_",
"=",
"LocalChunks",
".",
"getplan",
"(",
"chunk_size",
",",
"arr",
".",
"shape",
"[",
"1",
":",
"]",
",",
"arr",
".",
"dtype",
... | Created a chunked array from a full array and a chunk size.
Parameters
----------
array : ndarray
Array that will be broken into chunks
chunk_size : string or tuple, default = '150'
Size of each image chunk.
If a str, size of memory footprint in KB.
... | [
"Created",
"a",
"chunked",
"array",
"from",
"a",
"full",
"array",
"and",
"a",
"chunk",
"size",
"."
] | 967ff8f3e7c2fabe1705743d95eb2746d4329786 | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/blocks/local.py#L121-L178 |
12,272 | thunder-project/thunder | thunder/base.py | Data.filter | def filter(self, func):
"""
Filter array along an axis.
Applies a function which should evaluate to boolean,
along a single axis or multiple axes. Array will be
aligned so that the desired set of axes are in the
keys, which may require a transpose/reshape.
Param... | python | def filter(self, func):
"""
Filter array along an axis.
Applies a function which should evaluate to boolean,
along a single axis or multiple axes. Array will be
aligned so that the desired set of axes are in the
keys, which may require a transpose/reshape.
Param... | [
"def",
"filter",
"(",
"self",
",",
"func",
")",
":",
"if",
"self",
".",
"mode",
"==",
"'local'",
":",
"reshaped",
"=",
"self",
".",
"_align",
"(",
"self",
".",
"baseaxes",
")",
"filtered",
"=",
"asarray",
"(",
"list",
"(",
"filter",
"(",
"func",
",... | Filter array along an axis.
Applies a function which should evaluate to boolean,
along a single axis or multiple axes. Array will be
aligned so that the desired set of axes are in the
keys, which may require a transpose/reshape.
Parameters
----------
func : func... | [
"Filter",
"array",
"along",
"an",
"axis",
"."
] | 967ff8f3e7c2fabe1705743d95eb2746d4329786 | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/base.py#L372-L410 |
12,273 | thunder-project/thunder | thunder/base.py | Data.map | def map(self, func, value_shape=None, dtype=None, with_keys=False):
"""
Apply an array -> array function across an axis.
Array will be aligned so that the desired set of axes
are in the keys, which may require a transpose/reshape.
Parameters
----------
func : fu... | python | def map(self, func, value_shape=None, dtype=None, with_keys=False):
"""
Apply an array -> array function across an axis.
Array will be aligned so that the desired set of axes
are in the keys, which may require a transpose/reshape.
Parameters
----------
func : fu... | [
"def",
"map",
"(",
"self",
",",
"func",
",",
"value_shape",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"with_keys",
"=",
"False",
")",
":",
"axis",
"=",
"self",
".",
"baseaxes",
"if",
"self",
".",
"mode",
"==",
"'local'",
":",
"axes",
"=",
"sorte... | Apply an array -> array function across an axis.
Array will be aligned so that the desired set of axes
are in the keys, which may require a transpose/reshape.
Parameters
----------
func : function
Function of a single array to apply. If with_keys=True,
f... | [
"Apply",
"an",
"array",
"-",
">",
"array",
"function",
"across",
"an",
"axis",
"."
] | 967ff8f3e7c2fabe1705743d95eb2746d4329786 | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/base.py#L412-L469 |
12,274 | thunder-project/thunder | thunder/base.py | Data._reduce | def _reduce(self, func, axis=0):
"""
Reduce an array along an axis.
Applies an associative/commutative function of two arguments
cumulatively to all arrays along an axis. Array will be aligned
so that the desired set of axes are in the keys, which may
require a transpose... | python | def _reduce(self, func, axis=0):
"""
Reduce an array along an axis.
Applies an associative/commutative function of two arguments
cumulatively to all arrays along an axis. Array will be aligned
so that the desired set of axes are in the keys, which may
require a transpose... | [
"def",
"_reduce",
"(",
"self",
",",
"func",
",",
"axis",
"=",
"0",
")",
":",
"if",
"self",
".",
"mode",
"==",
"'local'",
":",
"axes",
"=",
"sorted",
"(",
"tupleize",
"(",
"axis",
")",
")",
"# if the function is a ufunc, it can automatically handle reducing ove... | Reduce an array along an axis.
Applies an associative/commutative function of two arguments
cumulatively to all arrays along an axis. Array will be aligned
so that the desired set of axes are in the keys, which may
require a transpose/reshape.
Parameters
----------
... | [
"Reduce",
"an",
"array",
"along",
"an",
"axis",
"."
] | 967ff8f3e7c2fabe1705743d95eb2746d4329786 | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/base.py#L471-L508 |
12,275 | thunder-project/thunder | thunder/base.py | Data.element_wise | def element_wise(self, other, op):
"""
Apply an elementwise operation to data.
Both self and other data must have the same mode.
If self is in local mode, other can also be a numpy array.
Self and other must have the same shape, or other must be a scalar.
Parameters
... | python | def element_wise(self, other, op):
"""
Apply an elementwise operation to data.
Both self and other data must have the same mode.
If self is in local mode, other can also be a numpy array.
Self and other must have the same shape, or other must be a scalar.
Parameters
... | [
"def",
"element_wise",
"(",
"self",
",",
"other",
",",
"op",
")",
":",
"if",
"not",
"isscalar",
"(",
"other",
")",
"and",
"not",
"self",
".",
"shape",
"==",
"other",
".",
"shape",
":",
"raise",
"ValueError",
"(",
"\"shapes %s and %s must be equal\"",
"%",
... | Apply an elementwise operation to data.
Both self and other data must have the same mode.
If self is in local mode, other can also be a numpy array.
Self and other must have the same shape, or other must be a scalar.
Parameters
----------
other : Data or numpy array
... | [
"Apply",
"an",
"elementwise",
"operation",
"to",
"data",
"."
] | 967ff8f3e7c2fabe1705743d95eb2746d4329786 | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/base.py#L510-L549 |
12,276 | thunder-project/thunder | thunder/base.py | Data.clip | def clip(self, min=None, max=None):
"""
Clip values above and below.
Parameters
----------
min : scalar or array-like
Minimum value. If array, will be broadcasted
max : scalar or array-like
Maximum value. If array, will be broadcasted.
""... | python | def clip(self, min=None, max=None):
"""
Clip values above and below.
Parameters
----------
min : scalar or array-like
Minimum value. If array, will be broadcasted
max : scalar or array-like
Maximum value. If array, will be broadcasted.
""... | [
"def",
"clip",
"(",
"self",
",",
"min",
"=",
"None",
",",
"max",
"=",
"None",
")",
":",
"return",
"self",
".",
"_constructor",
"(",
"self",
".",
"values",
".",
"clip",
"(",
"min",
"=",
"min",
",",
"max",
"=",
"max",
")",
")",
".",
"__finalize__",... | Clip values above and below.
Parameters
----------
min : scalar or array-like
Minimum value. If array, will be broadcasted
max : scalar or array-like
Maximum value. If array, will be broadcasted. | [
"Clip",
"values",
"above",
"and",
"below",
"."
] | 967ff8f3e7c2fabe1705743d95eb2746d4329786 | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/base.py#L575-L588 |
12,277 | thunder-project/thunder | thunder/series/readers.py | fromrdd | def fromrdd(rdd, nrecords=None, shape=None, index=None, labels=None, dtype=None, ordered=False):
"""
Load series data from a Spark RDD.
Assumes keys are tuples with increasing and unique indices,
and values are 1d ndarrays. Will try to infer properties
that are not explicitly provided.
Paramet... | python | def fromrdd(rdd, nrecords=None, shape=None, index=None, labels=None, dtype=None, ordered=False):
"""
Load series data from a Spark RDD.
Assumes keys are tuples with increasing and unique indices,
and values are 1d ndarrays. Will try to infer properties
that are not explicitly provided.
Paramet... | [
"def",
"fromrdd",
"(",
"rdd",
",",
"nrecords",
"=",
"None",
",",
"shape",
"=",
"None",
",",
"index",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"ordered",
"=",
"False",
")",
":",
"from",
".",
"series",
"import",
"Serie... | Load series data from a Spark RDD.
Assumes keys are tuples with increasing and unique indices,
and values are 1d ndarrays. Will try to infer properties
that are not explicitly provided.
Parameters
----------
rdd : SparkRDD
An RDD containing series data.
shape : tuple or array, opt... | [
"Load",
"series",
"data",
"from",
"a",
"Spark",
"RDD",
"."
] | 967ff8f3e7c2fabe1705743d95eb2746d4329786 | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/series/readers.py#L13-L72 |
12,278 | thunder-project/thunder | thunder/series/readers.py | fromarray | def fromarray(values, index=None, labels=None, npartitions=None, engine=None):
"""
Load series data from an array.
Assumes that all but final dimension index the records,
and the size of the final dimension is the length of each record,
e.g. a (2, 3, 4) array will be treated as 2 x 3 records of siz... | python | def fromarray(values, index=None, labels=None, npartitions=None, engine=None):
"""
Load series data from an array.
Assumes that all but final dimension index the records,
and the size of the final dimension is the length of each record,
e.g. a (2, 3, 4) array will be treated as 2 x 3 records of siz... | [
"def",
"fromarray",
"(",
"values",
",",
"index",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"npartitions",
"=",
"None",
",",
"engine",
"=",
"None",
")",
":",
"from",
".",
"series",
"import",
"Series",
"import",
"bolt",
"if",
"isinstance",
"(",
"valu... | Load series data from an array.
Assumes that all but final dimension index the records,
and the size of the final dimension is the length of each record,
e.g. a (2, 3, 4) array will be treated as 2 x 3 records of size (4,)
Parameters
----------
values : array-like
An array containing t... | [
"Load",
"series",
"data",
"from",
"an",
"array",
"."
] | 967ff8f3e7c2fabe1705743d95eb2746d4329786 | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/series/readers.py#L74-L124 |
12,279 | thunder-project/thunder | thunder/series/readers.py | fromlist | def fromlist(items, accessor=None, index=None, labels=None, dtype=None, npartitions=None, engine=None):
"""
Load series data from a list with an optional accessor function.
Will call accessor function on each item from the list,
providing a generic interface for data loading.
Parameters
------... | python | def fromlist(items, accessor=None, index=None, labels=None, dtype=None, npartitions=None, engine=None):
"""
Load series data from a list with an optional accessor function.
Will call accessor function on each item from the list,
providing a generic interface for data loading.
Parameters
------... | [
"def",
"fromlist",
"(",
"items",
",",
"accessor",
"=",
"None",
",",
"index",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"npartitions",
"=",
"None",
",",
"engine",
"=",
"None",
")",
":",
"if",
"spark",
"and",
"isinstance"... | Load series data from a list with an optional accessor function.
Will call accessor function on each item from the list,
providing a generic interface for data loading.
Parameters
----------
items : list
A list of items to load.
accessor : function, optional, default = None
A ... | [
"Load",
"series",
"data",
"from",
"a",
"list",
"with",
"an",
"optional",
"accessor",
"function",
"."
] | 967ff8f3e7c2fabe1705743d95eb2746d4329786 | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/series/readers.py#L126-L173 |
12,280 | thunder-project/thunder | thunder/series/readers.py | fromtext | def fromtext(path, ext='txt', dtype='float64', skip=0, shape=None, index=None, labels=None, npartitions=None, engine=None, credentials=None):
"""
Loads series data from text files.
Assumes data are formatted as rows, where each record is a row
of numbers separated by spaces e.g. 'v v v v v'. You can
... | python | def fromtext(path, ext='txt', dtype='float64', skip=0, shape=None, index=None, labels=None, npartitions=None, engine=None, credentials=None):
"""
Loads series data from text files.
Assumes data are formatted as rows, where each record is a row
of numbers separated by spaces e.g. 'v v v v v'. You can
... | [
"def",
"fromtext",
"(",
"path",
",",
"ext",
"=",
"'txt'",
",",
"dtype",
"=",
"'float64'",
",",
"skip",
"=",
"0",
",",
"shape",
"=",
"None",
",",
"index",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"npartitions",
"=",
"None",
",",
"engine",
"=",
... | Loads series data from text files.
Assumes data are formatted as rows, where each record is a row
of numbers separated by spaces e.g. 'v v v v v'. You can
optionally specify a fixed number of initial items per row to skip / discard.
Parameters
----------
path : string
Directory to load... | [
"Loads",
"series",
"data",
"from",
"text",
"files",
"."
] | 967ff8f3e7c2fabe1705743d95eb2746d4329786 | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/series/readers.py#L175-L252 |
12,281 | thunder-project/thunder | thunder/series/readers.py | frombinary | def frombinary(path, ext='bin', conf='conf.json', dtype=None, shape=None, skip=0, index=None, labels=None, engine=None, credentials=None):
"""
Load series data from flat binary files.
Parameters
----------
path : string URI or local filesystem path
Directory to load from, can be a URI strin... | python | def frombinary(path, ext='bin', conf='conf.json', dtype=None, shape=None, skip=0, index=None, labels=None, engine=None, credentials=None):
"""
Load series data from flat binary files.
Parameters
----------
path : string URI or local filesystem path
Directory to load from, can be a URI strin... | [
"def",
"frombinary",
"(",
"path",
",",
"ext",
"=",
"'bin'",
",",
"conf",
"=",
"'conf.json'",
",",
"dtype",
"=",
"None",
",",
"shape",
"=",
"None",
",",
"skip",
"=",
"0",
",",
"index",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"engine",
"=",
"... | Load series data from flat binary files.
Parameters
----------
path : string URI or local filesystem path
Directory to load from, can be a URI string with scheme
(e.g. 'file://', 's3n://', or 'gs://'), or a single file,
or a directory, or a directory with a single wildcard character... | [
"Load",
"series",
"data",
"from",
"flat",
"binary",
"files",
"."
] | 967ff8f3e7c2fabe1705743d95eb2746d4329786 | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/series/readers.py#L254-L342 |
12,282 | thunder-project/thunder | thunder/series/readers.py | _binaryconfig | def _binaryconfig(path, conf, dtype=None, shape=None, credentials=None):
"""
Collects parameters to use for binary series loading.
"""
import json
from thunder.readers import get_file_reader, FileNotFoundError
reader = get_file_reader(path)(credentials=credentials)
try:
buf = reader... | python | def _binaryconfig(path, conf, dtype=None, shape=None, credentials=None):
"""
Collects parameters to use for binary series loading.
"""
import json
from thunder.readers import get_file_reader, FileNotFoundError
reader = get_file_reader(path)(credentials=credentials)
try:
buf = reader... | [
"def",
"_binaryconfig",
"(",
"path",
",",
"conf",
",",
"dtype",
"=",
"None",
",",
"shape",
"=",
"None",
",",
"credentials",
"=",
"None",
")",
":",
"import",
"json",
"from",
"thunder",
".",
"readers",
"import",
"get_file_reader",
",",
"FileNotFoundError",
"... | Collects parameters to use for binary series loading. | [
"Collects",
"parameters",
"to",
"use",
"for",
"binary",
"series",
"loading",
"."
] | 967ff8f3e7c2fabe1705743d95eb2746d4329786 | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/series/readers.py#L344-L370 |
12,283 | thunder-project/thunder | thunder/series/readers.py | fromexample | def fromexample(name=None, engine=None):
"""
Load example series data.
Data are downloaded from S3, so this method requires an internet connection.
Parameters
----------
name : str
Name of dataset, options include 'iris' | 'mouse' | 'fish'.
If not specified will print options.
... | python | def fromexample(name=None, engine=None):
"""
Load example series data.
Data are downloaded from S3, so this method requires an internet connection.
Parameters
----------
name : str
Name of dataset, options include 'iris' | 'mouse' | 'fish'.
If not specified will print options.
... | [
"def",
"fromexample",
"(",
"name",
"=",
"None",
",",
"engine",
"=",
"None",
")",
":",
"import",
"os",
"import",
"tempfile",
"import",
"shutil",
"from",
"boto",
".",
"s3",
".",
"connection",
"import",
"S3Connection",
"datasets",
"=",
"[",
"'iris'",
",",
"... | Load example series data.
Data are downloaded from S3, so this method requires an internet connection.
Parameters
----------
name : str
Name of dataset, options include 'iris' | 'mouse' | 'fish'.
If not specified will print options.
engine : object, default = None
Computat... | [
"Load",
"example",
"series",
"data",
"."
] | 967ff8f3e7c2fabe1705743d95eb2746d4329786 | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/series/readers.py#L398-L447 |
12,284 | thunder-project/thunder | thunder/series/writers.py | tobinary | def tobinary(series, path, prefix='series', overwrite=False, credentials=None):
"""
Writes out data to binary format.
Parameters
----------
series : Series
The data to write
path : string path or URI to directory to be created
Output files will be written underneath path.
... | python | def tobinary(series, path, prefix='series', overwrite=False, credentials=None):
"""
Writes out data to binary format.
Parameters
----------
series : Series
The data to write
path : string path or URI to directory to be created
Output files will be written underneath path.
... | [
"def",
"tobinary",
"(",
"series",
",",
"path",
",",
"prefix",
"=",
"'series'",
",",
"overwrite",
"=",
"False",
",",
"credentials",
"=",
"None",
")",
":",
"from",
"six",
"import",
"BytesIO",
"from",
"thunder",
".",
"utils",
"import",
"check_path",
"from",
... | Writes out data to binary format.
Parameters
----------
series : Series
The data to write
path : string path or URI to directory to be created
Output files will be written underneath path.
Directory will be created as a result of this call.
prefix : str, optional, default ... | [
"Writes",
"out",
"data",
"to",
"binary",
"format",
"."
] | 967ff8f3e7c2fabe1705743d95eb2746d4329786 | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/series/writers.py#L3-L65 |
12,285 | thunder-project/thunder | thunder/series/writers.py | write_config | def write_config(path, shape=None, dtype=None, name="conf.json", overwrite=True, credentials=None):
"""
Write a conf.json file with required information to load Series binary data.
"""
import json
from thunder.writers import get_file_writer
writer = get_file_writer(path)
conf = {'shape': sh... | python | def write_config(path, shape=None, dtype=None, name="conf.json", overwrite=True, credentials=None):
"""
Write a conf.json file with required information to load Series binary data.
"""
import json
from thunder.writers import get_file_writer
writer = get_file_writer(path)
conf = {'shape': sh... | [
"def",
"write_config",
"(",
"path",
",",
"shape",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"name",
"=",
"\"conf.json\"",
",",
"overwrite",
"=",
"True",
",",
"credentials",
"=",
"None",
")",
":",
"import",
"json",
"from",
"thunder",
".",
"writers",
... | Write a conf.json file with required information to load Series binary data. | [
"Write",
"a",
"conf",
".",
"json",
"file",
"with",
"required",
"information",
"to",
"load",
"Series",
"binary",
"data",
"."
] | 967ff8f3e7c2fabe1705743d95eb2746d4329786 | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/series/writers.py#L67-L81 |
12,286 | thunder-project/thunder | thunder/images/images.py | Images.toblocks | def toblocks(self, chunk_size='auto', padding=None):
"""
Convert to blocks which represent subdivisions of the images data.
Parameters
----------
chunk_size : str or tuple, size of image chunk used during conversion, default = 'auto'
String interpreted as memory size... | python | def toblocks(self, chunk_size='auto', padding=None):
"""
Convert to blocks which represent subdivisions of the images data.
Parameters
----------
chunk_size : str or tuple, size of image chunk used during conversion, default = 'auto'
String interpreted as memory size... | [
"def",
"toblocks",
"(",
"self",
",",
"chunk_size",
"=",
"'auto'",
",",
"padding",
"=",
"None",
")",
":",
"from",
"thunder",
".",
"blocks",
".",
"blocks",
"import",
"Blocks",
"from",
"thunder",
".",
"blocks",
".",
"local",
"import",
"LocalChunks",
"if",
"... | Convert to blocks which represent subdivisions of the images data.
Parameters
----------
chunk_size : str or tuple, size of image chunk used during conversion, default = 'auto'
String interpreted as memory size (in kilobytes, e.g. '64').
The exception is the string 'auto... | [
"Convert",
"to",
"blocks",
"which",
"represent",
"subdivisions",
"of",
"the",
"images",
"data",
"."
] | 967ff8f3e7c2fabe1705743d95eb2746d4329786 | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/images/images.py#L60-L89 |
12,287 | thunder-project/thunder | thunder/images/images.py | Images.toseries | def toseries(self, chunk_size='auto'):
"""
Converts to series data.
This method is equivalent to images.toblocks(size).toSeries().
Parameters
----------
chunk_size : str or tuple, size of image chunk used during conversion, default = 'auto'
String interprete... | python | def toseries(self, chunk_size='auto'):
"""
Converts to series data.
This method is equivalent to images.toblocks(size).toSeries().
Parameters
----------
chunk_size : str or tuple, size of image chunk used during conversion, default = 'auto'
String interprete... | [
"def",
"toseries",
"(",
"self",
",",
"chunk_size",
"=",
"'auto'",
")",
":",
"from",
"thunder",
".",
"series",
".",
"series",
"import",
"Series",
"if",
"chunk_size",
"is",
"'auto'",
":",
"chunk_size",
"=",
"str",
"(",
"max",
"(",
"[",
"int",
"(",
"1e5",... | Converts to series data.
This method is equivalent to images.toblocks(size).toSeries().
Parameters
----------
chunk_size : str or tuple, size of image chunk used during conversion, default = 'auto'
String interpreted as memory size (in kilobytes, e.g. '64').
The... | [
"Converts",
"to",
"series",
"data",
"."
] | 967ff8f3e7c2fabe1705743d95eb2746d4329786 | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/images/images.py#L91-L117 |
12,288 | thunder-project/thunder | thunder/images/images.py | Images.tospark | def tospark(self, engine=None):
"""
Convert to distributed spark mode.
"""
from thunder.images.readers import fromarray
if self.mode == 'spark':
logging.getLogger('thunder').warn('images already in spark mode')
pass
if engine is None:
... | python | def tospark(self, engine=None):
"""
Convert to distributed spark mode.
"""
from thunder.images.readers import fromarray
if self.mode == 'spark':
logging.getLogger('thunder').warn('images already in spark mode')
pass
if engine is None:
... | [
"def",
"tospark",
"(",
"self",
",",
"engine",
"=",
"None",
")",
":",
"from",
"thunder",
".",
"images",
".",
"readers",
"import",
"fromarray",
"if",
"self",
".",
"mode",
"==",
"'spark'",
":",
"logging",
".",
"getLogger",
"(",
"'thunder'",
")",
".",
"war... | Convert to distributed spark mode. | [
"Convert",
"to",
"distributed",
"spark",
"mode",
"."
] | 967ff8f3e7c2fabe1705743d95eb2746d4329786 | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/images/images.py#L131-L144 |
12,289 | thunder-project/thunder | thunder/images/images.py | Images.foreach | def foreach(self, func):
"""
Execute a function on each image.
Functions can have side effects. There is no return value.
"""
if self.mode == 'spark':
self.values.tordd().map(lambda kv: (kv[0][0], kv[1])).foreach(func)
else:
[func(kv) for kv in en... | python | def foreach(self, func):
"""
Execute a function on each image.
Functions can have side effects. There is no return value.
"""
if self.mode == 'spark':
self.values.tordd().map(lambda kv: (kv[0][0], kv[1])).foreach(func)
else:
[func(kv) for kv in en... | [
"def",
"foreach",
"(",
"self",
",",
"func",
")",
":",
"if",
"self",
".",
"mode",
"==",
"'spark'",
":",
"self",
".",
"values",
".",
"tordd",
"(",
")",
".",
"map",
"(",
"lambda",
"kv",
":",
"(",
"kv",
"[",
"0",
"]",
"[",
"0",
"]",
",",
"kv",
... | Execute a function on each image.
Functions can have side effects. There is no return value. | [
"Execute",
"a",
"function",
"on",
"each",
"image",
"."
] | 967ff8f3e7c2fabe1705743d95eb2746d4329786 | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/images/images.py#L146-L155 |
12,290 | thunder-project/thunder | thunder/images/images.py | Images.sample | def sample(self, nsamples=100, seed=None):
"""
Extract a random sample of images.
Parameters
----------
nsamples : int, optional, default = 100
The number of data points to sample.
seed : int, optional, default = None
Random seed.
"""
... | python | def sample(self, nsamples=100, seed=None):
"""
Extract a random sample of images.
Parameters
----------
nsamples : int, optional, default = 100
The number of data points to sample.
seed : int, optional, default = None
Random seed.
"""
... | [
"def",
"sample",
"(",
"self",
",",
"nsamples",
"=",
"100",
",",
"seed",
"=",
"None",
")",
":",
"if",
"nsamples",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"\"Number of samples must be larger than 0, got '%g'\"",
"%",
"nsamples",
")",
"if",
"seed",
"is",
"No... | Extract a random sample of images.
Parameters
----------
nsamples : int, optional, default = 100
The number of data points to sample.
seed : int, optional, default = None
Random seed. | [
"Extract",
"a",
"random",
"sample",
"of",
"images",
"."
] | 967ff8f3e7c2fabe1705743d95eb2746d4329786 | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/images/images.py#L157-L182 |
12,291 | thunder-project/thunder | thunder/images/images.py | Images.var | def var(self):
"""
Compute the variance across images.
"""
return self._constructor(self.values.var(axis=0, keepdims=True)) | python | def var(self):
"""
Compute the variance across images.
"""
return self._constructor(self.values.var(axis=0, keepdims=True)) | [
"def",
"var",
"(",
"self",
")",
":",
"return",
"self",
".",
"_constructor",
"(",
"self",
".",
"values",
".",
"var",
"(",
"axis",
"=",
"0",
",",
"keepdims",
"=",
"True",
")",
")"
] | Compute the variance across images. | [
"Compute",
"the",
"variance",
"across",
"images",
"."
] | 967ff8f3e7c2fabe1705743d95eb2746d4329786 | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/images/images.py#L201-L205 |
12,292 | thunder-project/thunder | thunder/images/images.py | Images.std | def std(self):
"""
Compute the standard deviation across images.
"""
return self._constructor(self.values.std(axis=0, keepdims=True)) | python | def std(self):
"""
Compute the standard deviation across images.
"""
return self._constructor(self.values.std(axis=0, keepdims=True)) | [
"def",
"std",
"(",
"self",
")",
":",
"return",
"self",
".",
"_constructor",
"(",
"self",
".",
"values",
".",
"std",
"(",
"axis",
"=",
"0",
",",
"keepdims",
"=",
"True",
")",
")"
] | Compute the standard deviation across images. | [
"Compute",
"the",
"standard",
"deviation",
"across",
"images",
"."
] | 967ff8f3e7c2fabe1705743d95eb2746d4329786 | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/images/images.py#L207-L211 |
12,293 | thunder-project/thunder | thunder/images/images.py | Images.squeeze | def squeeze(self):
"""
Remove single-dimensional axes from images.
"""
axis = tuple(range(1, len(self.shape) - 1)) if prod(self.shape[1:]) == 1 else None
return self.map(lambda x: x.squeeze(axis=axis)) | python | def squeeze(self):
"""
Remove single-dimensional axes from images.
"""
axis = tuple(range(1, len(self.shape) - 1)) if prod(self.shape[1:]) == 1 else None
return self.map(lambda x: x.squeeze(axis=axis)) | [
"def",
"squeeze",
"(",
"self",
")",
":",
"axis",
"=",
"tuple",
"(",
"range",
"(",
"1",
",",
"len",
"(",
"self",
".",
"shape",
")",
"-",
"1",
")",
")",
"if",
"prod",
"(",
"self",
".",
"shape",
"[",
"1",
":",
"]",
")",
"==",
"1",
"else",
"Non... | Remove single-dimensional axes from images. | [
"Remove",
"single",
"-",
"dimensional",
"axes",
"from",
"images",
"."
] | 967ff8f3e7c2fabe1705743d95eb2746d4329786 | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/images/images.py#L231-L236 |
12,294 | thunder-project/thunder | thunder/images/images.py | Images.max_projection | def max_projection(self, axis=2):
"""
Compute maximum projections of images along a dimension.
Parameters
----------
axis : int, optional, default = 2
Which axis to compute projection along.
"""
if axis >= size(self.value_shape):
raise Exc... | python | def max_projection(self, axis=2):
"""
Compute maximum projections of images along a dimension.
Parameters
----------
axis : int, optional, default = 2
Which axis to compute projection along.
"""
if axis >= size(self.value_shape):
raise Exc... | [
"def",
"max_projection",
"(",
"self",
",",
"axis",
"=",
"2",
")",
":",
"if",
"axis",
">=",
"size",
"(",
"self",
".",
"value_shape",
")",
":",
"raise",
"Exception",
"(",
"'Axis for projection (%s) exceeds '",
"'image dimensions (%s-%s)'",
"%",
"(",
"axis",
",",... | Compute maximum projections of images along a dimension.
Parameters
----------
axis : int, optional, default = 2
Which axis to compute projection along. | [
"Compute",
"maximum",
"projections",
"of",
"images",
"along",
"a",
"dimension",
"."
] | 967ff8f3e7c2fabe1705743d95eb2746d4329786 | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/images/images.py#L258-L273 |
12,295 | thunder-project/thunder | thunder/images/images.py | Images.max_min_projection | def max_min_projection(self, axis=2):
"""
Compute maximum-minimum projection along a dimension.
This computes the sum of the maximum and minimum values.
Parameters
----------
axis : int, optional, default = 2
Which axis to compute projection along.
"... | python | def max_min_projection(self, axis=2):
"""
Compute maximum-minimum projection along a dimension.
This computes the sum of the maximum and minimum values.
Parameters
----------
axis : int, optional, default = 2
Which axis to compute projection along.
"... | [
"def",
"max_min_projection",
"(",
"self",
",",
"axis",
"=",
"2",
")",
":",
"if",
"axis",
">=",
"size",
"(",
"self",
".",
"value_shape",
")",
":",
"raise",
"Exception",
"(",
"'Axis for projection (%s) exceeds '",
"'image dimensions (%s-%s)'",
"%",
"(",
"axis",
... | Compute maximum-minimum projection along a dimension.
This computes the sum of the maximum and minimum values.
Parameters
----------
axis : int, optional, default = 2
Which axis to compute projection along. | [
"Compute",
"maximum",
"-",
"minimum",
"projection",
"along",
"a",
"dimension",
"."
] | 967ff8f3e7c2fabe1705743d95eb2746d4329786 | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/images/images.py#L275-L292 |
12,296 | thunder-project/thunder | thunder/images/images.py | Images.subsample | def subsample(self, factor):
"""
Downsample images by an integer factor.
Parameters
----------
factor : positive int or tuple of positive ints
Stride to use in subsampling. If a single int is passed,
each dimension of the image will be downsampled by this... | python | def subsample(self, factor):
"""
Downsample images by an integer factor.
Parameters
----------
factor : positive int or tuple of positive ints
Stride to use in subsampling. If a single int is passed,
each dimension of the image will be downsampled by this... | [
"def",
"subsample",
"(",
"self",
",",
"factor",
")",
":",
"value_shape",
"=",
"self",
".",
"value_shape",
"ndims",
"=",
"len",
"(",
"value_shape",
")",
"if",
"not",
"hasattr",
"(",
"factor",
",",
"'__len__'",
")",
":",
"factor",
"=",
"[",
"factor",
"]"... | Downsample images by an integer factor.
Parameters
----------
factor : positive int or tuple of positive ints
Stride to use in subsampling. If a single int is passed,
each dimension of the image will be downsampled by this factor.
If a tuple is passed, each d... | [
"Downsample",
"images",
"by",
"an",
"integer",
"factor",
"."
] | 967ff8f3e7c2fabe1705743d95eb2746d4329786 | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/images/images.py#L294-L320 |
12,297 | thunder-project/thunder | thunder/images/images.py | Images.gaussian_filter | def gaussian_filter(self, sigma=2, order=0):
"""
Spatially smooth images with a gaussian filter.
Filtering will be applied to every image in the collection.
Parameters
----------
sigma : scalar or sequence of scalars, default = 2
Size of the filter size as s... | python | def gaussian_filter(self, sigma=2, order=0):
"""
Spatially smooth images with a gaussian filter.
Filtering will be applied to every image in the collection.
Parameters
----------
sigma : scalar or sequence of scalars, default = 2
Size of the filter size as s... | [
"def",
"gaussian_filter",
"(",
"self",
",",
"sigma",
"=",
"2",
",",
"order",
"=",
"0",
")",
":",
"from",
"scipy",
".",
"ndimage",
".",
"filters",
"import",
"gaussian_filter",
"return",
"self",
".",
"map",
"(",
"lambda",
"v",
":",
"gaussian_filter",
"(",
... | Spatially smooth images with a gaussian filter.
Filtering will be applied to every image in the collection.
Parameters
----------
sigma : scalar or sequence of scalars, default = 2
Size of the filter size as standard deviation in pixels.
A sequence is interprete... | [
"Spatially",
"smooth",
"images",
"with",
"a",
"gaussian",
"filter",
"."
] | 967ff8f3e7c2fabe1705743d95eb2746d4329786 | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/images/images.py#L322-L341 |
12,298 | thunder-project/thunder | thunder/images/images.py | Images._image_filter | def _image_filter(self, filter=None, size=2):
"""
Generic function for maping a filtering operation over images.
Parameters
----------
filter : string
Which filter to use.
size : int or tuple
Size parameter for filter.
"""
from nu... | python | def _image_filter(self, filter=None, size=2):
"""
Generic function for maping a filtering operation over images.
Parameters
----------
filter : string
Which filter to use.
size : int or tuple
Size parameter for filter.
"""
from nu... | [
"def",
"_image_filter",
"(",
"self",
",",
"filter",
"=",
"None",
",",
"size",
"=",
"2",
")",
":",
"from",
"numpy",
"import",
"isscalar",
"from",
"scipy",
".",
"ndimage",
".",
"filters",
"import",
"median_filter",
",",
"uniform_filter",
"FILTERS",
"=",
"{",... | Generic function for maping a filtering operation over images.
Parameters
----------
filter : string
Which filter to use.
size : int or tuple
Size parameter for filter. | [
"Generic",
"function",
"for",
"maping",
"a",
"filtering",
"operation",
"over",
"images",
"."
] | 967ff8f3e7c2fabe1705743d95eb2746d4329786 | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/images/images.py#L373-L414 |
12,299 | thunder-project/thunder | thunder/images/images.py | Images.localcorr | def localcorr(self, size=2):
"""
Correlate every pixel in an image sequence to the average of its local neighborhood.
This algorithm computes, for every pixel, the correlation coefficient
between the sequence of values for that pixel, and the average of all pixels
in a local nei... | python | def localcorr(self, size=2):
"""
Correlate every pixel in an image sequence to the average of its local neighborhood.
This algorithm computes, for every pixel, the correlation coefficient
between the sequence of values for that pixel, and the average of all pixels
in a local nei... | [
"def",
"localcorr",
"(",
"self",
",",
"size",
"=",
"2",
")",
":",
"from",
"thunder",
".",
"images",
".",
"readers",
"import",
"fromarray",
",",
"fromrdd",
"from",
"numpy",
"import",
"corrcoef",
",",
"concatenate",
"nimages",
"=",
"self",
".",
"shape",
"[... | Correlate every pixel in an image sequence to the average of its local neighborhood.
This algorithm computes, for every pixel, the correlation coefficient
between the sequence of values for that pixel, and the average of all pixels
in a local neighborhood. It does this by blurring the image(s) ... | [
"Correlate",
"every",
"pixel",
"in",
"an",
"image",
"sequence",
"to",
"the",
"average",
"of",
"its",
"local",
"neighborhood",
"."
] | 967ff8f3e7c2fabe1705743d95eb2746d4329786 | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/images/images.py#L416-L454 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.