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 listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
ajslater/picopt | picopt/stats.py | skip | def skip(type_name, filename):
"""Provide reporting statistics for a skipped file."""
report = ['Skipping {} file: {}'.format(type_name, filename)]
report_stats = ReportStats(filename, report=report)
return report_stats | python | def skip(type_name, filename):
"""Provide reporting statistics for a skipped file."""
report = ['Skipping {} file: {}'.format(type_name, filename)]
report_stats = ReportStats(filename, report=report)
return report_stats | [
"def",
"skip",
"(",
"type_name",
",",
"filename",
")",
":",
"report",
"=",
"[",
"'Skipping {} file: {}'",
".",
"format",
"(",
"type_name",
",",
"filename",
")",
"]",
"report_stats",
"=",
"ReportStats",
"(",
"filename",
",",
"report",
"=",
"report",
")",
"r... | Provide reporting statistics for a skipped file. | [
"Provide",
"reporting",
"statistics",
"for",
"a",
"skipped",
"file",
"."
] | 261da837027563c1dc3ed07b70e1086520a60402 | https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/stats.py#L183-L187 | train | 42,500 |
ajslater/picopt | picopt/formats/gif.py | gifsicle | def gifsicle(ext_args):
"""Run the EXTERNAL program gifsicle."""
args = _GIFSICLE_ARGS + [ext_args.new_filename]
extern.run_ext(args)
return _GIF_FORMAT | python | def gifsicle(ext_args):
"""Run the EXTERNAL program gifsicle."""
args = _GIFSICLE_ARGS + [ext_args.new_filename]
extern.run_ext(args)
return _GIF_FORMAT | [
"def",
"gifsicle",
"(",
"ext_args",
")",
":",
"args",
"=",
"_GIFSICLE_ARGS",
"+",
"[",
"ext_args",
".",
"new_filename",
"]",
"extern",
".",
"run_ext",
"(",
"args",
")",
"return",
"_GIF_FORMAT"
] | Run the EXTERNAL program gifsicle. | [
"Run",
"the",
"EXTERNAL",
"program",
"gifsicle",
"."
] | 261da837027563c1dc3ed07b70e1086520a60402 | https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/formats/gif.py#L14-L18 | train | 42,501 |
ajslater/picopt | picopt/optimize.py | _optimize_image_external | def _optimize_image_external(filename, func, image_format, new_ext):
"""Optimize the file with the external function."""
new_filename = filename + TMP_SUFFIX + new_ext
new_filename = os.path.normpath(new_filename)
shutil.copy2(filename, new_filename)
ext_args = ExtArgs(filename, new_filename)
new_image_format = func(ext_args)
report_stats = files.cleanup_after_optimize(filename, new_filename,
image_format,
new_image_format)
percent = stats.new_percent_saved(report_stats)
if percent != 0:
report = '{}: {}'.format(func.__name__, percent)
else:
report = ''
report_stats.report_list.append(report)
return report_stats | python | def _optimize_image_external(filename, func, image_format, new_ext):
"""Optimize the file with the external function."""
new_filename = filename + TMP_SUFFIX + new_ext
new_filename = os.path.normpath(new_filename)
shutil.copy2(filename, new_filename)
ext_args = ExtArgs(filename, new_filename)
new_image_format = func(ext_args)
report_stats = files.cleanup_after_optimize(filename, new_filename,
image_format,
new_image_format)
percent = stats.new_percent_saved(report_stats)
if percent != 0:
report = '{}: {}'.format(func.__name__, percent)
else:
report = ''
report_stats.report_list.append(report)
return report_stats | [
"def",
"_optimize_image_external",
"(",
"filename",
",",
"func",
",",
"image_format",
",",
"new_ext",
")",
":",
"new_filename",
"=",
"filename",
"+",
"TMP_SUFFIX",
"+",
"new_ext",
"new_filename",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"new_filename",
")... | Optimize the file with the external function. | [
"Optimize",
"the",
"file",
"with",
"the",
"external",
"function",
"."
] | 261da837027563c1dc3ed07b70e1086520a60402 | https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/optimize.py#L19-L38 | train | 42,502 |
ajslater/picopt | picopt/optimize.py | _optimize_with_progs | def _optimize_with_progs(format_module, filename, image_format):
"""
Use the correct optimizing functions in sequence.
And report back statistics.
"""
filesize_in = os.stat(filename).st_size
report_stats = None
for func in format_module.PROGRAMS:
if not getattr(Settings, func.__name__):
continue
report_stats = _optimize_image_external(
filename, func, image_format, format_module.OUT_EXT)
filename = report_stats.final_filename
if format_module.BEST_ONLY:
break
if report_stats is not None:
report_stats.bytes_in = filesize_in
else:
report_stats = stats.skip(image_format, filename)
return report_stats | python | def _optimize_with_progs(format_module, filename, image_format):
"""
Use the correct optimizing functions in sequence.
And report back statistics.
"""
filesize_in = os.stat(filename).st_size
report_stats = None
for func in format_module.PROGRAMS:
if not getattr(Settings, func.__name__):
continue
report_stats = _optimize_image_external(
filename, func, image_format, format_module.OUT_EXT)
filename = report_stats.final_filename
if format_module.BEST_ONLY:
break
if report_stats is not None:
report_stats.bytes_in = filesize_in
else:
report_stats = stats.skip(image_format, filename)
return report_stats | [
"def",
"_optimize_with_progs",
"(",
"format_module",
",",
"filename",
",",
"image_format",
")",
":",
"filesize_in",
"=",
"os",
".",
"stat",
"(",
"filename",
")",
".",
"st_size",
"report_stats",
"=",
"None",
"for",
"func",
"in",
"format_module",
".",
"PROGRAMS"... | Use the correct optimizing functions in sequence.
And report back statistics. | [
"Use",
"the",
"correct",
"optimizing",
"functions",
"in",
"sequence",
"."
] | 261da837027563c1dc3ed07b70e1086520a60402 | https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/optimize.py#L41-L64 | train | 42,503 |
ajslater/picopt | picopt/optimize.py | _get_format_module | def _get_format_module(image_format):
"""Get the format module to use for optimizing the image."""
format_module = None
nag_about_gifs = False
if detect_format.is_format_selected(image_format,
Settings.to_png_formats,
png.PROGRAMS):
format_module = png
elif detect_format.is_format_selected(image_format, jpeg.FORMATS,
jpeg.PROGRAMS):
format_module = jpeg
elif detect_format.is_format_selected(image_format, gif.FORMATS,
gif.PROGRAMS):
# this captures still GIFs too if not caught above
format_module = gif
nag_about_gifs = True
return format_module, nag_about_gifs | python | def _get_format_module(image_format):
"""Get the format module to use for optimizing the image."""
format_module = None
nag_about_gifs = False
if detect_format.is_format_selected(image_format,
Settings.to_png_formats,
png.PROGRAMS):
format_module = png
elif detect_format.is_format_selected(image_format, jpeg.FORMATS,
jpeg.PROGRAMS):
format_module = jpeg
elif detect_format.is_format_selected(image_format, gif.FORMATS,
gif.PROGRAMS):
# this captures still GIFs too if not caught above
format_module = gif
nag_about_gifs = True
return format_module, nag_about_gifs | [
"def",
"_get_format_module",
"(",
"image_format",
")",
":",
"format_module",
"=",
"None",
"nag_about_gifs",
"=",
"False",
"if",
"detect_format",
".",
"is_format_selected",
"(",
"image_format",
",",
"Settings",
".",
"to_png_formats",
",",
"png",
".",
"PROGRAMS",
")... | Get the format module to use for optimizing the image. | [
"Get",
"the",
"format",
"module",
"to",
"use",
"for",
"optimizing",
"the",
"image",
"."
] | 261da837027563c1dc3ed07b70e1086520a60402 | https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/optimize.py#L67-L85 | train | 42,504 |
ajslater/picopt | picopt/optimize.py | optimize_image | def optimize_image(arg):
"""Optimize a given image from a filename."""
try:
filename, image_format, settings = arg
Settings.update(settings)
format_module, nag_about_gifs = _get_format_module(image_format)
if format_module is None:
if Settings.verbose > 1:
print(filename, image_format) # image.mode)
print("\tFile format not selected.")
return None
report_stats = _optimize_with_progs(format_module, filename,
image_format)
report_stats.nag_about_gifs = nag_about_gifs
stats.report_saved(report_stats)
return report_stats
except Exception as exc:
print(exc)
traceback.print_exc()
return stats.ReportStats(filename, error="Optimizing Image") | python | def optimize_image(arg):
"""Optimize a given image from a filename."""
try:
filename, image_format, settings = arg
Settings.update(settings)
format_module, nag_about_gifs = _get_format_module(image_format)
if format_module is None:
if Settings.verbose > 1:
print(filename, image_format) # image.mode)
print("\tFile format not selected.")
return None
report_stats = _optimize_with_progs(format_module, filename,
image_format)
report_stats.nag_about_gifs = nag_about_gifs
stats.report_saved(report_stats)
return report_stats
except Exception as exc:
print(exc)
traceback.print_exc()
return stats.ReportStats(filename, error="Optimizing Image") | [
"def",
"optimize_image",
"(",
"arg",
")",
":",
"try",
":",
"filename",
",",
"image_format",
",",
"settings",
"=",
"arg",
"Settings",
".",
"update",
"(",
"settings",
")",
"format_module",
",",
"nag_about_gifs",
"=",
"_get_format_module",
"(",
"image_format",
")... | Optimize a given image from a filename. | [
"Optimize",
"a",
"given",
"image",
"from",
"a",
"filename",
"."
] | 261da837027563c1dc3ed07b70e1086520a60402 | https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/optimize.py#L88-L111 | train | 42,505 |
ajslater/picopt | picopt/detect_format.py | _is_program_selected | def _is_program_selected(progs):
"""Determine if the program is enabled in the settings."""
mode = False
for prog in progs:
if getattr(Settings, prog.__name__):
mode = True
break
return mode | python | def _is_program_selected(progs):
"""Determine if the program is enabled in the settings."""
mode = False
for prog in progs:
if getattr(Settings, prog.__name__):
mode = True
break
return mode | [
"def",
"_is_program_selected",
"(",
"progs",
")",
":",
"mode",
"=",
"False",
"for",
"prog",
"in",
"progs",
":",
"if",
"getattr",
"(",
"Settings",
",",
"prog",
".",
"__name__",
")",
":",
"mode",
"=",
"True",
"break",
"return",
"mode"
] | Determine if the program is enabled in the settings. | [
"Determine",
"if",
"the",
"program",
"is",
"enabled",
"in",
"the",
"settings",
"."
] | 261da837027563c1dc3ed07b70e1086520a60402 | https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/detect_format.py#L14-L21 | train | 42,506 |
ajslater/picopt | picopt/detect_format.py | is_format_selected | def is_format_selected(image_format, formats, progs):
"""Determine if the image format is selected by command line arguments."""
intersection = formats & Settings.formats
mode = _is_program_selected(progs)
result = (image_format in intersection) and mode
return result | python | def is_format_selected(image_format, formats, progs):
"""Determine if the image format is selected by command line arguments."""
intersection = formats & Settings.formats
mode = _is_program_selected(progs)
result = (image_format in intersection) and mode
return result | [
"def",
"is_format_selected",
"(",
"image_format",
",",
"formats",
",",
"progs",
")",
":",
"intersection",
"=",
"formats",
"&",
"Settings",
".",
"formats",
"mode",
"=",
"_is_program_selected",
"(",
"progs",
")",
"result",
"=",
"(",
"image_format",
"in",
"inters... | Determine if the image format is selected by command line arguments. | [
"Determine",
"if",
"the",
"image",
"format",
"is",
"selected",
"by",
"command",
"line",
"arguments",
"."
] | 261da837027563c1dc3ed07b70e1086520a60402 | https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/detect_format.py#L24-L29 | train | 42,507 |
ajslater/picopt | picopt/detect_format.py | _is_image_sequenced | def _is_image_sequenced(image):
"""Determine if the image is a sequenced image."""
try:
image.seek(1)
image.seek(0)
result = True
except EOFError:
result = False
return result | python | def _is_image_sequenced(image):
"""Determine if the image is a sequenced image."""
try:
image.seek(1)
image.seek(0)
result = True
except EOFError:
result = False
return result | [
"def",
"_is_image_sequenced",
"(",
"image",
")",
":",
"try",
":",
"image",
".",
"seek",
"(",
"1",
")",
"image",
".",
"seek",
"(",
"0",
")",
"result",
"=",
"True",
"except",
"EOFError",
":",
"result",
"=",
"False",
"return",
"result"
] | Determine if the image is a sequenced image. | [
"Determine",
"if",
"the",
"image",
"is",
"a",
"sequenced",
"image",
"."
] | 261da837027563c1dc3ed07b70e1086520a60402 | https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/detect_format.py#L32-L41 | train | 42,508 |
ajslater/picopt | picopt/detect_format.py | get_image_format | def get_image_format(filename):
"""Get the image format."""
image = None
bad_image = 1
image_format = NONE_FORMAT
sequenced = False
try:
bad_image = Image.open(filename).verify()
image = Image.open(filename)
image_format = image.format
sequenced = _is_image_sequenced(image)
except (OSError, IOError, AttributeError):
pass
if sequenced:
image_format = gif.SEQUENCED_TEMPLATE.format(image_format)
elif image is None or bad_image or image_format == NONE_FORMAT:
image_format = ERROR_FORMAT
comic_format = comic.get_comic_format(filename)
if comic_format:
image_format = comic_format
if (Settings.verbose > 1) and image_format == ERROR_FORMAT and \
(not Settings.list_only):
print(filename, "doesn't look like an image or comic archive.")
return image_format | python | def get_image_format(filename):
"""Get the image format."""
image = None
bad_image = 1
image_format = NONE_FORMAT
sequenced = False
try:
bad_image = Image.open(filename).verify()
image = Image.open(filename)
image_format = image.format
sequenced = _is_image_sequenced(image)
except (OSError, IOError, AttributeError):
pass
if sequenced:
image_format = gif.SEQUENCED_TEMPLATE.format(image_format)
elif image is None or bad_image or image_format == NONE_FORMAT:
image_format = ERROR_FORMAT
comic_format = comic.get_comic_format(filename)
if comic_format:
image_format = comic_format
if (Settings.verbose > 1) and image_format == ERROR_FORMAT and \
(not Settings.list_only):
print(filename, "doesn't look like an image or comic archive.")
return image_format | [
"def",
"get_image_format",
"(",
"filename",
")",
":",
"image",
"=",
"None",
"bad_image",
"=",
"1",
"image_format",
"=",
"NONE_FORMAT",
"sequenced",
"=",
"False",
"try",
":",
"bad_image",
"=",
"Image",
".",
"open",
"(",
"filename",
")",
".",
"verify",
"(",
... | Get the image format. | [
"Get",
"the",
"image",
"format",
"."
] | 261da837027563c1dc3ed07b70e1086520a60402 | https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/detect_format.py#L44-L68 | train | 42,509 |
ajslater/picopt | picopt/detect_format.py | detect_file | def detect_file(filename):
"""Decide what to do with the file."""
image_format = get_image_format(filename)
if image_format in Settings.formats:
return image_format
if image_format in (NONE_FORMAT, ERROR_FORMAT):
return None
if Settings.verbose > 1 and not Settings.list_only:
print(filename, image_format, 'is not a enabled image or '
'comic archive type.')
return None | python | def detect_file(filename):
"""Decide what to do with the file."""
image_format = get_image_format(filename)
if image_format in Settings.formats:
return image_format
if image_format in (NONE_FORMAT, ERROR_FORMAT):
return None
if Settings.verbose > 1 and not Settings.list_only:
print(filename, image_format, 'is not a enabled image or '
'comic archive type.')
return None | [
"def",
"detect_file",
"(",
"filename",
")",
":",
"image_format",
"=",
"get_image_format",
"(",
"filename",
")",
"if",
"image_format",
"in",
"Settings",
".",
"formats",
":",
"return",
"image_format",
"if",
"image_format",
"in",
"(",
"NONE_FORMAT",
",",
"ERROR_FOR... | Decide what to do with the file. | [
"Decide",
"what",
"to",
"do",
"with",
"the",
"file",
"."
] | 261da837027563c1dc3ed07b70e1086520a60402 | https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/detect_format.py#L71-L84 | train | 42,510 |
ajslater/picopt | picopt/settings.py | Settings.update | def update(cls, settings):
"""Update settings with a dict."""
for key, val in settings.__dict__.items():
if key.startswith('_'):
continue
setattr(cls, key, val) | python | def update(cls, settings):
"""Update settings with a dict."""
for key, val in settings.__dict__.items():
if key.startswith('_'):
continue
setattr(cls, key, val) | [
"def",
"update",
"(",
"cls",
",",
"settings",
")",
":",
"for",
"key",
",",
"val",
"in",
"settings",
".",
"__dict__",
".",
"items",
"(",
")",
":",
"if",
"key",
".",
"startswith",
"(",
"'_'",
")",
":",
"continue",
"setattr",
"(",
"cls",
",",
"key",
... | Update settings with a dict. | [
"Update",
"settings",
"with",
"a",
"dict",
"."
] | 261da837027563c1dc3ed07b70e1086520a60402 | https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/settings.py#L39-L44 | train | 42,511 |
ajslater/picopt | picopt/settings.py | Settings._set_program_defaults | def _set_program_defaults(cls, programs):
"""Run the external program tester on the required binaries."""
for program in programs:
val = getattr(cls, program.__name__) \
and extern.does_external_program_run(program.__name__,
Settings.verbose)
setattr(cls, program.__name__, val) | python | def _set_program_defaults(cls, programs):
"""Run the external program tester on the required binaries."""
for program in programs:
val = getattr(cls, program.__name__) \
and extern.does_external_program_run(program.__name__,
Settings.verbose)
setattr(cls, program.__name__, val) | [
"def",
"_set_program_defaults",
"(",
"cls",
",",
"programs",
")",
":",
"for",
"program",
"in",
"programs",
":",
"val",
"=",
"getattr",
"(",
"cls",
",",
"program",
".",
"__name__",
")",
"and",
"extern",
".",
"does_external_program_run",
"(",
"program",
".",
... | Run the external program tester on the required binaries. | [
"Run",
"the",
"external",
"program",
"tester",
"on",
"the",
"required",
"binaries",
"."
] | 261da837027563c1dc3ed07b70e1086520a60402 | https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/settings.py#L47-L53 | train | 42,512 |
ajslater/picopt | picopt/settings.py | Settings.config_program_reqs | def config_program_reqs(cls, programs):
"""Run the program tester and determine if we can do anything."""
cls._set_program_defaults(programs)
do_png = cls.optipng or cls.pngout or cls.advpng
do_jpeg = cls.mozjpeg or cls.jpegrescan or cls.jpegtran
do_comics = cls.comics
if not do_png and not do_jpeg and not do_comics:
print("All optimizers are not available or disabled.")
exit(1) | python | def config_program_reqs(cls, programs):
"""Run the program tester and determine if we can do anything."""
cls._set_program_defaults(programs)
do_png = cls.optipng or cls.pngout or cls.advpng
do_jpeg = cls.mozjpeg or cls.jpegrescan or cls.jpegtran
do_comics = cls.comics
if not do_png and not do_jpeg and not do_comics:
print("All optimizers are not available or disabled.")
exit(1) | [
"def",
"config_program_reqs",
"(",
"cls",
",",
"programs",
")",
":",
"cls",
".",
"_set_program_defaults",
"(",
"programs",
")",
"do_png",
"=",
"cls",
".",
"optipng",
"or",
"cls",
".",
"pngout",
"or",
"cls",
".",
"advpng",
"do_jpeg",
"=",
"cls",
".",
"moz... | Run the program tester and determine if we can do anything. | [
"Run",
"the",
"program",
"tester",
"and",
"determine",
"if",
"we",
"can",
"do",
"anything",
"."
] | 261da837027563c1dc3ed07b70e1086520a60402 | https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/settings.py#L56-L67 | train | 42,513 |
ajslater/picopt | picopt/formats/png.py | optipng | def optipng(ext_args):
"""Run the external program optipng on the file."""
args = _OPTIPNG_ARGS + [ext_args.new_filename]
extern.run_ext(args)
return _PNG_FORMAT | python | def optipng(ext_args):
"""Run the external program optipng on the file."""
args = _OPTIPNG_ARGS + [ext_args.new_filename]
extern.run_ext(args)
return _PNG_FORMAT | [
"def",
"optipng",
"(",
"ext_args",
")",
":",
"args",
"=",
"_OPTIPNG_ARGS",
"+",
"[",
"ext_args",
".",
"new_filename",
"]",
"extern",
".",
"run_ext",
"(",
"args",
")",
"return",
"_PNG_FORMAT"
] | Run the external program optipng on the file. | [
"Run",
"the",
"external",
"program",
"optipng",
"on",
"the",
"file",
"."
] | 261da837027563c1dc3ed07b70e1086520a60402 | https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/formats/png.py#L17-L21 | train | 42,514 |
ajslater/picopt | picopt/formats/png.py | advpng | def advpng(ext_args):
"""Run the external program advpng on the file."""
args = _ADVPNG_ARGS + [ext_args.new_filename]
extern.run_ext(args)
return _PNG_FORMAT | python | def advpng(ext_args):
"""Run the external program advpng on the file."""
args = _ADVPNG_ARGS + [ext_args.new_filename]
extern.run_ext(args)
return _PNG_FORMAT | [
"def",
"advpng",
"(",
"ext_args",
")",
":",
"args",
"=",
"_ADVPNG_ARGS",
"+",
"[",
"ext_args",
".",
"new_filename",
"]",
"extern",
".",
"run_ext",
"(",
"args",
")",
"return",
"_PNG_FORMAT"
] | Run the external program advpng on the file. | [
"Run",
"the",
"external",
"program",
"advpng",
"on",
"the",
"file",
"."
] | 261da837027563c1dc3ed07b70e1086520a60402 | https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/formats/png.py#L24-L28 | train | 42,515 |
ajslater/picopt | picopt/formats/png.py | pngout | def pngout(ext_args):
"""Run the external program pngout on the file."""
args = _PNGOUT_ARGS + [ext_args.old_filename, ext_args.new_filename]
extern.run_ext(args)
return _PNG_FORMAT | python | def pngout(ext_args):
"""Run the external program pngout on the file."""
args = _PNGOUT_ARGS + [ext_args.old_filename, ext_args.new_filename]
extern.run_ext(args)
return _PNG_FORMAT | [
"def",
"pngout",
"(",
"ext_args",
")",
":",
"args",
"=",
"_PNGOUT_ARGS",
"+",
"[",
"ext_args",
".",
"old_filename",
",",
"ext_args",
".",
"new_filename",
"]",
"extern",
".",
"run_ext",
"(",
"args",
")",
"return",
"_PNG_FORMAT"
] | Run the external program pngout on the file. | [
"Run",
"the",
"external",
"program",
"pngout",
"on",
"the",
"file",
"."
] | 261da837027563c1dc3ed07b70e1086520a60402 | https://github.com/ajslater/picopt/blob/261da837027563c1dc3ed07b70e1086520a60402/picopt/formats/png.py#L31-L35 | train | 42,516 |
AtteqCom/zsl | src/zsl/resource/guard.py | _nested_transactional | def _nested_transactional(fn):
# type: (Callable) -> Callable
"""In a transactional method create a nested transaction."""
@wraps(fn)
def wrapped(self, *args, **kwargs):
# type: (SessionFactory) -> Any
try:
rv = fn(self, *args, **kwargs)
except _TransactionalPolicyViolationError as e:
getattr(self, _TX_HOLDER_ATTRIBUTE).rollback()
rv = e.result
return rv
return wrapped | python | def _nested_transactional(fn):
# type: (Callable) -> Callable
"""In a transactional method create a nested transaction."""
@wraps(fn)
def wrapped(self, *args, **kwargs):
# type: (SessionFactory) -> Any
try:
rv = fn(self, *args, **kwargs)
except _TransactionalPolicyViolationError as e:
getattr(self, _TX_HOLDER_ATTRIBUTE).rollback()
rv = e.result
return rv
return wrapped | [
"def",
"_nested_transactional",
"(",
"fn",
")",
":",
"# type: (Callable) -> Callable",
"@",
"wraps",
"(",
"fn",
")",
"def",
"wrapped",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (SessionFactory) -> Any",
"try",
":",
"rv",
"=",... | In a transactional method create a nested transaction. | [
"In",
"a",
"transactional",
"method",
"create",
"a",
"nested",
"transaction",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/resource/guard.py#L343-L357 | train | 42,517 |
datacamp/protowhat | protowhat/checks/check_files.py | check_file | def check_file(
state,
fname,
missing_msg="Did you create a file named `{}`?",
is_dir_msg="Want to check a file named `{}`, but found a directory.",
parse=True,
use_fs=True,
use_solution=False,
):
"""Test whether file exists, and make its contents the student code.
Note: this SCT fails if the file is a directory.
"""
if use_fs:
p = Path(fname)
if not p.exists():
state.report(Feedback(missing_msg.format(fname))) # test file exists
if p.is_dir():
state.report(Feedback(is_dir_msg.format(fname))) # test its not a dir
code = p.read_text()
else:
code = _get_fname(state, "student_code", fname)
if code is None:
state.report(Feedback(missing_msg.format(fname))) # test file exists
sol_kwargs = {"solution_code": None, "solution_ast": None}
if use_solution:
sol_code = _get_fname(state, "solution_code", fname)
if sol_code is None:
raise Exception("Solution code does not have file named: %s" % fname)
sol_kwargs["solution_code"] = sol_code
sol_kwargs["solution_ast"] = (
state.parse(sol_code, test=False) if parse else None
)
return state.to_child(
student_code=code,
student_ast=state.parse(code) if parse else None,
fname=fname,
**sol_kwargs
) | python | def check_file(
state,
fname,
missing_msg="Did you create a file named `{}`?",
is_dir_msg="Want to check a file named `{}`, but found a directory.",
parse=True,
use_fs=True,
use_solution=False,
):
"""Test whether file exists, and make its contents the student code.
Note: this SCT fails if the file is a directory.
"""
if use_fs:
p = Path(fname)
if not p.exists():
state.report(Feedback(missing_msg.format(fname))) # test file exists
if p.is_dir():
state.report(Feedback(is_dir_msg.format(fname))) # test its not a dir
code = p.read_text()
else:
code = _get_fname(state, "student_code", fname)
if code is None:
state.report(Feedback(missing_msg.format(fname))) # test file exists
sol_kwargs = {"solution_code": None, "solution_ast": None}
if use_solution:
sol_code = _get_fname(state, "solution_code", fname)
if sol_code is None:
raise Exception("Solution code does not have file named: %s" % fname)
sol_kwargs["solution_code"] = sol_code
sol_kwargs["solution_ast"] = (
state.parse(sol_code, test=False) if parse else None
)
return state.to_child(
student_code=code,
student_ast=state.parse(code) if parse else None,
fname=fname,
**sol_kwargs
) | [
"def",
"check_file",
"(",
"state",
",",
"fname",
",",
"missing_msg",
"=",
"\"Did you create a file named `{}`?\"",
",",
"is_dir_msg",
"=",
"\"Want to check a file named `{}`, but found a directory.\"",
",",
"parse",
"=",
"True",
",",
"use_fs",
"=",
"True",
",",
"use_sol... | Test whether file exists, and make its contents the student code.
Note: this SCT fails if the file is a directory. | [
"Test",
"whether",
"file",
"exists",
"and",
"make",
"its",
"contents",
"the",
"student",
"code",
"."
] | a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc | https://github.com/datacamp/protowhat/blob/a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc/protowhat/checks/check_files.py#L7-L50 | train | 42,518 |
datacamp/protowhat | protowhat/checks/check_files.py | has_dir | def has_dir(state, fname, incorrect_msg="Did you create a directory named `{}`?"):
"""Test whether a directory exists."""
if not Path(fname).is_dir():
state.report(Feedback(incorrect_msg.format(fname)))
return state | python | def has_dir(state, fname, incorrect_msg="Did you create a directory named `{}`?"):
"""Test whether a directory exists."""
if not Path(fname).is_dir():
state.report(Feedback(incorrect_msg.format(fname)))
return state | [
"def",
"has_dir",
"(",
"state",
",",
"fname",
",",
"incorrect_msg",
"=",
"\"Did you create a directory named `{}`?\"",
")",
":",
"if",
"not",
"Path",
"(",
"fname",
")",
".",
"is_dir",
"(",
")",
":",
"state",
".",
"report",
"(",
"Feedback",
"(",
"incorrect_ms... | Test whether a directory exists. | [
"Test",
"whether",
"a",
"directory",
"exists",
"."
] | a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc | https://github.com/datacamp/protowhat/blob/a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc/protowhat/checks/check_files.py#L63-L68 | train | 42,519 |
AtteqCom/zsl | src/zsl/interface/task.py | exec_task | def exec_task(task_path, data):
"""Execute task.
:param task_path: task path
:type task_path: str|Callable
:param data: task's data
:type data: Any
:return:
"""
if not data:
data = {'data': None, 'path': task_path}
elif not isinstance(data, (str, bytes)):
data = {'data': json.dumps(data, cls=RequestJSONEncoder),
'path': task_path}
else:
# Open the data from file, if necessary.
if data is not None and data.startswith("file://"):
with open(data[len("file://"):]) as f:
data = f.read()
data = {'data': data, 'path': task_path}
# Prepare the task.
job = Job(data)
(task, task_callable) = create_task(task_path)
with delegating_job_context(job, task, task_callable) as jc:
return jc.task_callable(jc.task_data) | python | def exec_task(task_path, data):
"""Execute task.
:param task_path: task path
:type task_path: str|Callable
:param data: task's data
:type data: Any
:return:
"""
if not data:
data = {'data': None, 'path': task_path}
elif not isinstance(data, (str, bytes)):
data = {'data': json.dumps(data, cls=RequestJSONEncoder),
'path': task_path}
else:
# Open the data from file, if necessary.
if data is not None and data.startswith("file://"):
with open(data[len("file://"):]) as f:
data = f.read()
data = {'data': data, 'path': task_path}
# Prepare the task.
job = Job(data)
(task, task_callable) = create_task(task_path)
with delegating_job_context(job, task, task_callable) as jc:
return jc.task_callable(jc.task_data) | [
"def",
"exec_task",
"(",
"task_path",
",",
"data",
")",
":",
"if",
"not",
"data",
":",
"data",
"=",
"{",
"'data'",
":",
"None",
",",
"'path'",
":",
"task_path",
"}",
"elif",
"not",
"isinstance",
"(",
"data",
",",
"(",
"str",
",",
"bytes",
")",
")",... | Execute task.
:param task_path: task path
:type task_path: str|Callable
:param data: task's data
:type data: Any
:return: | [
"Execute",
"task",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/interface/task.py#L107-L136 | train | 42,520 |
datacamp/protowhat | protowhat/utils_ast.py | dump | def dump(node, config):
"""
Convert a node tree to a simple nested dict
All steps in this conversion are configurable using DumpConfig
dump dictionary node: {"type": str, "data": dict}
"""
if config.is_node(node):
fields = OrderedDict()
for name in config.fields_iter(node):
attr = config.field_val(node, name)
if attr is not None:
fields[name] = dump(attr, config)
return {"type": config.node_type(node), "data": fields}
elif config.is_list(node):
return [dump(x, config) for x in config.list_iter(node)]
else:
return config.leaf_val(node) | python | def dump(node, config):
"""
Convert a node tree to a simple nested dict
All steps in this conversion are configurable using DumpConfig
dump dictionary node: {"type": str, "data": dict}
"""
if config.is_node(node):
fields = OrderedDict()
for name in config.fields_iter(node):
attr = config.field_val(node, name)
if attr is not None:
fields[name] = dump(attr, config)
return {"type": config.node_type(node), "data": fields}
elif config.is_list(node):
return [dump(x, config) for x in config.list_iter(node)]
else:
return config.leaf_val(node) | [
"def",
"dump",
"(",
"node",
",",
"config",
")",
":",
"if",
"config",
".",
"is_node",
"(",
"node",
")",
":",
"fields",
"=",
"OrderedDict",
"(",
")",
"for",
"name",
"in",
"config",
".",
"fields_iter",
"(",
"node",
")",
":",
"attr",
"=",
"config",
"."... | Convert a node tree to a simple nested dict
All steps in this conversion are configurable using DumpConfig
dump dictionary node: {"type": str, "data": dict} | [
"Convert",
"a",
"node",
"tree",
"to",
"a",
"simple",
"nested",
"dict"
] | a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc | https://github.com/datacamp/protowhat/blob/a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc/protowhat/utils_ast.py#L30-L48 | train | 42,521 |
briney/abutils | abutils/utils/cluster.py | cluster | def cluster(seqs, threshold=0.975, out_file=None, temp_dir=None, make_db=True,
quiet=False, threads=0, return_just_seq_ids=False, max_memory=800, debug=False):
'''
Perform sequence clustering with CD-HIT.
Args:
seqs (list): An iterable of sequences, in any format that `abutils.utils.sequence.Sequence()`
can handle
threshold (float): Clustering identity threshold. Default is `0.975`.
out_file (str): Path to the clustering output file. Default is to use
`tempfile.NamedTemporaryFile` to generate an output file name.
temp_dir (str): Path to the temporary directory. If not provided, `'/tmp'` is used.
make_db (bool): Whether to build a SQlite database of sequence information. Required
if you want to calculate consensus/centroid sequences for the resulting
clusters or if you need to access the clustered sequences (not just sequence IDs)
Default is `True`.
quiet (bool): If `True`, surpresses printing of output/progress info. Default is `False`.
threads (int): Number of threads (CPU cores) to be used for clustering. Default is `0`,
which results in all available cores being used.
return_just_seq_ids (bool): If `True`, will return a 2D list of sequence IDs
(a list containing a list of sequence IDs for each cluster) rather than returning a
list of `Cluster` objects.
max_memory (int): Max memory (in MB) for CD-HIT. Will be passed directly to CD-HIT through
the `-M` runtime option. Default is `800`.
debug (bool): If `True`, print standard output and standard error from CD-HIT. Default is `False`.
Returns:
list: A list of `Cluster` objects (or a 2D list of sequence IDs, if `return_just_seq_ids` is `True`).
'''
if make_db:
ofile, cfile, seq_db, db_path = cdhit(seqs, out_file=out_file, temp_dir=temp_dir,
threshold=threshold, make_db=True, quiet=quiet,
threads=threads, max_memory=max_memory, debug=debug)
return parse_clusters(ofile, cfile, seq_db=seq_db, db_path=db_path, return_just_seq_ids=return_just_seq_ids)
else:
seqs = [Sequence(s) for s in seqs]
seq_dict = {s.id: s for s in seqs}
ofile, cfile, = cdhit(seqs, out_file=out_file, temp_dir=temp_dir, threads=threads,
threshold=threshold, make_db=False, quiet=quiet,
max_memory=max_memory, debug=debug)
return parse_clusters(ofile, cfile, seq_dict=seq_dict, return_just_seq_ids=return_just_seq_ids) | python | def cluster(seqs, threshold=0.975, out_file=None, temp_dir=None, make_db=True,
quiet=False, threads=0, return_just_seq_ids=False, max_memory=800, debug=False):
'''
Perform sequence clustering with CD-HIT.
Args:
seqs (list): An iterable of sequences, in any format that `abutils.utils.sequence.Sequence()`
can handle
threshold (float): Clustering identity threshold. Default is `0.975`.
out_file (str): Path to the clustering output file. Default is to use
`tempfile.NamedTemporaryFile` to generate an output file name.
temp_dir (str): Path to the temporary directory. If not provided, `'/tmp'` is used.
make_db (bool): Whether to build a SQlite database of sequence information. Required
if you want to calculate consensus/centroid sequences for the resulting
clusters or if you need to access the clustered sequences (not just sequence IDs)
Default is `True`.
quiet (bool): If `True`, surpresses printing of output/progress info. Default is `False`.
threads (int): Number of threads (CPU cores) to be used for clustering. Default is `0`,
which results in all available cores being used.
return_just_seq_ids (bool): If `True`, will return a 2D list of sequence IDs
(a list containing a list of sequence IDs for each cluster) rather than returning a
list of `Cluster` objects.
max_memory (int): Max memory (in MB) for CD-HIT. Will be passed directly to CD-HIT through
the `-M` runtime option. Default is `800`.
debug (bool): If `True`, print standard output and standard error from CD-HIT. Default is `False`.
Returns:
list: A list of `Cluster` objects (or a 2D list of sequence IDs, if `return_just_seq_ids` is `True`).
'''
if make_db:
ofile, cfile, seq_db, db_path = cdhit(seqs, out_file=out_file, temp_dir=temp_dir,
threshold=threshold, make_db=True, quiet=quiet,
threads=threads, max_memory=max_memory, debug=debug)
return parse_clusters(ofile, cfile, seq_db=seq_db, db_path=db_path, return_just_seq_ids=return_just_seq_ids)
else:
seqs = [Sequence(s) for s in seqs]
seq_dict = {s.id: s for s in seqs}
ofile, cfile, = cdhit(seqs, out_file=out_file, temp_dir=temp_dir, threads=threads,
threshold=threshold, make_db=False, quiet=quiet,
max_memory=max_memory, debug=debug)
return parse_clusters(ofile, cfile, seq_dict=seq_dict, return_just_seq_ids=return_just_seq_ids) | [
"def",
"cluster",
"(",
"seqs",
",",
"threshold",
"=",
"0.975",
",",
"out_file",
"=",
"None",
",",
"temp_dir",
"=",
"None",
",",
"make_db",
"=",
"True",
",",
"quiet",
"=",
"False",
",",
"threads",
"=",
"0",
",",
"return_just_seq_ids",
"=",
"False",
",",... | Perform sequence clustering with CD-HIT.
Args:
seqs (list): An iterable of sequences, in any format that `abutils.utils.sequence.Sequence()`
can handle
threshold (float): Clustering identity threshold. Default is `0.975`.
out_file (str): Path to the clustering output file. Default is to use
`tempfile.NamedTemporaryFile` to generate an output file name.
temp_dir (str): Path to the temporary directory. If not provided, `'/tmp'` is used.
make_db (bool): Whether to build a SQlite database of sequence information. Required
if you want to calculate consensus/centroid sequences for the resulting
clusters or if you need to access the clustered sequences (not just sequence IDs)
Default is `True`.
quiet (bool): If `True`, surpresses printing of output/progress info. Default is `False`.
threads (int): Number of threads (CPU cores) to be used for clustering. Default is `0`,
which results in all available cores being used.
return_just_seq_ids (bool): If `True`, will return a 2D list of sequence IDs
(a list containing a list of sequence IDs for each cluster) rather than returning a
list of `Cluster` objects.
max_memory (int): Max memory (in MB) for CD-HIT. Will be passed directly to CD-HIT through
the `-M` runtime option. Default is `800`.
debug (bool): If `True`, print standard output and standard error from CD-HIT. Default is `False`.
Returns:
list: A list of `Cluster` objects (or a 2D list of sequence IDs, if `return_just_seq_ids` is `True`). | [
"Perform",
"sequence",
"clustering",
"with",
"CD",
"-",
"HIT",
"."
] | 944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b | https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/utils/cluster.py#L233-L284 | train | 42,522 |
briney/abutils | abutils/utils/cluster.py | cdhit | def cdhit(seqs, out_file=None, temp_dir=None, threshold=0.975, make_db=True, quiet=False, threads=0, max_memory=800, retries=5, debug=False):
'''
Run CD-HIT.
Args:
seqs (list): An iterable of sequences, in any format that `abutils.utils.sequence.Sequence()`
can handle
threshold (float): Clustering identity threshold. Default is `0.975`.
out_file (str): Path to the clustering output file. Default is to use
`tempfile.NamedTemporaryFile` to generate an output file name.
temp_dir (str): Path to the temporary directory. If not provided, `'/tmp'` is used.
make_db (bool): Whether to build a SQlite database of sequence information. Required
if you want to calculate consensus/centroid sequences for the resulting
clusters or if you need to access the clustered sequences (not just sequence IDs)
Default is `True`.
quiet (bool): If `True`, surpresses printing of output/progress info. Default is `False`.
threads (int): Number of threads (CPU cores) to be used for clustering. Default is `0`,
which results in all available cores being used.
max_memory (int): Max memory (in MB) for CD-HIT. Will be passed directly to CD-HIT through
the `-M` runtime option. Default is `800`.
debug (bool): If `True`, print standard output and standard error from CD-HIT. Default is `False`.
Returns:
If `make_db` is `True`, returns the CD-HIT output file path, the CD-HIT cluster file path,
a `sqlite3` database connection object, and the database path. If `make_db` is `False`, only the
CD-HIT output file path and CD-HIT cluster file path are returned.
'''
start_time = time.time()
seqs = [Sequence(s) for s in seqs]
if not quiet:
print('CD-HIT: clustering {} seqeunces'.format(len(seqs)))
if out_file is None:
out_file = tempfile.NamedTemporaryFile(dir=temp_dir, delete=False)
out_file.close()
ofile = out_file.name
else:
ofile = os.path.expanduser(out_file)
cfile = ofile + '.clstr'
with open(ofile, 'w') as f: f.write('')
with open(cfile, 'w') as f: f.write('')
ifile = _make_cdhit_input(seqs, temp_dir)
cdhit_cmd = 'cdhit -i {} -o {} -c {} -n 5 -d 0 -T {} -M {}'.format(ifile,
ofile,
threshold,
threads,
max_memory)
while not all([os.path.getsize(cfile), os.path.getsize(cfile)]):
cluster = sp.Popen(cdhit_cmd,
shell=True,
stdout=sp.PIPE,
stderr=sp.PIPE)
stdout, stderr = cluster.communicate()
if not retries:
break
retries -= 1
end_time = time.time()
if debug:
print(stdout)
print(stderr)
else:
os.unlink(ifile)
if not quiet:
print('CD-HIT: clustering took {:.2f} seconds'.format(end_time - start_time))
if make_db:
if not quiet:
print('CD-HIT: building a SQLite3 database')
seq_db, db_path = _build_seq_db(seqs, direc=temp_dir)
return ofile, cfile, seq_db, db_path
return ofile, cfile | python | def cdhit(seqs, out_file=None, temp_dir=None, threshold=0.975, make_db=True, quiet=False, threads=0, max_memory=800, retries=5, debug=False):
'''
Run CD-HIT.
Args:
seqs (list): An iterable of sequences, in any format that `abutils.utils.sequence.Sequence()`
can handle
threshold (float): Clustering identity threshold. Default is `0.975`.
out_file (str): Path to the clustering output file. Default is to use
`tempfile.NamedTemporaryFile` to generate an output file name.
temp_dir (str): Path to the temporary directory. If not provided, `'/tmp'` is used.
make_db (bool): Whether to build a SQlite database of sequence information. Required
if you want to calculate consensus/centroid sequences for the resulting
clusters or if you need to access the clustered sequences (not just sequence IDs)
Default is `True`.
quiet (bool): If `True`, surpresses printing of output/progress info. Default is `False`.
threads (int): Number of threads (CPU cores) to be used for clustering. Default is `0`,
which results in all available cores being used.
max_memory (int): Max memory (in MB) for CD-HIT. Will be passed directly to CD-HIT through
the `-M` runtime option. Default is `800`.
debug (bool): If `True`, print standard output and standard error from CD-HIT. Default is `False`.
Returns:
If `make_db` is `True`, returns the CD-HIT output file path, the CD-HIT cluster file path,
a `sqlite3` database connection object, and the database path. If `make_db` is `False`, only the
CD-HIT output file path and CD-HIT cluster file path are returned.
'''
start_time = time.time()
seqs = [Sequence(s) for s in seqs]
if not quiet:
print('CD-HIT: clustering {} seqeunces'.format(len(seqs)))
if out_file is None:
out_file = tempfile.NamedTemporaryFile(dir=temp_dir, delete=False)
out_file.close()
ofile = out_file.name
else:
ofile = os.path.expanduser(out_file)
cfile = ofile + '.clstr'
with open(ofile, 'w') as f: f.write('')
with open(cfile, 'w') as f: f.write('')
ifile = _make_cdhit_input(seqs, temp_dir)
cdhit_cmd = 'cdhit -i {} -o {} -c {} -n 5 -d 0 -T {} -M {}'.format(ifile,
ofile,
threshold,
threads,
max_memory)
while not all([os.path.getsize(cfile), os.path.getsize(cfile)]):
cluster = sp.Popen(cdhit_cmd,
shell=True,
stdout=sp.PIPE,
stderr=sp.PIPE)
stdout, stderr = cluster.communicate()
if not retries:
break
retries -= 1
end_time = time.time()
if debug:
print(stdout)
print(stderr)
else:
os.unlink(ifile)
if not quiet:
print('CD-HIT: clustering took {:.2f} seconds'.format(end_time - start_time))
if make_db:
if not quiet:
print('CD-HIT: building a SQLite3 database')
seq_db, db_path = _build_seq_db(seqs, direc=temp_dir)
return ofile, cfile, seq_db, db_path
return ofile, cfile | [
"def",
"cdhit",
"(",
"seqs",
",",
"out_file",
"=",
"None",
",",
"temp_dir",
"=",
"None",
",",
"threshold",
"=",
"0.975",
",",
"make_db",
"=",
"True",
",",
"quiet",
"=",
"False",
",",
"threads",
"=",
"0",
",",
"max_memory",
"=",
"800",
",",
"retries",... | Run CD-HIT.
Args:
seqs (list): An iterable of sequences, in any format that `abutils.utils.sequence.Sequence()`
can handle
threshold (float): Clustering identity threshold. Default is `0.975`.
out_file (str): Path to the clustering output file. Default is to use
`tempfile.NamedTemporaryFile` to generate an output file name.
temp_dir (str): Path to the temporary directory. If not provided, `'/tmp'` is used.
make_db (bool): Whether to build a SQlite database of sequence information. Required
if you want to calculate consensus/centroid sequences for the resulting
clusters or if you need to access the clustered sequences (not just sequence IDs)
Default is `True`.
quiet (bool): If `True`, surpresses printing of output/progress info. Default is `False`.
threads (int): Number of threads (CPU cores) to be used for clustering. Default is `0`,
which results in all available cores being used.
max_memory (int): Max memory (in MB) for CD-HIT. Will be passed directly to CD-HIT through
the `-M` runtime option. Default is `800`.
debug (bool): If `True`, print standard output and standard error from CD-HIT. Default is `False`.
Returns:
If `make_db` is `True`, returns the CD-HIT output file path, the CD-HIT cluster file path,
a `sqlite3` database connection object, and the database path. If `make_db` is `False`, only the
CD-HIT output file path and CD-HIT cluster file path are returned. | [
"Run",
"CD",
"-",
"HIT",
"."
] | 944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b | https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/utils/cluster.py#L287-L365 | train | 42,523 |
briney/abutils | abutils/utils/cluster.py | parse_clusters | def parse_clusters(out_file, clust_file, seq_db=None, db_path=None, seq_dict=None, return_just_seq_ids=False):
'''
Parses CD-HIT output.
Args:
out_file (str): Path to the CD-HIT output file. Required.
clust_file (str): Path to the CD-HIT cluster file. Required.
seq_db (sqlite.Connection): SQLite3 `Connection` object. Default is `None`. If not provided and
`return_just_seq_ids` is False, the returned `Cluster` objects will not contain any sequence
information beyond the sequence ID.
db_path (str): Path to a SQLite3 database file. Default is `None`. Must be provided if
`seq_db` is also provided.
seq_dict (dict): A `dict` mapping sequence IDs to `abutils.core.sequence.Sequence` objects. Default
is `None`. Typically used when a relatively small number of sequences are being clustered and
creating a `sqlite3` database would be overkill.
temp_dir (str): Path to the temporary directory. If not provided, `'/tmp'` is used.
make_db (bool): Whether to build a SQlite database of sequence information. Required
if you want to calculate consensus/centroid sequences for the resulting
clusters or if you need to access the clustered sequences (not just sequence IDs)
Default is `True`.
quiet (bool): If `True`, surpresses printing of output/progress info. Default is `False`.
threads (int): Number of threads (CPU cores) to be used for clustering. Default is `0`,
which results in all available cores being used.
return_just_seq_ids (bool): If `True`, will return a 2D list of sequence IDs
(a list containing a list of sequence IDs for each cluster) rather than returning a
list of `Cluster` objects.
max_memory (int): Max memory (in MB) for CD-HIT. Will be passed directly to CD-HIT through
the `-M` runtime option. Default is `800`.
debug (bool): If `True`, print standard output and standard error from CD-HIT. Default is `False`.
Returns:
A CDHITResult object, or a 2D list of sequence IDs, if `return_just_seq_ids` is `True`.
'''
raw_clusters = [c.split('\n') for c in open(clust_file, 'r').read().split('\n>')]
if return_just_seq_ids:
ids = []
for rc in raw_clusters:
_ids = []
for c in rc[1:]:
if c:
_ids.append(c.split()[2][1:-3])
ids.append(_ids)
os.unlink(out_file)
os.unlink(clust_file)
return ids
os.unlink(out_file)
os.unlink(clust_file)
clusters = [Cluster(rc, seq_db, db_path, seq_dict) for rc in raw_clusters]
return CDHITResult(clusters, seq_db=seq_db, db_path=db_path, seq_dict=seq_dict) | python | def parse_clusters(out_file, clust_file, seq_db=None, db_path=None, seq_dict=None, return_just_seq_ids=False):
'''
Parses CD-HIT output.
Args:
out_file (str): Path to the CD-HIT output file. Required.
clust_file (str): Path to the CD-HIT cluster file. Required.
seq_db (sqlite.Connection): SQLite3 `Connection` object. Default is `None`. If not provided and
`return_just_seq_ids` is False, the returned `Cluster` objects will not contain any sequence
information beyond the sequence ID.
db_path (str): Path to a SQLite3 database file. Default is `None`. Must be provided if
`seq_db` is also provided.
seq_dict (dict): A `dict` mapping sequence IDs to `abutils.core.sequence.Sequence` objects. Default
is `None`. Typically used when a relatively small number of sequences are being clustered and
creating a `sqlite3` database would be overkill.
temp_dir (str): Path to the temporary directory. If not provided, `'/tmp'` is used.
make_db (bool): Whether to build a SQlite database of sequence information. Required
if you want to calculate consensus/centroid sequences for the resulting
clusters or if you need to access the clustered sequences (not just sequence IDs)
Default is `True`.
quiet (bool): If `True`, surpresses printing of output/progress info. Default is `False`.
threads (int): Number of threads (CPU cores) to be used for clustering. Default is `0`,
which results in all available cores being used.
return_just_seq_ids (bool): If `True`, will return a 2D list of sequence IDs
(a list containing a list of sequence IDs for each cluster) rather than returning a
list of `Cluster` objects.
max_memory (int): Max memory (in MB) for CD-HIT. Will be passed directly to CD-HIT through
the `-M` runtime option. Default is `800`.
debug (bool): If `True`, print standard output and standard error from CD-HIT. Default is `False`.
Returns:
A CDHITResult object, or a 2D list of sequence IDs, if `return_just_seq_ids` is `True`.
'''
raw_clusters = [c.split('\n') for c in open(clust_file, 'r').read().split('\n>')]
if return_just_seq_ids:
ids = []
for rc in raw_clusters:
_ids = []
for c in rc[1:]:
if c:
_ids.append(c.split()[2][1:-3])
ids.append(_ids)
os.unlink(out_file)
os.unlink(clust_file)
return ids
os.unlink(out_file)
os.unlink(clust_file)
clusters = [Cluster(rc, seq_db, db_path, seq_dict) for rc in raw_clusters]
return CDHITResult(clusters, seq_db=seq_db, db_path=db_path, seq_dict=seq_dict) | [
"def",
"parse_clusters",
"(",
"out_file",
",",
"clust_file",
",",
"seq_db",
"=",
"None",
",",
"db_path",
"=",
"None",
",",
"seq_dict",
"=",
"None",
",",
"return_just_seq_ids",
"=",
"False",
")",
":",
"raw_clusters",
"=",
"[",
"c",
".",
"split",
"(",
"'\\... | Parses CD-HIT output.
Args:
out_file (str): Path to the CD-HIT output file. Required.
clust_file (str): Path to the CD-HIT cluster file. Required.
seq_db (sqlite.Connection): SQLite3 `Connection` object. Default is `None`. If not provided and
`return_just_seq_ids` is False, the returned `Cluster` objects will not contain any sequence
information beyond the sequence ID.
db_path (str): Path to a SQLite3 database file. Default is `None`. Must be provided if
`seq_db` is also provided.
seq_dict (dict): A `dict` mapping sequence IDs to `abutils.core.sequence.Sequence` objects. Default
is `None`. Typically used when a relatively small number of sequences are being clustered and
creating a `sqlite3` database would be overkill.
temp_dir (str): Path to the temporary directory. If not provided, `'/tmp'` is used.
make_db (bool): Whether to build a SQlite database of sequence information. Required
if you want to calculate consensus/centroid sequences for the resulting
clusters or if you need to access the clustered sequences (not just sequence IDs)
Default is `True`.
quiet (bool): If `True`, surpresses printing of output/progress info. Default is `False`.
threads (int): Number of threads (CPU cores) to be used for clustering. Default is `0`,
which results in all available cores being used.
return_just_seq_ids (bool): If `True`, will return a 2D list of sequence IDs
(a list containing a list of sequence IDs for each cluster) rather than returning a
list of `Cluster` objects.
max_memory (int): Max memory (in MB) for CD-HIT. Will be passed directly to CD-HIT through
the `-M` runtime option. Default is `800`.
debug (bool): If `True`, print standard output and standard error from CD-HIT. Default is `False`.
Returns:
A CDHITResult object, or a 2D list of sequence IDs, if `return_just_seq_ids` is `True`. | [
"Parses",
"CD",
"-",
"HIT",
"output",
"."
] | 944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b | https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/utils/cluster.py#L368-L429 | train | 42,524 |
AtteqCom/zsl | src/zsl/task/task_decorator.py | log_output | def log_output(f):
"""
Logs the output value.
"""
@wraps(f)
def wrapper_fn(*args, **kwargs):
res = f(*args, **kwargs)
logging.debug("Logging result %s.", res)
return res
return wrapper_fn | python | def log_output(f):
"""
Logs the output value.
"""
@wraps(f)
def wrapper_fn(*args, **kwargs):
res = f(*args, **kwargs)
logging.debug("Logging result %s.", res)
return res
return wrapper_fn | [
"def",
"log_output",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"wrapper_fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"res",
"=",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"logging",
".",
"debug",
"(",
"\"... | Logs the output value. | [
"Logs",
"the",
"output",
"value",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/task/task_decorator.py#L34-L45 | train | 42,525 |
AtteqCom/zsl | src/zsl/task/task_decorator.py | save_to_file | def save_to_file(destination_filename, append=False):
"""
Save the output value to file.
"""
def decorator_fn(f):
@wraps(f)
def wrapper_fn(*args, **kwargs):
res = f(*args, **kwargs)
makedirs(os.path.dirname(destination_filename))
mode = "a" if append else "w"
with open(destination_filename, mode) as text_file:
text_file.write(res)
return res
return wrapper_fn
return decorator_fn | python | def save_to_file(destination_filename, append=False):
"""
Save the output value to file.
"""
def decorator_fn(f):
@wraps(f)
def wrapper_fn(*args, **kwargs):
res = f(*args, **kwargs)
makedirs(os.path.dirname(destination_filename))
mode = "a" if append else "w"
with open(destination_filename, mode) as text_file:
text_file.write(res)
return res
return wrapper_fn
return decorator_fn | [
"def",
"save_to_file",
"(",
"destination_filename",
",",
"append",
"=",
"False",
")",
":",
"def",
"decorator_fn",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"wrapper_fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"res",
"=",
... | Save the output value to file. | [
"Save",
"the",
"output",
"value",
"to",
"file",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/task/task_decorator.py#L48-L67 | train | 42,526 |
AtteqCom/zsl | src/zsl/task/task_decorator.py | json_input | def json_input(f):
"""
Expects task input data in json format and parse this data.
"""
@wraps(f)
def json_input_decorator(*args, **kwargs):
# If the data is already transformed, we do not transform it any
# further.
task_data = _get_data_from_args(args)
if task_data is None:
logging.error("Task data is empty during JSON decoding.")
if task_data.payload:
try:
is_transformed = request.get_json()
# We transform the data only in the case of plain POST requests.
if not is_transformed:
task_data.transform_payload(json.loads)
except (ValueError, RuntimeError):
logging.error(
"Exception while processing JSON input decorator.")
task_data.transform_payload(json.loads)
else:
task_data.transform_payload(lambda _: {})
return f(*args, **kwargs)
return json_input_decorator | python | def json_input(f):
"""
Expects task input data in json format and parse this data.
"""
@wraps(f)
def json_input_decorator(*args, **kwargs):
# If the data is already transformed, we do not transform it any
# further.
task_data = _get_data_from_args(args)
if task_data is None:
logging.error("Task data is empty during JSON decoding.")
if task_data.payload:
try:
is_transformed = request.get_json()
# We transform the data only in the case of plain POST requests.
if not is_transformed:
task_data.transform_payload(json.loads)
except (ValueError, RuntimeError):
logging.error(
"Exception while processing JSON input decorator.")
task_data.transform_payload(json.loads)
else:
task_data.transform_payload(lambda _: {})
return f(*args, **kwargs)
return json_input_decorator | [
"def",
"json_input",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"json_input_decorator",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# If the data is already transformed, we do not transform it any",
"# further.",
"task_data",
"=",
"_get_data... | Expects task input data in json format and parse this data. | [
"Expects",
"task",
"input",
"data",
"in",
"json",
"format",
"and",
"parse",
"this",
"data",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/task/task_decorator.py#L70-L100 | train | 42,527 |
AtteqCom/zsl | src/zsl/task/task_decorator.py | jsonp_wrap | def jsonp_wrap(callback_key='callback'):
"""
Format response to jsonp and add a callback to JSON data - a jsonp request
"""
def decorator_fn(f):
@wraps(f)
def jsonp_output_decorator(*args, **kwargs):
task_data = _get_data_from_args(args)
data = task_data.get_data()
if callback_key not in data:
raise KeyError(
'Missing required parameter "{0}" for task.'.format(
callback_key))
callback = data[callback_key]
jsonp = f(*args, **kwargs)
if isinstance(JobContext.get_current_context(), WebJobContext):
JobContext.get_current_context().add_responder(
MimeSetterWebTaskResponder('application/javascript'))
jsonp = "{callback}({data})".format(callback=callback, data=jsonp)
return jsonp
return jsonp_output_decorator
return decorator_fn | python | def jsonp_wrap(callback_key='callback'):
"""
Format response to jsonp and add a callback to JSON data - a jsonp request
"""
def decorator_fn(f):
@wraps(f)
def jsonp_output_decorator(*args, **kwargs):
task_data = _get_data_from_args(args)
data = task_data.get_data()
if callback_key not in data:
raise KeyError(
'Missing required parameter "{0}" for task.'.format(
callback_key))
callback = data[callback_key]
jsonp = f(*args, **kwargs)
if isinstance(JobContext.get_current_context(), WebJobContext):
JobContext.get_current_context().add_responder(
MimeSetterWebTaskResponder('application/javascript'))
jsonp = "{callback}({data})".format(callback=callback, data=jsonp)
return jsonp
return jsonp_output_decorator
return decorator_fn | [
"def",
"jsonp_wrap",
"(",
"callback_key",
"=",
"'callback'",
")",
":",
"def",
"decorator_fn",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"jsonp_output_decorator",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"task_data",
"=",
"_get... | Format response to jsonp and add a callback to JSON data - a jsonp request | [
"Format",
"response",
"to",
"jsonp",
"and",
"add",
"a",
"callback",
"to",
"JSON",
"data",
"-",
"a",
"jsonp",
"request"
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/task/task_decorator.py#L134-L162 | train | 42,528 |
AtteqCom/zsl | src/zsl/task/task_decorator.py | append_get_parameters | def append_get_parameters(accept_only_web=True):
# type: (bool) -> Callable
"""
Task decorator which appends the GET data to the task data.
:param accept_only_web: Parameter which limits using this task only
with web requests.
"""
def wrapper(f):
@wraps(f)
def append_get_parameters_wrapper_fn(*args, **kwargs):
jc = JobContext.get_current_context()
if isinstance(jc, WebJobContext):
# Update the data with GET parameters
web_request = jc.get_web_request()
task_data = _get_data_from_args(args)
data = task_data.get_data()
data.update(web_request.args.to_dict(flat=True))
elif accept_only_web:
# Raise exception on non web usage if necessary
raise Exception("append_get_parameters decorator may be used "
"with GET requests only.")
return f(*args, **kwargs)
return append_get_parameters_wrapper_fn
return wrapper | python | def append_get_parameters(accept_only_web=True):
# type: (bool) -> Callable
"""
Task decorator which appends the GET data to the task data.
:param accept_only_web: Parameter which limits using this task only
with web requests.
"""
def wrapper(f):
@wraps(f)
def append_get_parameters_wrapper_fn(*args, **kwargs):
jc = JobContext.get_current_context()
if isinstance(jc, WebJobContext):
# Update the data with GET parameters
web_request = jc.get_web_request()
task_data = _get_data_from_args(args)
data = task_data.get_data()
data.update(web_request.args.to_dict(flat=True))
elif accept_only_web:
# Raise exception on non web usage if necessary
raise Exception("append_get_parameters decorator may be used "
"with GET requests only.")
return f(*args, **kwargs)
return append_get_parameters_wrapper_fn
return wrapper | [
"def",
"append_get_parameters",
"(",
"accept_only_web",
"=",
"True",
")",
":",
"# type: (bool) -> Callable",
"def",
"wrapper",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"append_get_parameters_wrapper_fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs"... | Task decorator which appends the GET data to the task data.
:param accept_only_web: Parameter which limits using this task only
with web requests. | [
"Task",
"decorator",
"which",
"appends",
"the",
"GET",
"data",
"to",
"the",
"task",
"data",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/task/task_decorator.py#L271-L301 | train | 42,529 |
AtteqCom/zsl | src/zsl/task/task_decorator.py | secured_task | def secured_task(f):
"""
Secured task decorator.
"""
@wraps(f)
def secured_task_decorator(*args, **kwargs):
task_data = _get_data_from_args(args)
assert isinstance(task_data, TaskData)
if not verify_security_data(task_data.get_data()['security']):
raise SecurityException(
task_data.get_data()['security']['hashed_token'])
task_data.transform_payload(lambda x: x['data'])
return f(*args, **kwargs)
return secured_task_decorator | python | def secured_task(f):
"""
Secured task decorator.
"""
@wraps(f)
def secured_task_decorator(*args, **kwargs):
task_data = _get_data_from_args(args)
assert isinstance(task_data, TaskData)
if not verify_security_data(task_data.get_data()['security']):
raise SecurityException(
task_data.get_data()['security']['hashed_token'])
task_data.transform_payload(lambda x: x['data'])
return f(*args, **kwargs)
return secured_task_decorator | [
"def",
"secured_task",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"secured_task_decorator",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"task_data",
"=",
"_get_data_from_args",
"(",
"args",
")",
"assert",
"isinstance",
"(",
"task_da... | Secured task decorator. | [
"Secured",
"task",
"decorator",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/task/task_decorator.py#L323-L339 | train | 42,530 |
AtteqCom/zsl | src/zsl/task/task_decorator.py | file_upload | def file_upload(f):
"""
Return list of `werkzeug.datastructures.FileStorage` objects - files to be
uploaded
"""
@wraps(f)
def file_upload_decorator(*args, **kwargs):
# If the data is already transformed, we do not transform it any
# further.
task_data = _get_data_from_args(args)
if task_data is None:
logging.error("Task data is empty during FilesUploadDecorator.")
task_data.transform_payload(lambda _: request.files.getlist('file'))
return f(*args, **kwargs)
return file_upload_decorator | python | def file_upload(f):
"""
Return list of `werkzeug.datastructures.FileStorage` objects - files to be
uploaded
"""
@wraps(f)
def file_upload_decorator(*args, **kwargs):
# If the data is already transformed, we do not transform it any
# further.
task_data = _get_data_from_args(args)
if task_data is None:
logging.error("Task data is empty during FilesUploadDecorator.")
task_data.transform_payload(lambda _: request.files.getlist('file'))
return f(*args, **kwargs)
return file_upload_decorator | [
"def",
"file_upload",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"file_upload_decorator",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# If the data is already transformed, we do not transform it any",
"# further.",
"task_data",
"=",
"_get_da... | Return list of `werkzeug.datastructures.FileStorage` objects - files to be
uploaded | [
"Return",
"list",
"of",
"werkzeug",
".",
"datastructures",
".",
"FileStorage",
"objects",
"-",
"files",
"to",
"be",
"uploaded"
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/task/task_decorator.py#L359-L377 | train | 42,531 |
AtteqCom/zsl | src/zsl/task/task_decorator.py | forbid_web_access | def forbid_web_access(f):
"""
Forbids running task using http request.
:param f: Callable
:return Callable
"""
@wraps(f)
def wrapper_fn(*args, **kwargs):
if isinstance(JobContext.get_current_context(), WebJobContext):
raise ForbiddenError('Access forbidden from web.')
return f(*args, **kwargs)
return wrapper_fn | python | def forbid_web_access(f):
"""
Forbids running task using http request.
:param f: Callable
:return Callable
"""
@wraps(f)
def wrapper_fn(*args, **kwargs):
if isinstance(JobContext.get_current_context(), WebJobContext):
raise ForbiddenError('Access forbidden from web.')
return f(*args, **kwargs)
return wrapper_fn | [
"def",
"forbid_web_access",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"wrapper_fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"JobContext",
".",
"get_current_context",
"(",
")",
",",
"WebJobContext",
")... | Forbids running task using http request.
:param f: Callable
:return Callable | [
"Forbids",
"running",
"task",
"using",
"http",
"request",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/task/task_decorator.py#L490-L505 | train | 42,532 |
AtteqCom/zsl | src/zsl/resource/resource_helper.py | filter_from_url_arg | def filter_from_url_arg(model_cls, query, arg, query_operator=and_,
arg_types=None):
"""
Parse filter URL argument ``arg`` and apply to ``query``
Example: 'column1<=value,column2==value' -> query.filter(Model.column1 <= value, Model.column2 == value)
"""
fields = arg.split(',')
mapper = class_mapper(model_cls)
if not arg_types:
arg_types = {}
exprs = []
joins = set()
for expr in fields:
if expr == "":
continue
e_mapper = mapper
e_model_cls = model_cls
operator = None
method = None
for op in operator_order:
if op in expr:
operator = op
method = operator_to_method[op]
break
if operator is None:
raise Exception('No operator in expression "{0}".'.format(expr))
(column_names, value) = expr.split(operator)
column_names = column_names.split('__')
value = value.strip()
for column_name in column_names:
if column_name in arg_types:
typed_value = arg_types[column_name](value)
else:
typed_value = value
if column_name in e_mapper.relationships:
joins.add(column_name)
e_model_cls = e_mapper.attrs[column_name].mapper.class_
e_mapper = class_mapper(e_model_cls)
if hasattr(e_model_cls, column_name):
column = getattr(e_model_cls, column_name)
exprs.append(getattr(column, method)(typed_value))
else:
raise Exception('Invalid property {0} in class {1}.'.format(column_name, e_model_cls))
return query.join(*joins).filter(query_operator(*exprs)) | python | def filter_from_url_arg(model_cls, query, arg, query_operator=and_,
arg_types=None):
"""
Parse filter URL argument ``arg`` and apply to ``query``
Example: 'column1<=value,column2==value' -> query.filter(Model.column1 <= value, Model.column2 == value)
"""
fields = arg.split(',')
mapper = class_mapper(model_cls)
if not arg_types:
arg_types = {}
exprs = []
joins = set()
for expr in fields:
if expr == "":
continue
e_mapper = mapper
e_model_cls = model_cls
operator = None
method = None
for op in operator_order:
if op in expr:
operator = op
method = operator_to_method[op]
break
if operator is None:
raise Exception('No operator in expression "{0}".'.format(expr))
(column_names, value) = expr.split(operator)
column_names = column_names.split('__')
value = value.strip()
for column_name in column_names:
if column_name in arg_types:
typed_value = arg_types[column_name](value)
else:
typed_value = value
if column_name in e_mapper.relationships:
joins.add(column_name)
e_model_cls = e_mapper.attrs[column_name].mapper.class_
e_mapper = class_mapper(e_model_cls)
if hasattr(e_model_cls, column_name):
column = getattr(e_model_cls, column_name)
exprs.append(getattr(column, method)(typed_value))
else:
raise Exception('Invalid property {0} in class {1}.'.format(column_name, e_model_cls))
return query.join(*joins).filter(query_operator(*exprs)) | [
"def",
"filter_from_url_arg",
"(",
"model_cls",
",",
"query",
",",
"arg",
",",
"query_operator",
"=",
"and_",
",",
"arg_types",
"=",
"None",
")",
":",
"fields",
"=",
"arg",
".",
"split",
"(",
"','",
")",
"mapper",
"=",
"class_mapper",
"(",
"model_cls",
"... | Parse filter URL argument ``arg`` and apply to ``query``
Example: 'column1<=value,column2==value' -> query.filter(Model.column1 <= value, Model.column2 == value) | [
"Parse",
"filter",
"URL",
"argument",
"arg",
"and",
"apply",
"to",
"query"
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/resource/resource_helper.py#L16-L72 | train | 42,533 |
AtteqCom/zsl | src/zsl/resource/resource_helper.py | model_tree | def model_tree(name, model_cls, visited=None):
"""Create a simple tree of model's properties and its related models.
It traverse trough relations, but ignore any loops.
:param name: name of the model
:type name: str
:param model_cls: model class
:param visited: set of visited models
:type visited: list or None
:return: a dictionary where values are lists of string or other \
dictionaries
"""
if not visited:
visited = set()
visited.add(model_cls)
mapper = class_mapper(model_cls)
columns = [column.key for column in mapper.column_attrs]
related = [model_tree(rel.key, rel.mapper.entity, visited)
for rel in mapper.relationships if rel.mapper.entity not in visited]
return {name: columns + related} | python | def model_tree(name, model_cls, visited=None):
"""Create a simple tree of model's properties and its related models.
It traverse trough relations, but ignore any loops.
:param name: name of the model
:type name: str
:param model_cls: model class
:param visited: set of visited models
:type visited: list or None
:return: a dictionary where values are lists of string or other \
dictionaries
"""
if not visited:
visited = set()
visited.add(model_cls)
mapper = class_mapper(model_cls)
columns = [column.key for column in mapper.column_attrs]
related = [model_tree(rel.key, rel.mapper.entity, visited)
for rel in mapper.relationships if rel.mapper.entity not in visited]
return {name: columns + related} | [
"def",
"model_tree",
"(",
"name",
",",
"model_cls",
",",
"visited",
"=",
"None",
")",
":",
"if",
"not",
"visited",
":",
"visited",
"=",
"set",
"(",
")",
"visited",
".",
"add",
"(",
"model_cls",
")",
"mapper",
"=",
"class_mapper",
"(",
"model_cls",
")",... | Create a simple tree of model's properties and its related models.
It traverse trough relations, but ignore any loops.
:param name: name of the model
:type name: str
:param model_cls: model class
:param visited: set of visited models
:type visited: list or None
:return: a dictionary where values are lists of string or other \
dictionaries | [
"Create",
"a",
"simple",
"tree",
"of",
"model",
"s",
"properties",
"and",
"its",
"related",
"models",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/resource/resource_helper.py#L147-L170 | train | 42,534 |
AtteqCom/zsl | src/zsl/resource/resource_helper.py | flat_model | def flat_model(tree):
"""Flatten the tree into a list of properties adding parents as prefixes."""
names = []
for columns in viewvalues(tree):
for col in columns:
if isinstance(col, dict):
col_name = list(col)[0]
names += [col_name + '__' + c for c in flat_model(col)]
else:
names.append(col)
return names | python | def flat_model(tree):
"""Flatten the tree into a list of properties adding parents as prefixes."""
names = []
for columns in viewvalues(tree):
for col in columns:
if isinstance(col, dict):
col_name = list(col)[0]
names += [col_name + '__' + c for c in flat_model(col)]
else:
names.append(col)
return names | [
"def",
"flat_model",
"(",
"tree",
")",
":",
"names",
"=",
"[",
"]",
"for",
"columns",
"in",
"viewvalues",
"(",
"tree",
")",
":",
"for",
"col",
"in",
"columns",
":",
"if",
"isinstance",
"(",
"col",
",",
"dict",
")",
":",
"col_name",
"=",
"list",
"("... | Flatten the tree into a list of properties adding parents as prefixes. | [
"Flatten",
"the",
"tree",
"into",
"a",
"list",
"of",
"properties",
"adding",
"parents",
"as",
"prefixes",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/resource/resource_helper.py#L173-L184 | train | 42,535 |
AtteqCom/zsl | src/zsl/interface/task_queue.py | execute_job | def execute_job(job, app=Injected, task_router=Injected):
# type: (Job, Zsl, TaskRouter) -> dict
"""Execute a job.
:param job: job to execute
:type job: Job
:param app: service application instance, injected
:type app: ServiceApplication
:param task_router: task router instance, injected
:type task_router: TaskRouter
:return: task result
:rtype: dict
"""
app.logger.info("Job fetched, preparing the task '{0}'.".format(job.path))
task, task_callable = task_router.route(job.path)
jc = JobContext(job, task, task_callable)
app.logger.info("Executing task.")
result = jc.task_callable(jc.task_data)
app.logger.info("Task {0} executed successfully.".format(job.path))
return {'task_name': job.path, 'data': result} | python | def execute_job(job, app=Injected, task_router=Injected):
# type: (Job, Zsl, TaskRouter) -> dict
"""Execute a job.
:param job: job to execute
:type job: Job
:param app: service application instance, injected
:type app: ServiceApplication
:param task_router: task router instance, injected
:type task_router: TaskRouter
:return: task result
:rtype: dict
"""
app.logger.info("Job fetched, preparing the task '{0}'.".format(job.path))
task, task_callable = task_router.route(job.path)
jc = JobContext(job, task, task_callable)
app.logger.info("Executing task.")
result = jc.task_callable(jc.task_data)
app.logger.info("Task {0} executed successfully.".format(job.path))
return {'task_name': job.path, 'data': result} | [
"def",
"execute_job",
"(",
"job",
",",
"app",
"=",
"Injected",
",",
"task_router",
"=",
"Injected",
")",
":",
"# type: (Job, Zsl, TaskRouter) -> dict",
"app",
".",
"logger",
".",
"info",
"(",
"\"Job fetched, preparing the task '{0}'.\"",
".",
"format",
"(",
"job",
... | Execute a job.
:param job: job to execute
:type job: Job
:param app: service application instance, injected
:type app: ServiceApplication
:param task_router: task router instance, injected
:type task_router: TaskRouter
:return: task result
:rtype: dict | [
"Execute",
"a",
"job",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/interface/task_queue.py#L28-L52 | train | 42,536 |
AtteqCom/zsl | src/zsl/interface/task_queue.py | TaskQueueWorker.handle_exception | def handle_exception(self, e, task_path):
# type: (Exception, str) -> dict
"""Handle exception raised during task execution.
:param e: exception
:type e: Exception
:param task_path: task path
:type task_path: str
:return: exception as task result
:rtype: dict
"""
self._app.logger.error(str(e) + "\n" + traceback.format_exc())
return {'task_name': task_path, 'data': None, 'error': str(e)} | python | def handle_exception(self, e, task_path):
# type: (Exception, str) -> dict
"""Handle exception raised during task execution.
:param e: exception
:type e: Exception
:param task_path: task path
:type task_path: str
:return: exception as task result
:rtype: dict
"""
self._app.logger.error(str(e) + "\n" + traceback.format_exc())
return {'task_name': task_path, 'data': None, 'error': str(e)} | [
"def",
"handle_exception",
"(",
"self",
",",
"e",
",",
"task_path",
")",
":",
"# type: (Exception, str) -> dict",
"self",
".",
"_app",
".",
"logger",
".",
"error",
"(",
"str",
"(",
"e",
")",
"+",
"\"\\n\"",
"+",
"traceback",
".",
"format_exc",
"(",
")",
... | Handle exception raised during task execution.
:param e: exception
:type e: Exception
:param task_path: task path
:type task_path: str
:return: exception as task result
:rtype: dict | [
"Handle",
"exception",
"raised",
"during",
"task",
"execution",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/interface/task_queue.py#L80-L93 | train | 42,537 |
AtteqCom/zsl | src/zsl/interface/task_queue.py | TaskQueueWorker.execute_job | def execute_job(self, job):
# type: (Job) -> dict
"""Execute job given by the task queue.
:param job: job
:type job: Job
:return: task result
:rtype: dict
"""
try:
return execute_job(job)
except KillWorkerException:
self._app.logger.info("Stopping Gearman worker on demand flag set.")
self.stop_worker()
except Exception as e:
return self.handle_exception(e, job.path) | python | def execute_job(self, job):
# type: (Job) -> dict
"""Execute job given by the task queue.
:param job: job
:type job: Job
:return: task result
:rtype: dict
"""
try:
return execute_job(job)
except KillWorkerException:
self._app.logger.info("Stopping Gearman worker on demand flag set.")
self.stop_worker()
except Exception as e:
return self.handle_exception(e, job.path) | [
"def",
"execute_job",
"(",
"self",
",",
"job",
")",
":",
"# type: (Job) -> dict",
"try",
":",
"return",
"execute_job",
"(",
"job",
")",
"except",
"KillWorkerException",
":",
"self",
".",
"_app",
".",
"logger",
".",
"info",
"(",
"\"Stopping Gearman worker on dema... | Execute job given by the task queue.
:param job: job
:type job: Job
:return: task result
:rtype: dict | [
"Execute",
"job",
"given",
"by",
"the",
"task",
"queue",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/interface/task_queue.py#L95-L112 | train | 42,538 |
datacamp/protowhat | protowhat/utils.py | legacy_signature | def legacy_signature(**kwargs_mapping):
"""
This decorator makes it possible to call a function using old argument names
when they are passed as keyword arguments.
@legacy_signature(old_arg1='arg1', old_arg2='arg2')
def func(arg1, arg2=1):
return arg1 + arg2
func(old_arg1=1) == 2
func(old_arg1=1, old_arg2=2) == 3
"""
def signature_decorator(f):
@wraps(f)
def wrapper(*args, **kwargs):
redirected_kwargs = {
kwargs_mapping[k] if k in kwargs_mapping else k: v
for k, v in kwargs.items()
}
return f(*args, **redirected_kwargs)
return wrapper
return signature_decorator | python | def legacy_signature(**kwargs_mapping):
"""
This decorator makes it possible to call a function using old argument names
when they are passed as keyword arguments.
@legacy_signature(old_arg1='arg1', old_arg2='arg2')
def func(arg1, arg2=1):
return arg1 + arg2
func(old_arg1=1) == 2
func(old_arg1=1, old_arg2=2) == 3
"""
def signature_decorator(f):
@wraps(f)
def wrapper(*args, **kwargs):
redirected_kwargs = {
kwargs_mapping[k] if k in kwargs_mapping else k: v
for k, v in kwargs.items()
}
return f(*args, **redirected_kwargs)
return wrapper
return signature_decorator | [
"def",
"legacy_signature",
"(",
"*",
"*",
"kwargs_mapping",
")",
":",
"def",
"signature_decorator",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"redirected_kwargs",
"=",
"{",
... | This decorator makes it possible to call a function using old argument names
when they are passed as keyword arguments.
@legacy_signature(old_arg1='arg1', old_arg2='arg2')
def func(arg1, arg2=1):
return arg1 + arg2
func(old_arg1=1) == 2
func(old_arg1=1, old_arg2=2) == 3 | [
"This",
"decorator",
"makes",
"it",
"possible",
"to",
"call",
"a",
"function",
"using",
"old",
"argument",
"names",
"when",
"they",
"are",
"passed",
"as",
"keyword",
"arguments",
"."
] | a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc | https://github.com/datacamp/protowhat/blob/a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc/protowhat/utils.py#L4-L28 | train | 42,539 |
AtteqCom/zsl | src/zsl/application/initializers/service_initializer.py | ServiceInitializer._bind_service | def _bind_service(package_name, cls_name, binder=Injected):
"""Bind service to application injector.
:param package_name: service package
:type package_name: str
:param cls_name: service class
:type cls_name: str
:param binder: current application binder, injected
:type binder: Binder
"""
module = importlib.import_module(package_name)
cls = getattr(module, cls_name)
binder.bind(
cls,
to=binder.injector.create_object(cls),
scope=singleton
)
logging.debug("Created {0} binding.".format(cls)) | python | def _bind_service(package_name, cls_name, binder=Injected):
"""Bind service to application injector.
:param package_name: service package
:type package_name: str
:param cls_name: service class
:type cls_name: str
:param binder: current application binder, injected
:type binder: Binder
"""
module = importlib.import_module(package_name)
cls = getattr(module, cls_name)
binder.bind(
cls,
to=binder.injector.create_object(cls),
scope=singleton
)
logging.debug("Created {0} binding.".format(cls)) | [
"def",
"_bind_service",
"(",
"package_name",
",",
"cls_name",
",",
"binder",
"=",
"Injected",
")",
":",
"module",
"=",
"importlib",
".",
"import_module",
"(",
"package_name",
")",
"cls",
"=",
"getattr",
"(",
"module",
",",
"cls_name",
")",
"binder",
".",
"... | Bind service to application injector.
:param package_name: service package
:type package_name: str
:param cls_name: service class
:type cls_name: str
:param binder: current application binder, injected
:type binder: Binder | [
"Bind",
"service",
"to",
"application",
"injector",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/application/initializers/service_initializer.py#L21-L39 | train | 42,540 |
AtteqCom/zsl | src/zsl/application/initializers/service_initializer.py | ServiceInitializer.initialize | def initialize(config):
"""Initialize method.
:param config: current application config, injected
:type config: Config
"""
service_injection_config = config.get('SERVICE_INJECTION', ())
if not isinstance(service_injection_config, (tuple, list)):
service_injection_config = (service_injection_config,)
for si_conf in service_injection_config:
if isinstance(si_conf, str):
package_name, cls_name = si_conf.rsplit('.', 1)
ServiceInitializer._bind_service(package_name, cls_name)
elif isinstance(si_conf, dict):
services = si_conf['list']
service_package = si_conf['package']
for cls_name in services:
module_name = camelcase_to_underscore(cls_name)
package_name = "{0}.{1}".format(service_package, module_name)
ServiceInitializer._bind_service(package_name, cls_name) | python | def initialize(config):
"""Initialize method.
:param config: current application config, injected
:type config: Config
"""
service_injection_config = config.get('SERVICE_INJECTION', ())
if not isinstance(service_injection_config, (tuple, list)):
service_injection_config = (service_injection_config,)
for si_conf in service_injection_config:
if isinstance(si_conf, str):
package_name, cls_name = si_conf.rsplit('.', 1)
ServiceInitializer._bind_service(package_name, cls_name)
elif isinstance(si_conf, dict):
services = si_conf['list']
service_package = si_conf['package']
for cls_name in services:
module_name = camelcase_to_underscore(cls_name)
package_name = "{0}.{1}".format(service_package, module_name)
ServiceInitializer._bind_service(package_name, cls_name) | [
"def",
"initialize",
"(",
"config",
")",
":",
"service_injection_config",
"=",
"config",
".",
"get",
"(",
"'SERVICE_INJECTION'",
",",
"(",
")",
")",
"if",
"not",
"isinstance",
"(",
"service_injection_config",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
... | Initialize method.
:param config: current application config, injected
:type config: Config | [
"Initialize",
"method",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/application/initializers/service_initializer.py#L43-L65 | train | 42,541 |
AtteqCom/zsl | src/zsl/resource/json_server_resource.py | _get_link_pages | def _get_link_pages(page, per_page, count, page_url):
# type: (int, int, int, str) -> Dict[str, str]
"""Create link header for page metadata.
:param page: current page
:param per_page: page limit
:param count: count of all resources
:param page_url: url for resources
:return: dictionary with name of the link as key and its url as value
"""
current_page = _page_arg(page)
links = {}
end = page * per_page
if page > 1:
links['prev'] = page_url.replace(current_page, _page_arg(page - 1))
if end < count:
links['next'] = page_url.replace(current_page, _page_arg(page + 1))
if per_page < count:
links['first'] = page_url.replace(current_page, _page_arg(1))
links['last'] = page_url.replace(current_page, _page_arg((count + per_page - 1) // per_page))
return links | python | def _get_link_pages(page, per_page, count, page_url):
# type: (int, int, int, str) -> Dict[str, str]
"""Create link header for page metadata.
:param page: current page
:param per_page: page limit
:param count: count of all resources
:param page_url: url for resources
:return: dictionary with name of the link as key and its url as value
"""
current_page = _page_arg(page)
links = {}
end = page * per_page
if page > 1:
links['prev'] = page_url.replace(current_page, _page_arg(page - 1))
if end < count:
links['next'] = page_url.replace(current_page, _page_arg(page + 1))
if per_page < count:
links['first'] = page_url.replace(current_page, _page_arg(1))
links['last'] = page_url.replace(current_page, _page_arg((count + per_page - 1) // per_page))
return links | [
"def",
"_get_link_pages",
"(",
"page",
",",
"per_page",
",",
"count",
",",
"page_url",
")",
":",
"# type: (int, int, int, str) -> Dict[str, str]",
"current_page",
"=",
"_page_arg",
"(",
"page",
")",
"links",
"=",
"{",
"}",
"end",
"=",
"page",
"*",
"per_page",
... | Create link header for page metadata.
:param page: current page
:param per_page: page limit
:param count: count of all resources
:param page_url: url for resources
:return: dictionary with name of the link as key and its url as value | [
"Create",
"link",
"header",
"for",
"page",
"metadata",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/resource/json_server_resource.py#L47-L71 | train | 42,542 |
AtteqCom/zsl | src/zsl/resource/json_server_resource.py | JsonServerResource.to_filter | def to_filter(self, query, arg):
"""Json-server filter using the _or_ operator."""
return filter_from_url_arg(self.model_cls, query, arg, query_operator=or_) | python | def to_filter(self, query, arg):
"""Json-server filter using the _or_ operator."""
return filter_from_url_arg(self.model_cls, query, arg, query_operator=or_) | [
"def",
"to_filter",
"(",
"self",
",",
"query",
",",
"arg",
")",
":",
"return",
"filter_from_url_arg",
"(",
"self",
".",
"model_cls",
",",
"query",
",",
"arg",
",",
"query_operator",
"=",
"or_",
")"
] | Json-server filter using the _or_ operator. | [
"Json",
"-",
"server",
"filter",
"using",
"the",
"_or_",
"operator",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/resource/json_server_resource.py#L81-L83 | train | 42,543 |
AtteqCom/zsl | src/zsl/resource/json_server_resource.py | JsonServerResource.create | def create(self, *args, **kwargs):
"""Adds created http status response and location link."""
resource = super(JsonServerResource, self).create(*args, **kwargs)
return ResourceResult(
body=resource,
status=get_http_status_code_value(http.client.CREATED),
location="{}/{}".format(request.url, resource.get_id())
) | python | def create(self, *args, **kwargs):
"""Adds created http status response and location link."""
resource = super(JsonServerResource, self).create(*args, **kwargs)
return ResourceResult(
body=resource,
status=get_http_status_code_value(http.client.CREATED),
location="{}/{}".format(request.url, resource.get_id())
) | [
"def",
"create",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"resource",
"=",
"super",
"(",
"JsonServerResource",
",",
"self",
")",
".",
"create",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"ResourceResult",
"(",
... | Adds created http status response and location link. | [
"Adds",
"created",
"http",
"status",
"response",
"and",
"location",
"link",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/resource/json_server_resource.py#L85-L93 | train | 42,544 |
AtteqCom/zsl | src/zsl/resource/json_server_resource.py | JsonServerResource._create_filter_by | def _create_filter_by(self):
"""Transform the json-server filter arguments to model-resource ones."""
filter_by = []
for name, values in request.args.copy().lists(): # copy.lists works in py2 and py3
if name not in _SKIPPED_ARGUMENTS:
column = _re_column_name.search(name).group(1)
if column not in self._model_columns:
continue
for value in values:
if name.endswith('_ne'):
filter_by.append(name[:-3] + '!=' + value)
elif name.endswith('_lte'):
filter_by.append(name[:-4] + '<=' + value)
elif name.endswith('_gte'):
filter_by.append(name[:-4] + '>=' + value)
elif name.endswith('_like'):
filter_by.append(name[:-5] + '::like::%' + value + '%')
else:
filter_by.append(name.replace('__', '.') + '==' + value)
filter_by += self._create_fulltext_query()
return ','.join(filter_by) | python | def _create_filter_by(self):
"""Transform the json-server filter arguments to model-resource ones."""
filter_by = []
for name, values in request.args.copy().lists(): # copy.lists works in py2 and py3
if name not in _SKIPPED_ARGUMENTS:
column = _re_column_name.search(name).group(1)
if column not in self._model_columns:
continue
for value in values:
if name.endswith('_ne'):
filter_by.append(name[:-3] + '!=' + value)
elif name.endswith('_lte'):
filter_by.append(name[:-4] + '<=' + value)
elif name.endswith('_gte'):
filter_by.append(name[:-4] + '>=' + value)
elif name.endswith('_like'):
filter_by.append(name[:-5] + '::like::%' + value + '%')
else:
filter_by.append(name.replace('__', '.') + '==' + value)
filter_by += self._create_fulltext_query()
return ','.join(filter_by) | [
"def",
"_create_filter_by",
"(",
"self",
")",
":",
"filter_by",
"=",
"[",
"]",
"for",
"name",
",",
"values",
"in",
"request",
".",
"args",
".",
"copy",
"(",
")",
".",
"lists",
"(",
")",
":",
"# copy.lists works in py2 and py3",
"if",
"name",
"not",
"in",... | Transform the json-server filter arguments to model-resource ones. | [
"Transform",
"the",
"json",
"-",
"server",
"filter",
"arguments",
"to",
"model",
"-",
"resource",
"ones",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/resource/json_server_resource.py#L95-L120 | train | 42,545 |
AtteqCom/zsl | src/zsl/resource/json_server_resource.py | JsonServerResource._create_related | def _create_related(args):
# type: (Dict) -> None
"""Create related field from `_embed` arguments."""
if '_embed' in request.args:
embeds = request.args.getlist('_embed')
args['related'] = ','.join(embeds)
del args['_embed'] | python | def _create_related(args):
# type: (Dict) -> None
"""Create related field from `_embed` arguments."""
if '_embed' in request.args:
embeds = request.args.getlist('_embed')
args['related'] = ','.join(embeds)
del args['_embed'] | [
"def",
"_create_related",
"(",
"args",
")",
":",
"# type: (Dict) -> None",
"if",
"'_embed'",
"in",
"request",
".",
"args",
":",
"embeds",
"=",
"request",
".",
"args",
".",
"getlist",
"(",
"'_embed'",
")",
"args",
"[",
"'related'",
"]",
"=",
"','",
".",
"... | Create related field from `_embed` arguments. | [
"Create",
"related",
"field",
"from",
"_embed",
"arguments",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/resource/json_server_resource.py#L123-L131 | train | 42,546 |
AtteqCom/zsl | src/zsl/resource/json_server_resource.py | JsonServerResource._create_fulltext_query | def _create_fulltext_query(self):
"""Support the json-server fulltext search with a broad LIKE filter."""
filter_by = []
if 'q' in request.args:
columns = flat_model(model_tree(self.__class__.__name__, self.model_cls))
for q in request.args.getlist('q'):
filter_by += ['{col}::like::%{q}%'.format(col=col, q=q) for col in columns]
return filter_by | python | def _create_fulltext_query(self):
"""Support the json-server fulltext search with a broad LIKE filter."""
filter_by = []
if 'q' in request.args:
columns = flat_model(model_tree(self.__class__.__name__, self.model_cls))
for q in request.args.getlist('q'):
filter_by += ['{col}::like::%{q}%'.format(col=col, q=q) for col in columns]
return filter_by | [
"def",
"_create_fulltext_query",
"(",
"self",
")",
":",
"filter_by",
"=",
"[",
"]",
"if",
"'q'",
"in",
"request",
".",
"args",
":",
"columns",
"=",
"flat_model",
"(",
"model_tree",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"self",
".",
"model_... | Support the json-server fulltext search with a broad LIKE filter. | [
"Support",
"the",
"json",
"-",
"server",
"fulltext",
"search",
"with",
"a",
"broad",
"LIKE",
"filter",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/resource/json_server_resource.py#L133-L142 | train | 42,547 |
AtteqCom/zsl | src/zsl/resource/json_server_resource.py | JsonServerResource._transform_list_args | def _transform_list_args(self, args):
# type: (dict) -> None
"""Transforms all list arguments from json-server to model-resource ones.
This modifies the given arguments.
"""
if '_limit' in args:
args['limit'] = int(args['_limit'])
del args['_limit']
if '_page' in args:
page = int(args['_page'])
if page < 0:
page = 1
args['page'] = page
del args['_page']
if 'limit' not in args:
args['limit'] = 10
if '_end' in args:
end = int(args['_end'])
args['limit'] = end - int(args.get('_start', 0))
if '_start' in args:
args['offset'] = args['_start']
del args['_start']
if '_sort' in args:
args['order_by'] = args['_sort'].replace('__', '.')
del args['_sort']
if args.get('_order', 'ASC') == 'DESC':
args['order_by'] = '-' + args['order_by']
if '_order' in args:
del args['_order']
filter_by = self._create_filter_by()
if filter_by:
args['filter_by'] = filter_by | python | def _transform_list_args(self, args):
# type: (dict) -> None
"""Transforms all list arguments from json-server to model-resource ones.
This modifies the given arguments.
"""
if '_limit' in args:
args['limit'] = int(args['_limit'])
del args['_limit']
if '_page' in args:
page = int(args['_page'])
if page < 0:
page = 1
args['page'] = page
del args['_page']
if 'limit' not in args:
args['limit'] = 10
if '_end' in args:
end = int(args['_end'])
args['limit'] = end - int(args.get('_start', 0))
if '_start' in args:
args['offset'] = args['_start']
del args['_start']
if '_sort' in args:
args['order_by'] = args['_sort'].replace('__', '.')
del args['_sort']
if args.get('_order', 'ASC') == 'DESC':
args['order_by'] = '-' + args['order_by']
if '_order' in args:
del args['_order']
filter_by = self._create_filter_by()
if filter_by:
args['filter_by'] = filter_by | [
"def",
"_transform_list_args",
"(",
"self",
",",
"args",
")",
":",
"# type: (dict) -> None",
"if",
"'_limit'",
"in",
"args",
":",
"args",
"[",
"'limit'",
"]",
"=",
"int",
"(",
"args",
"[",
"'_limit'",
"]",
")",
"del",
"args",
"[",
"'_limit'",
"]",
"if",
... | Transforms all list arguments from json-server to model-resource ones.
This modifies the given arguments. | [
"Transforms",
"all",
"list",
"arguments",
"from",
"json",
"-",
"server",
"to",
"model",
"-",
"resource",
"ones",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/resource/json_server_resource.py#L144-L186 | train | 42,548 |
AtteqCom/zsl | src/zsl/resource/json_server_resource.py | JsonServerResource.read | def read(self, params, args, data):
"""Modifies the parameters and adds metadata for read results."""
result_count = None
result_links = None
if params is None:
params = []
if args:
args = args.copy()
else:
args = {}
ctx = self._create_context(params, args, data)
row_id = ctx.get_row_id()
if not row_id:
self._transform_list_args(args)
if 'page' in args or 'limit' in args:
ctx = self._create_context(params, args, data)
result_count = self._get_collection_count(ctx)
if 'page' in args:
result_links = _get_link_pages(
page=args['page'],
per_page=int(args['limit']),
count=result_count,
page_url=request.url
)
if 'limit' not in args:
args['limit'] = 'unlimited'
self._create_related(args)
try:
return ResourceResult(
body=super(JsonServerResource, self).read(params, args, data),
count=result_count,
links=result_links
)
except NoResultFound:
return NOT_FOUND | python | def read(self, params, args, data):
"""Modifies the parameters and adds metadata for read results."""
result_count = None
result_links = None
if params is None:
params = []
if args:
args = args.copy()
else:
args = {}
ctx = self._create_context(params, args, data)
row_id = ctx.get_row_id()
if not row_id:
self._transform_list_args(args)
if 'page' in args or 'limit' in args:
ctx = self._create_context(params, args, data)
result_count = self._get_collection_count(ctx)
if 'page' in args:
result_links = _get_link_pages(
page=args['page'],
per_page=int(args['limit']),
count=result_count,
page_url=request.url
)
if 'limit' not in args:
args['limit'] = 'unlimited'
self._create_related(args)
try:
return ResourceResult(
body=super(JsonServerResource, self).read(params, args, data),
count=result_count,
links=result_links
)
except NoResultFound:
return NOT_FOUND | [
"def",
"read",
"(",
"self",
",",
"params",
",",
"args",
",",
"data",
")",
":",
"result_count",
"=",
"None",
"result_links",
"=",
"None",
"if",
"params",
"is",
"None",
":",
"params",
"=",
"[",
"]",
"if",
"args",
":",
"args",
"=",
"args",
".",
"copy"... | Modifies the parameters and adds metadata for read results. | [
"Modifies",
"the",
"parameters",
"and",
"adds",
"metadata",
"for",
"read",
"results",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/resource/json_server_resource.py#L188-L231 | train | 42,549 |
AtteqCom/zsl | src/zsl/resource/json_server_resource.py | JsonServerResource.update | def update(self, *args, **kwargs):
"""Modifies the parameters and adds metadata for update results.
Currently it does not support `PUT` method, which works as replacing
the resource. This is somehow questionable in relation DB.
"""
if request.method == 'PUT':
logging.warning("Called not implemented resource method PUT")
resource = super(JsonServerResource, self).update(*args, **kwargs)
if resource:
return resource
else:
return NOT_FOUND | python | def update(self, *args, **kwargs):
"""Modifies the parameters and adds metadata for update results.
Currently it does not support `PUT` method, which works as replacing
the resource. This is somehow questionable in relation DB.
"""
if request.method == 'PUT':
logging.warning("Called not implemented resource method PUT")
resource = super(JsonServerResource, self).update(*args, **kwargs)
if resource:
return resource
else:
return NOT_FOUND | [
"def",
"update",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"request",
".",
"method",
"==",
"'PUT'",
":",
"logging",
".",
"warning",
"(",
"\"Called not implemented resource method PUT\"",
")",
"resource",
"=",
"super",
"(",
"Js... | Modifies the parameters and adds metadata for update results.
Currently it does not support `PUT` method, which works as replacing
the resource. This is somehow questionable in relation DB. | [
"Modifies",
"the",
"parameters",
"and",
"adds",
"metadata",
"for",
"update",
"results",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/resource/json_server_resource.py#L233-L247 | train | 42,550 |
AtteqCom/zsl | src/zsl/resource/json_server_resource.py | JsonServerResource.delete | def delete(self, params, args, data):
"""Supports only singular delete and adds proper http status."""
ctx = self._create_context(params, args, data)
row_id = ctx.get_row_id()
if row_id:
deleted = self._delete_one(row_id, ctx)
if deleted:
return ResourceResult(body={})
else:
return NOT_FOUND
else:
return NOT_FOUND | python | def delete(self, params, args, data):
"""Supports only singular delete and adds proper http status."""
ctx = self._create_context(params, args, data)
row_id = ctx.get_row_id()
if row_id:
deleted = self._delete_one(row_id, ctx)
if deleted:
return ResourceResult(body={})
else:
return NOT_FOUND
else:
return NOT_FOUND | [
"def",
"delete",
"(",
"self",
",",
"params",
",",
"args",
",",
"data",
")",
":",
"ctx",
"=",
"self",
".",
"_create_context",
"(",
"params",
",",
"args",
",",
"data",
")",
"row_id",
"=",
"ctx",
".",
"get_row_id",
"(",
")",
"if",
"row_id",
":",
"dele... | Supports only singular delete and adds proper http status. | [
"Supports",
"only",
"singular",
"delete",
"and",
"adds",
"proper",
"http",
"status",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/resource/json_server_resource.py#L250-L263 | train | 42,551 |
briney/abutils | abutils/plots/summary.py | _aggregate | def _aggregate(data, norm=True, sort_by='value', keys=None):
'''
Counts the number of occurances of each item in 'data'.
Inputs
data: a list of values.
norm: normalize the resulting counts (as percent)
sort_by: how to sort the retured data. Options are 'value' and 'count'.
Output
a non-redundant list of values (from 'data') and a list of counts.
'''
if keys:
vdict = {k: 0 for k in keys}
for d in data:
if d in keys:
vdict[d] += 1
else:
vdict = {}
for d in data:
vdict[d] = vdict[d] + 1 if d in vdict else 1
vals = [(k, v) for k, v in vdict.items()]
if sort_by == 'value':
vals.sort(key=lambda x: x[0])
else:
vals.sort(key=lambda x: x[1])
xs = [v[0] for v in vals]
if norm:
raw_y = [v[1] for v in vals]
total_y = sum(raw_y)
ys = [100. * y / total_y for y in raw_y]
else:
ys = [v[1] for v in vals]
return xs, ys | python | def _aggregate(data, norm=True, sort_by='value', keys=None):
'''
Counts the number of occurances of each item in 'data'.
Inputs
data: a list of values.
norm: normalize the resulting counts (as percent)
sort_by: how to sort the retured data. Options are 'value' and 'count'.
Output
a non-redundant list of values (from 'data') and a list of counts.
'''
if keys:
vdict = {k: 0 for k in keys}
for d in data:
if d in keys:
vdict[d] += 1
else:
vdict = {}
for d in data:
vdict[d] = vdict[d] + 1 if d in vdict else 1
vals = [(k, v) for k, v in vdict.items()]
if sort_by == 'value':
vals.sort(key=lambda x: x[0])
else:
vals.sort(key=lambda x: x[1])
xs = [v[0] for v in vals]
if norm:
raw_y = [v[1] for v in vals]
total_y = sum(raw_y)
ys = [100. * y / total_y for y in raw_y]
else:
ys = [v[1] for v in vals]
return xs, ys | [
"def",
"_aggregate",
"(",
"data",
",",
"norm",
"=",
"True",
",",
"sort_by",
"=",
"'value'",
",",
"keys",
"=",
"None",
")",
":",
"if",
"keys",
":",
"vdict",
"=",
"{",
"k",
":",
"0",
"for",
"k",
"in",
"keys",
"}",
"for",
"d",
"in",
"data",
":",
... | Counts the number of occurances of each item in 'data'.
Inputs
data: a list of values.
norm: normalize the resulting counts (as percent)
sort_by: how to sort the retured data. Options are 'value' and 'count'.
Output
a non-redundant list of values (from 'data') and a list of counts. | [
"Counts",
"the",
"number",
"of",
"occurances",
"of",
"each",
"item",
"in",
"data",
"."
] | 944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b | https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/plots/summary.py#L111-L144 | train | 42,552 |
AtteqCom/zsl | src/zsl/utils/deploy/apiari_doc_generator.py | generate_apiary_doc | def generate_apiary_doc(task_router):
"""Generate apiary documentation.
Create a Apiary generator and add application packages to it.
:param task_router: task router, injected
:type task_router: TaskRouter
:return: apiary generator
:rtype: ApiaryDoc
"""
generator = ApiaryDoc()
for m in task_router.get_task_packages() + get_method_packages():
m = importlib.import_module(m)
generator.docmodule(m)
return generator | python | def generate_apiary_doc(task_router):
"""Generate apiary documentation.
Create a Apiary generator and add application packages to it.
:param task_router: task router, injected
:type task_router: TaskRouter
:return: apiary generator
:rtype: ApiaryDoc
"""
generator = ApiaryDoc()
for m in task_router.get_task_packages() + get_method_packages():
m = importlib.import_module(m)
generator.docmodule(m)
return generator | [
"def",
"generate_apiary_doc",
"(",
"task_router",
")",
":",
"generator",
"=",
"ApiaryDoc",
"(",
")",
"for",
"m",
"in",
"task_router",
".",
"get_task_packages",
"(",
")",
"+",
"get_method_packages",
"(",
")",
":",
"m",
"=",
"importlib",
".",
"import_module",
... | Generate apiary documentation.
Create a Apiary generator and add application packages to it.
:param task_router: task router, injected
:type task_router: TaskRouter
:return: apiary generator
:rtype: ApiaryDoc | [
"Generate",
"apiary",
"documentation",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/deploy/apiari_doc_generator.py#L120-L136 | train | 42,553 |
briney/abutils | abutils/utils/log.py | setup_logging | def setup_logging(logfile, print_log_location=True, debug=False):
'''
Set up logging using the built-in ``logging`` package.
A stream handler is added to all logs, so that logs at or above
``logging.INFO`` level are printed to screen as well as written
to the log file.
Arguments:
logfile (str): Path to the log file. If the parent directory
does not exist, it will be created. Required.
print_log_location (bool): If ``True``, the log path will be
written to the log upon initialization. Default is ``True``.
debug (bool): If true, the log level will be set to ``logging.DEBUG``.
If ``False``, the log level will be set to ``logging.INFO``.
Default is ``False``.
'''
log_dir = os.path.dirname(logfile)
make_dir(log_dir)
fmt = '[%(levelname)s] %(name)s %(asctime)s %(message)s'
if debug:
logging.basicConfig(filename=logfile,
filemode='w',
format=fmt,
level=logging.DEBUG)
else:
logging.basicConfig(filename=logfile,
filemode='w',
format=fmt,
level=logging.INFO)
logger = logging.getLogger('log')
logger = add_stream_handler(logger)
if print_log_location:
logger.info('LOG LOCATION: {}'.format(logfile)) | python | def setup_logging(logfile, print_log_location=True, debug=False):
'''
Set up logging using the built-in ``logging`` package.
A stream handler is added to all logs, so that logs at or above
``logging.INFO`` level are printed to screen as well as written
to the log file.
Arguments:
logfile (str): Path to the log file. If the parent directory
does not exist, it will be created. Required.
print_log_location (bool): If ``True``, the log path will be
written to the log upon initialization. Default is ``True``.
debug (bool): If true, the log level will be set to ``logging.DEBUG``.
If ``False``, the log level will be set to ``logging.INFO``.
Default is ``False``.
'''
log_dir = os.path.dirname(logfile)
make_dir(log_dir)
fmt = '[%(levelname)s] %(name)s %(asctime)s %(message)s'
if debug:
logging.basicConfig(filename=logfile,
filemode='w',
format=fmt,
level=logging.DEBUG)
else:
logging.basicConfig(filename=logfile,
filemode='w',
format=fmt,
level=logging.INFO)
logger = logging.getLogger('log')
logger = add_stream_handler(logger)
if print_log_location:
logger.info('LOG LOCATION: {}'.format(logfile)) | [
"def",
"setup_logging",
"(",
"logfile",
",",
"print_log_location",
"=",
"True",
",",
"debug",
"=",
"False",
")",
":",
"log_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"logfile",
")",
"make_dir",
"(",
"log_dir",
")",
"fmt",
"=",
"'[%(levelname)s] %(n... | Set up logging using the built-in ``logging`` package.
A stream handler is added to all logs, so that logs at or above
``logging.INFO`` level are printed to screen as well as written
to the log file.
Arguments:
logfile (str): Path to the log file. If the parent directory
does not exist, it will be created. Required.
print_log_location (bool): If ``True``, the log path will be
written to the log upon initialization. Default is ``True``.
debug (bool): If true, the log level will be set to ``logging.DEBUG``.
If ``False``, the log level will be set to ``logging.INFO``.
Default is ``False``. | [
"Set",
"up",
"logging",
"using",
"the",
"built",
"-",
"in",
"logging",
"package",
"."
] | 944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b | https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/utils/log.py#L34-L70 | train | 42,554 |
briney/abutils | abutils/utils/log.py | get_logger | def get_logger(name=None):
'''
Get a logging handle.
As with ``setup_logging``, a stream handler is added to the
log handle.
Arguments:
name (str): Name of the log handle. Default is ``None``.
'''
logger = logging.getLogger(name)
if len(logger.handlers) == 0:
logger = add_stream_handler(logger)
return logger | python | def get_logger(name=None):
'''
Get a logging handle.
As with ``setup_logging``, a stream handler is added to the
log handle.
Arguments:
name (str): Name of the log handle. Default is ``None``.
'''
logger = logging.getLogger(name)
if len(logger.handlers) == 0:
logger = add_stream_handler(logger)
return logger | [
"def",
"get_logger",
"(",
"name",
"=",
"None",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"name",
")",
"if",
"len",
"(",
"logger",
".",
"handlers",
")",
"==",
"0",
":",
"logger",
"=",
"add_stream_handler",
"(",
"logger",
")",
"return",
... | Get a logging handle.
As with ``setup_logging``, a stream handler is added to the
log handle.
Arguments:
name (str): Name of the log handle. Default is ``None``. | [
"Get",
"a",
"logging",
"handle",
"."
] | 944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b | https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/utils/log.py#L73-L87 | train | 42,555 |
AtteqCom/zsl | src/zsl/utils/injection_helper.py | inject | def inject(**bindings):
"""
Decorator for injecting parameters for ASL objects.
"""
def outer_wrapper(f):
def function_wrapper(ff):
for key, value in viewitems(bindings):
bindings[key] = BindingKey(value)
@functools.wraps(ff)
def _inject(*args, **kwargs):
inj = get_current_app().injector
dependencies = inj.args_to_inject(
function=ff,
bindings=bindings,
owner_key=ff
)
dependencies.update(kwargs)
try:
return ff(*args, **dependencies)
except TypeError as e:
reraise(e, CallError(ff, args, dependencies, e))
return _inject
'''
Just a convenience method - delegates everything to wrapper.
'''
def method_or_class_wrapper(*a, **kwargs):
"""
Properly installs the injector into the object so that the injection can be performed.
"""
inj = get_current_app().injector
# Install injector into the self instance if this is a method call.
inj.install_into(a[0])
# Use the generic wrapper.
inject_f = injector.inject(**bindings)
# Call the method.
return inject_f(f)(*a, **kwargs)
if inspect.ismethod(f):
return method_or_class_wrapper
else:
return function_wrapper(f)
return outer_wrapper | python | def inject(**bindings):
"""
Decorator for injecting parameters for ASL objects.
"""
def outer_wrapper(f):
def function_wrapper(ff):
for key, value in viewitems(bindings):
bindings[key] = BindingKey(value)
@functools.wraps(ff)
def _inject(*args, **kwargs):
inj = get_current_app().injector
dependencies = inj.args_to_inject(
function=ff,
bindings=bindings,
owner_key=ff
)
dependencies.update(kwargs)
try:
return ff(*args, **dependencies)
except TypeError as e:
reraise(e, CallError(ff, args, dependencies, e))
return _inject
'''
Just a convenience method - delegates everything to wrapper.
'''
def method_or_class_wrapper(*a, **kwargs):
"""
Properly installs the injector into the object so that the injection can be performed.
"""
inj = get_current_app().injector
# Install injector into the self instance if this is a method call.
inj.install_into(a[0])
# Use the generic wrapper.
inject_f = injector.inject(**bindings)
# Call the method.
return inject_f(f)(*a, **kwargs)
if inspect.ismethod(f):
return method_or_class_wrapper
else:
return function_wrapper(f)
return outer_wrapper | [
"def",
"inject",
"(",
"*",
"*",
"bindings",
")",
":",
"def",
"outer_wrapper",
"(",
"f",
")",
":",
"def",
"function_wrapper",
"(",
"ff",
")",
":",
"for",
"key",
",",
"value",
"in",
"viewitems",
"(",
"bindings",
")",
":",
"bindings",
"[",
"key",
"]",
... | Decorator for injecting parameters for ASL objects. | [
"Decorator",
"for",
"injecting",
"parameters",
"for",
"ASL",
"objects",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/injection_helper.py#L33-L81 | train | 42,556 |
briney/abutils | abutils/utils/phylogeny.py | igphyml | def igphyml(input_file=None, tree_file=None, root=None, verbose=False):
'''
Computes a phylogenetic tree using IgPhyML.
.. note::
IgPhyML must be installed. It can be downloaded from https://github.com/kbhoehn/IgPhyML.
Args:
input_file (str): Path to a Phylip-formatted multiple sequence alignment. Required.
tree_file (str): Path to the output tree file.
root (str): Name of the root sequence. Required.
verbose (bool): If `True`, prints the standard output and standard error for each IgPhyML run.
Default is `False`.
'''
if shutil.which('igphyml') is None:
raise RuntimeError('It appears that IgPhyML is not installed.\nPlease install and try again.')
# first, tree topology is estimated with the M0/GY94 model
igphyml_cmd1 = 'igphyml -i {} -m GY -w M0 -t e --run_id gy94'.format(aln_file)
p1 = sp.Popen(igphyml_cmd1, stdout=sp.PIPE, stderr=sp.PIPE)
stdout1, stderr1 = p1.communicate()
if verbose:
print(stdout1 + '\n')
print(stderr1 + '\n\n')
intermediate = input_file + '_igphyml_tree.txt_gy94'
# now we fit the HLP17 model once the tree topology is fixed
igphyml_cmd2 = 'igphyml -i {0} -m HLP17 --root {1} -o lr -u {}_igphyml_tree.txt_gy94 -o {}'.format(input_file,
root,
tree_file)
p2 = sp.Popen(igphyml_cmd2, stdout=sp.PIPE, stderr=sp.PIPE)
stdout2, stderr2 = p2.communicate()
if verbose:
print(stdout2 + '\n')
print(stderr2 + '\n')
return tree_file + '_igphyml_tree.txt' | python | def igphyml(input_file=None, tree_file=None, root=None, verbose=False):
'''
Computes a phylogenetic tree using IgPhyML.
.. note::
IgPhyML must be installed. It can be downloaded from https://github.com/kbhoehn/IgPhyML.
Args:
input_file (str): Path to a Phylip-formatted multiple sequence alignment. Required.
tree_file (str): Path to the output tree file.
root (str): Name of the root sequence. Required.
verbose (bool): If `True`, prints the standard output and standard error for each IgPhyML run.
Default is `False`.
'''
if shutil.which('igphyml') is None:
raise RuntimeError('It appears that IgPhyML is not installed.\nPlease install and try again.')
# first, tree topology is estimated with the M0/GY94 model
igphyml_cmd1 = 'igphyml -i {} -m GY -w M0 -t e --run_id gy94'.format(aln_file)
p1 = sp.Popen(igphyml_cmd1, stdout=sp.PIPE, stderr=sp.PIPE)
stdout1, stderr1 = p1.communicate()
if verbose:
print(stdout1 + '\n')
print(stderr1 + '\n\n')
intermediate = input_file + '_igphyml_tree.txt_gy94'
# now we fit the HLP17 model once the tree topology is fixed
igphyml_cmd2 = 'igphyml -i {0} -m HLP17 --root {1} -o lr -u {}_igphyml_tree.txt_gy94 -o {}'.format(input_file,
root,
tree_file)
p2 = sp.Popen(igphyml_cmd2, stdout=sp.PIPE, stderr=sp.PIPE)
stdout2, stderr2 = p2.communicate()
if verbose:
print(stdout2 + '\n')
print(stderr2 + '\n')
return tree_file + '_igphyml_tree.txt' | [
"def",
"igphyml",
"(",
"input_file",
"=",
"None",
",",
"tree_file",
"=",
"None",
",",
"root",
"=",
"None",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"shutil",
".",
"which",
"(",
"'igphyml'",
")",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"... | Computes a phylogenetic tree using IgPhyML.
.. note::
IgPhyML must be installed. It can be downloaded from https://github.com/kbhoehn/IgPhyML.
Args:
input_file (str): Path to a Phylip-formatted multiple sequence alignment. Required.
tree_file (str): Path to the output tree file.
root (str): Name of the root sequence. Required.
verbose (bool): If `True`, prints the standard output and standard error for each IgPhyML run.
Default is `False`. | [
"Computes",
"a",
"phylogenetic",
"tree",
"using",
"IgPhyML",
"."
] | 944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b | https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/utils/phylogeny.py#L452-L493 | train | 42,557 |
AtteqCom/zsl | src/zsl/utils/deploy/integrator.py | integrate_to_file | def integrate_to_file(what, filename, start_line, end_line):
"""WARNING this is working every second run.. so serious bug
Integrate content into a file withing "line marks"
"""
try:
with open(filename) as f:
lines = f.readlines()
except IOError:
lines = []
tmp_file = tempfile.NamedTemporaryFile(delete=False)
lines.reverse()
# first copy before start line
while lines:
line = lines.pop()
if line == start_line:
break
tmp_file.write(line)
# insert content
tmp_file.write(start_line)
tmp_file.write(what)
tmp_file.write(end_line)
# skip until end line
while lines:
line = lines.pop()
if line == end_line:
break
# copy rest
tmp_file.writelines(lines)
tmp_file.close()
os.rename(tmp_file.name, filename) | python | def integrate_to_file(what, filename, start_line, end_line):
"""WARNING this is working every second run.. so serious bug
Integrate content into a file withing "line marks"
"""
try:
with open(filename) as f:
lines = f.readlines()
except IOError:
lines = []
tmp_file = tempfile.NamedTemporaryFile(delete=False)
lines.reverse()
# first copy before start line
while lines:
line = lines.pop()
if line == start_line:
break
tmp_file.write(line)
# insert content
tmp_file.write(start_line)
tmp_file.write(what)
tmp_file.write(end_line)
# skip until end line
while lines:
line = lines.pop()
if line == end_line:
break
# copy rest
tmp_file.writelines(lines)
tmp_file.close()
os.rename(tmp_file.name, filename) | [
"def",
"integrate_to_file",
"(",
"what",
",",
"filename",
",",
"start_line",
",",
"end_line",
")",
":",
"try",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"f",
":",
"lines",
"=",
"f",
".",
"readlines",
"(",
")",
"except",
"IOError",
":",
"lines",
... | WARNING this is working every second run.. so serious bug
Integrate content into a file withing "line marks" | [
"WARNING",
"this",
"is",
"working",
"every",
"second",
"run",
"..",
"so",
"serious",
"bug",
"Integrate",
"content",
"into",
"a",
"file",
"withing",
"line",
"marks"
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/deploy/integrator.py#L12-L52 | train | 42,558 |
AtteqCom/zsl | src/zsl/utils/model_helper.py | update_model | def update_model(raw_model, app_model, forbidden_keys=None, inverse=False):
"""Updates the `raw_model` according to the values in the `app_model`.
:param raw_model: Raw model which gets updated.
:param app_model: App model holding the data.
:param forbidden_keys: Data/attributes which will not be updated.
:type forbidden_keys: list
:param inverse: If the value is `True` all `app_model` attributes which are contained in the `raw_model` are
updated. If the value is `False` all `raw_model` properties which are in the `app_model` will be
updated.
"""
if forbidden_keys is None:
forbidden_keys = []
if type(app_model) != dict:
app_model = app_model.__dict__
if inverse:
for k in app_model:
logging.debug("Considering property {0}.".format(k))
if (hasattr(raw_model, k)) and (k not in forbidden_keys):
logging.debug("Setting property {0} to value '{1}'.".format(k, app_model[k]))
setattr(raw_model, k, app_model[k])
else:
for k in raw_model.__dict__:
logging.debug("Considering property {0}.".format(k))
if (k in app_model) and (k not in forbidden_keys):
logging.debug("Setting property {0} to value '{1}'.".format(k, app_model[k]))
setattr(raw_model, k, app_model[k]) | python | def update_model(raw_model, app_model, forbidden_keys=None, inverse=False):
"""Updates the `raw_model` according to the values in the `app_model`.
:param raw_model: Raw model which gets updated.
:param app_model: App model holding the data.
:param forbidden_keys: Data/attributes which will not be updated.
:type forbidden_keys: list
:param inverse: If the value is `True` all `app_model` attributes which are contained in the `raw_model` are
updated. If the value is `False` all `raw_model` properties which are in the `app_model` will be
updated.
"""
if forbidden_keys is None:
forbidden_keys = []
if type(app_model) != dict:
app_model = app_model.__dict__
if inverse:
for k in app_model:
logging.debug("Considering property {0}.".format(k))
if (hasattr(raw_model, k)) and (k not in forbidden_keys):
logging.debug("Setting property {0} to value '{1}'.".format(k, app_model[k]))
setattr(raw_model, k, app_model[k])
else:
for k in raw_model.__dict__:
logging.debug("Considering property {0}.".format(k))
if (k in app_model) and (k not in forbidden_keys):
logging.debug("Setting property {0} to value '{1}'.".format(k, app_model[k]))
setattr(raw_model, k, app_model[k]) | [
"def",
"update_model",
"(",
"raw_model",
",",
"app_model",
",",
"forbidden_keys",
"=",
"None",
",",
"inverse",
"=",
"False",
")",
":",
"if",
"forbidden_keys",
"is",
"None",
":",
"forbidden_keys",
"=",
"[",
"]",
"if",
"type",
"(",
"app_model",
")",
"!=",
... | Updates the `raw_model` according to the values in the `app_model`.
:param raw_model: Raw model which gets updated.
:param app_model: App model holding the data.
:param forbidden_keys: Data/attributes which will not be updated.
:type forbidden_keys: list
:param inverse: If the value is `True` all `app_model` attributes which are contained in the `raw_model` are
updated. If the value is `False` all `raw_model` properties which are in the `app_model` will be
updated. | [
"Updates",
"the",
"raw_model",
"according",
"to",
"the",
"values",
"in",
"the",
"app_model",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/model_helper.py#L13-L41 | train | 42,559 |
briney/abutils | abutils/utils/progbar.py | progress_bar | def progress_bar(finished, total, start_time=None, extra_info=None,
autocomplete=True, completion_string='/n'):
'''
Prints an ASCII progress bar.
Each call to ``progress_bar`` will update the progress bar. An example
of tracking the progress of a list of items would look like::
job_list = [job1, job2, job3, ... jobN]
total_jobs = len(job_list)
#initialize the progress bar
progress_bar(0, total_jobs)
# do the jobs
for i, job in enumerate(job_list):
do_job(job)
progress_bar(i + 1, total_jobs)
Args:
finished (int): Number of finished jobs.
total (int): Total number of jobs.
start_time (datetime): Start time, as a ``datetime.datetime`` object.
Only required if you want to display execution time alongside
the progress bar. If not provided, execution time is not shown.
extra_info (str): A string containing extra information to be displayed
at the end of the progbar string. Examples include the number of failed
jobs, the name of the job batch currently being processed, etc.
complete (bool): If `True`, will append `completion_string` to the end
of the progbar string.
completion_string (str): Will be appended to the progbar string if
`complete` is `True`. Default is `'\n\n'`.
'''
pct = int(100. * finished / total)
ticks = int(pct / 2)
spaces = int(50 - ticks)
if start_time is not None:
elapsed = (datetime.now() - start_time).seconds
minutes = int(elapsed / 60)
seconds = int(elapsed % 60)
minute_str = '0' * (2 - len(str(minutes))) + str(minutes)
second_str = '0' * (2 - len(str(seconds))) + str(seconds)
prog_bar = '\r({}/{}) |{}{}| {}% ({}:{}) '.format(finished, total,
'|' * ticks, ' ' * spaces, pct, minute_str, second_str)
else:
prog_bar = '\r({}/{}) |{}{}| {}% '.format(finished, total,
'|' * ticks, ' ' * spaces, pct)
if extra_info is not None:
prog_bar += str(extra_info)
if autocomplete and finished == total:
prog_bar += completion_string
sys.stdout.write(prog_bar)
sys.stdout.flush() | python | def progress_bar(finished, total, start_time=None, extra_info=None,
autocomplete=True, completion_string='/n'):
'''
Prints an ASCII progress bar.
Each call to ``progress_bar`` will update the progress bar. An example
of tracking the progress of a list of items would look like::
job_list = [job1, job2, job3, ... jobN]
total_jobs = len(job_list)
#initialize the progress bar
progress_bar(0, total_jobs)
# do the jobs
for i, job in enumerate(job_list):
do_job(job)
progress_bar(i + 1, total_jobs)
Args:
finished (int): Number of finished jobs.
total (int): Total number of jobs.
start_time (datetime): Start time, as a ``datetime.datetime`` object.
Only required if you want to display execution time alongside
the progress bar. If not provided, execution time is not shown.
extra_info (str): A string containing extra information to be displayed
at the end of the progbar string. Examples include the number of failed
jobs, the name of the job batch currently being processed, etc.
complete (bool): If `True`, will append `completion_string` to the end
of the progbar string.
completion_string (str): Will be appended to the progbar string if
`complete` is `True`. Default is `'\n\n'`.
'''
pct = int(100. * finished / total)
ticks = int(pct / 2)
spaces = int(50 - ticks)
if start_time is not None:
elapsed = (datetime.now() - start_time).seconds
minutes = int(elapsed / 60)
seconds = int(elapsed % 60)
minute_str = '0' * (2 - len(str(minutes))) + str(minutes)
second_str = '0' * (2 - len(str(seconds))) + str(seconds)
prog_bar = '\r({}/{}) |{}{}| {}% ({}:{}) '.format(finished, total,
'|' * ticks, ' ' * spaces, pct, minute_str, second_str)
else:
prog_bar = '\r({}/{}) |{}{}| {}% '.format(finished, total,
'|' * ticks, ' ' * spaces, pct)
if extra_info is not None:
prog_bar += str(extra_info)
if autocomplete and finished == total:
prog_bar += completion_string
sys.stdout.write(prog_bar)
sys.stdout.flush() | [
"def",
"progress_bar",
"(",
"finished",
",",
"total",
",",
"start_time",
"=",
"None",
",",
"extra_info",
"=",
"None",
",",
"autocomplete",
"=",
"True",
",",
"completion_string",
"=",
"'/n'",
")",
":",
"pct",
"=",
"int",
"(",
"100.",
"*",
"finished",
"/",... | Prints an ASCII progress bar.
Each call to ``progress_bar`` will update the progress bar. An example
of tracking the progress of a list of items would look like::
job_list = [job1, job2, job3, ... jobN]
total_jobs = len(job_list)
#initialize the progress bar
progress_bar(0, total_jobs)
# do the jobs
for i, job in enumerate(job_list):
do_job(job)
progress_bar(i + 1, total_jobs)
Args:
finished (int): Number of finished jobs.
total (int): Total number of jobs.
start_time (datetime): Start time, as a ``datetime.datetime`` object.
Only required if you want to display execution time alongside
the progress bar. If not provided, execution time is not shown.
extra_info (str): A string containing extra information to be displayed
at the end of the progbar string. Examples include the number of failed
jobs, the name of the job batch currently being processed, etc.
complete (bool): If `True`, will append `completion_string` to the end
of the progbar string.
completion_string (str): Will be appended to the progbar string if
`complete` is `True`. Default is `'\n\n'`. | [
"Prints",
"an",
"ASCII",
"progress",
"bar",
"."
] | 944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b | https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/utils/progbar.py#L32-L91 | train | 42,560 |
AtteqCom/zsl | src/zsl/db/model/raw_model.py | ModelBase.update | def update(self, app_model, forbidden_keys=None, inverse=False):
"""
Updates the raw model. Consult `zsl.utils.model_helper.update_model`.
"""
if forbidden_keys is None:
forbidden_keys = []
update_model(self, app_model, forbidden_keys, inverse) | python | def update(self, app_model, forbidden_keys=None, inverse=False):
"""
Updates the raw model. Consult `zsl.utils.model_helper.update_model`.
"""
if forbidden_keys is None:
forbidden_keys = []
update_model(self, app_model, forbidden_keys, inverse) | [
"def",
"update",
"(",
"self",
",",
"app_model",
",",
"forbidden_keys",
"=",
"None",
",",
"inverse",
"=",
"False",
")",
":",
"if",
"forbidden_keys",
"is",
"None",
":",
"forbidden_keys",
"=",
"[",
"]",
"update_model",
"(",
"self",
",",
"app_model",
",",
"f... | Updates the raw model. Consult `zsl.utils.model_helper.update_model`. | [
"Updates",
"the",
"raw",
"model",
".",
"Consult",
"zsl",
".",
"utils",
".",
"model_helper",
".",
"update_model",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/db/model/raw_model.py#L15-L22 | train | 42,561 |
AtteqCom/zsl | src/zsl/utils/xml_to_json.py | _parse_dict | def _parse_dict(element, definition):
"""Parse xml element by a definition given in dict format.
:param element: ElementTree element
:param definition: definition schema
:type definition: dict
:return: parsed xml
:rtype: dict
"""
sub_dict = {}
for name, subdef in viewitems(definition):
(name, required) = _parse_name(name)
sub_dict[name] = xml_to_json(element, subdef, required)
return sub_dict | python | def _parse_dict(element, definition):
"""Parse xml element by a definition given in dict format.
:param element: ElementTree element
:param definition: definition schema
:type definition: dict
:return: parsed xml
:rtype: dict
"""
sub_dict = {}
for name, subdef in viewitems(definition):
(name, required) = _parse_name(name)
sub_dict[name] = xml_to_json(element, subdef, required)
return sub_dict | [
"def",
"_parse_dict",
"(",
"element",
",",
"definition",
")",
":",
"sub_dict",
"=",
"{",
"}",
"for",
"name",
",",
"subdef",
"in",
"viewitems",
"(",
"definition",
")",
":",
"(",
"name",
",",
"required",
")",
"=",
"_parse_name",
"(",
"name",
")",
"sub_di... | Parse xml element by a definition given in dict format.
:param element: ElementTree element
:param definition: definition schema
:type definition: dict
:return: parsed xml
:rtype: dict | [
"Parse",
"xml",
"element",
"by",
"a",
"definition",
"given",
"in",
"dict",
"format",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/xml_to_json.py#L84-L100 | train | 42,562 |
AtteqCom/zsl | src/zsl/utils/xml_to_json.py | _parse_tuple | def _parse_tuple(element, definition, required):
"""Parse xml element by a definition given in tuple format.
:param element: ElementTree element
:param definition: definition schema
:type definition: tuple
:param required: parsed value should be not None
:type required: bool
:return: parsed xml
"""
# TODO needs to be documented properly.
d_len = len(definition)
if d_len == 0:
return None
if d_len == 1:
return xml_to_json(element, definition[0], required)
first = definition[0]
if hasattr(first, '__call__'):
# TODO I think it could be done without creating the array
# first(xml_to_json(element, d) for d in definition[1:]) test it
return first(*[xml_to_json(element, d) for d in definition[1:]])
if not isinstance(first, str):
raise XmlToJsonException('Tuple definition must start with function or string')
if first[0] == '@':
raise XmlToJsonException('Tuple definition must not start with attribute')
sub_elem = element.find(first)
if sub_elem is None:
if required:
raise NotCompleteXmlException('Expecting {0} in element {1}'.format(first, element.tag))
return None
return xml_to_json(sub_elem, definition[1], required) | python | def _parse_tuple(element, definition, required):
"""Parse xml element by a definition given in tuple format.
:param element: ElementTree element
:param definition: definition schema
:type definition: tuple
:param required: parsed value should be not None
:type required: bool
:return: parsed xml
"""
# TODO needs to be documented properly.
d_len = len(definition)
if d_len == 0:
return None
if d_len == 1:
return xml_to_json(element, definition[0], required)
first = definition[0]
if hasattr(first, '__call__'):
# TODO I think it could be done without creating the array
# first(xml_to_json(element, d) for d in definition[1:]) test it
return first(*[xml_to_json(element, d) for d in definition[1:]])
if not isinstance(first, str):
raise XmlToJsonException('Tuple definition must start with function or string')
if first[0] == '@':
raise XmlToJsonException('Tuple definition must not start with attribute')
sub_elem = element.find(first)
if sub_elem is None:
if required:
raise NotCompleteXmlException('Expecting {0} in element {1}'.format(first, element.tag))
return None
return xml_to_json(sub_elem, definition[1], required) | [
"def",
"_parse_tuple",
"(",
"element",
",",
"definition",
",",
"required",
")",
":",
"# TODO needs to be documented properly.",
"d_len",
"=",
"len",
"(",
"definition",
")",
"if",
"d_len",
"==",
"0",
":",
"return",
"None",
"if",
"d_len",
"==",
"1",
":",
"retu... | Parse xml element by a definition given in tuple format.
:param element: ElementTree element
:param definition: definition schema
:type definition: tuple
:param required: parsed value should be not None
:type required: bool
:return: parsed xml | [
"Parse",
"xml",
"element",
"by",
"a",
"definition",
"given",
"in",
"tuple",
"format",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/xml_to_json.py#L103-L142 | train | 42,563 |
AtteqCom/zsl | src/zsl/utils/xml_to_json.py | _parse_list | def _parse_list(element, definition):
"""Parse xml element by definition given by list.
Find all elements matched by the string given as the first value
in the list (as XPath or @attribute).
If there is a second argument it will be handled as a definitions
for the elements matched or the text when not.
:param element: ElementTree element
:param definition: definition schema
:type definition: list
:return: parsed xml
:rtype: list
"""
if len(definition) == 0:
raise XmlToJsonException('List definition needs some definition')
tag = definition[0]
tag_def = definition[1] if len(definition) > 1 else None
sub_list = []
for el in element.findall(tag):
sub_list.append(xml_to_json(el, tag_def))
return sub_list | python | def _parse_list(element, definition):
"""Parse xml element by definition given by list.
Find all elements matched by the string given as the first value
in the list (as XPath or @attribute).
If there is a second argument it will be handled as a definitions
for the elements matched or the text when not.
:param element: ElementTree element
:param definition: definition schema
:type definition: list
:return: parsed xml
:rtype: list
"""
if len(definition) == 0:
raise XmlToJsonException('List definition needs some definition')
tag = definition[0]
tag_def = definition[1] if len(definition) > 1 else None
sub_list = []
for el in element.findall(tag):
sub_list.append(xml_to_json(el, tag_def))
return sub_list | [
"def",
"_parse_list",
"(",
"element",
",",
"definition",
")",
":",
"if",
"len",
"(",
"definition",
")",
"==",
"0",
":",
"raise",
"XmlToJsonException",
"(",
"'List definition needs some definition'",
")",
"tag",
"=",
"definition",
"[",
"0",
"]",
"tag_def",
"=",... | Parse xml element by definition given by list.
Find all elements matched by the string given as the first value
in the list (as XPath or @attribute).
If there is a second argument it will be handled as a definitions
for the elements matched or the text when not.
:param element: ElementTree element
:param definition: definition schema
:type definition: list
:return: parsed xml
:rtype: list | [
"Parse",
"xml",
"element",
"by",
"definition",
"given",
"by",
"list",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/xml_to_json.py#L145-L171 | train | 42,564 |
AtteqCom/zsl | src/zsl/utils/xml_to_json.py | _parse_name | def _parse_name(name):
"""Parse name in complex dict definition.
In complex definition required params can be marked with `*`.
:param name:
:return: name and required flag
:rtype: tuple
"""
required = False
if name[-1] == '*':
name = name[0:-1]
required = True
return name, required | python | def _parse_name(name):
"""Parse name in complex dict definition.
In complex definition required params can be marked with `*`.
:param name:
:return: name and required flag
:rtype: tuple
"""
required = False
if name[-1] == '*':
name = name[0:-1]
required = True
return name, required | [
"def",
"_parse_name",
"(",
"name",
")",
":",
"required",
"=",
"False",
"if",
"name",
"[",
"-",
"1",
"]",
"==",
"'*'",
":",
"name",
"=",
"name",
"[",
"0",
":",
"-",
"1",
"]",
"required",
"=",
"True",
"return",
"name",
",",
"required"
] | Parse name in complex dict definition.
In complex definition required params can be marked with `*`.
:param name:
:return: name and required flag
:rtype: tuple | [
"Parse",
"name",
"in",
"complex",
"dict",
"definition",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/xml_to_json.py#L174-L189 | train | 42,565 |
briney/abutils | abutils/core/lineage.py | Lineage.name | def name(self):
'''
Returns the lineage name, or None if the name cannot be found.
'''
clonify_ids = [p.heavy['clonify']['id'] for p in self.heavies if 'clonify' in p.heavy]
if len(clonify_ids) > 0:
return clonify_ids[0]
return None | python | def name(self):
'''
Returns the lineage name, or None if the name cannot be found.
'''
clonify_ids = [p.heavy['clonify']['id'] for p in self.heavies if 'clonify' in p.heavy]
if len(clonify_ids) > 0:
return clonify_ids[0]
return None | [
"def",
"name",
"(",
"self",
")",
":",
"clonify_ids",
"=",
"[",
"p",
".",
"heavy",
"[",
"'clonify'",
"]",
"[",
"'id'",
"]",
"for",
"p",
"in",
"self",
".",
"heavies",
"if",
"'clonify'",
"in",
"p",
".",
"heavy",
"]",
"if",
"len",
"(",
"clonify_ids",
... | Returns the lineage name, or None if the name cannot be found. | [
"Returns",
"the",
"lineage",
"name",
"or",
"None",
"if",
"the",
"name",
"cannot",
"be",
"found",
"."
] | 944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b | https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/core/lineage.py#L170-L177 | train | 42,566 |
briney/abutils | abutils/core/lineage.py | Lineage.verified_pairs | def verified_pairs(self):
'''
Returns all lineage Pair objects that contain verified pairings.
'''
if not hasattr(self.just_pairs[0], 'verified'):
self.verify_light_chains()
return [p for p in self.just_pairs if p.verified] | python | def verified_pairs(self):
'''
Returns all lineage Pair objects that contain verified pairings.
'''
if not hasattr(self.just_pairs[0], 'verified'):
self.verify_light_chains()
return [p for p in self.just_pairs if p.verified] | [
"def",
"verified_pairs",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
".",
"just_pairs",
"[",
"0",
"]",
",",
"'verified'",
")",
":",
"self",
".",
"verify_light_chains",
"(",
")",
"return",
"[",
"p",
"for",
"p",
"in",
"self",
".",
"just... | Returns all lineage Pair objects that contain verified pairings. | [
"Returns",
"all",
"lineage",
"Pair",
"objects",
"that",
"contain",
"verified",
"pairings",
"."
] | 944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b | https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/core/lineage.py#L188-L194 | train | 42,567 |
briney/abutils | abutils/core/lineage.py | Lineage.size | def size(self, pairs_only=False):
'''
Calculate the size of the lineage.
Inputs (optional)
-----------------
pairs_only: count only paired sequences
Returns
-------
Lineage size (int)
'''
if pairs_only:
return len(self.just_pairs)
else:
return len(self.heavies) | python | def size(self, pairs_only=False):
'''
Calculate the size of the lineage.
Inputs (optional)
-----------------
pairs_only: count only paired sequences
Returns
-------
Lineage size (int)
'''
if pairs_only:
return len(self.just_pairs)
else:
return len(self.heavies) | [
"def",
"size",
"(",
"self",
",",
"pairs_only",
"=",
"False",
")",
":",
"if",
"pairs_only",
":",
"return",
"len",
"(",
"self",
".",
"just_pairs",
")",
"else",
":",
"return",
"len",
"(",
"self",
".",
"heavies",
")"
] | Calculate the size of the lineage.
Inputs (optional)
-----------------
pairs_only: count only paired sequences
Returns
-------
Lineage size (int) | [
"Calculate",
"the",
"size",
"of",
"the",
"lineage",
"."
] | 944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b | https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/core/lineage.py#L273-L288 | train | 42,568 |
briney/abutils | abutils/core/lineage.py | Lineage.dot_alignment | def dot_alignment(self, seq_field='vdj_nt', name_field='seq_id', uca=None,
chain='heavy', uca_name='UCA', as_fasta=False, just_alignment=False):
'''
Returns a multiple sequence alignment of all lineage sequence with the UCA
where matches to the UCA are shown as dots and mismatches are shown as the
mismatched residue.
Inputs (optional)
-----------------
seq_field: the sequence field to be used for alignment. Default is 'vdj_nt'.
name_field: field used for the sequence name. Default is 'seq_id'.
chain: either 'heavy' or 'light'. Default is 'heavy'.
Returns
-------
The dot alignment (string)
'''
if uca is None:
uca = self.uca.heavy if chain == 'heavy' else self.uca.light
uca.id = 'UCA'
if chain == 'heavy':
sequences = [p.heavy for p in self.heavies if seq_field in p.heavy]
if name_field != 'seq_id':
uca[name_field] = uca['seq_id']
sequences.append(uca)
seqs = [(s[name_field], s[seq_field]) for s in sequences]
else:
sequences = [p.light for p in self.lights if seq_field in p.light]
if name_field != 'seq_id':
uca[name_field] = uca['seq_id']
sequences.append(uca)
seqs = [(s[name_field], s[seq_field]) for s in sequences]
aln = muscle(seqs)
g_aln = [a for a in aln if a.id == 'UCA'][0]
dots = [(uca_name, str(g_aln.seq)), ]
for seq in [a for a in aln if a.id != 'UCA']:
s_aln = ''
for g, q in zip(str(g_aln.seq), str(seq.seq)):
if g == q == '-':
s_aln += '-'
elif g == q:
s_aln += '.'
else:
s_aln += q
dots.append((seq.id, s_aln))
if just_alignment:
return [d[1] for d in dots]
name_len = max([len(d[0]) for d in dots]) + 2
dot_aln = []
for d in dots:
if as_fasta:
dot_aln.append('>{}\n{}'.format(d[0], d[1]))
else:
spaces = name_len - len(d[0])
dot_aln.append(d[0] + ' ' * spaces + d[1])
return '\n'.join(dot_aln) | python | def dot_alignment(self, seq_field='vdj_nt', name_field='seq_id', uca=None,
chain='heavy', uca_name='UCA', as_fasta=False, just_alignment=False):
'''
Returns a multiple sequence alignment of all lineage sequence with the UCA
where matches to the UCA are shown as dots and mismatches are shown as the
mismatched residue.
Inputs (optional)
-----------------
seq_field: the sequence field to be used for alignment. Default is 'vdj_nt'.
name_field: field used for the sequence name. Default is 'seq_id'.
chain: either 'heavy' or 'light'. Default is 'heavy'.
Returns
-------
The dot alignment (string)
'''
if uca is None:
uca = self.uca.heavy if chain == 'heavy' else self.uca.light
uca.id = 'UCA'
if chain == 'heavy':
sequences = [p.heavy for p in self.heavies if seq_field in p.heavy]
if name_field != 'seq_id':
uca[name_field] = uca['seq_id']
sequences.append(uca)
seqs = [(s[name_field], s[seq_field]) for s in sequences]
else:
sequences = [p.light for p in self.lights if seq_field in p.light]
if name_field != 'seq_id':
uca[name_field] = uca['seq_id']
sequences.append(uca)
seqs = [(s[name_field], s[seq_field]) for s in sequences]
aln = muscle(seqs)
g_aln = [a for a in aln if a.id == 'UCA'][0]
dots = [(uca_name, str(g_aln.seq)), ]
for seq in [a for a in aln if a.id != 'UCA']:
s_aln = ''
for g, q in zip(str(g_aln.seq), str(seq.seq)):
if g == q == '-':
s_aln += '-'
elif g == q:
s_aln += '.'
else:
s_aln += q
dots.append((seq.id, s_aln))
if just_alignment:
return [d[1] for d in dots]
name_len = max([len(d[0]) for d in dots]) + 2
dot_aln = []
for d in dots:
if as_fasta:
dot_aln.append('>{}\n{}'.format(d[0], d[1]))
else:
spaces = name_len - len(d[0])
dot_aln.append(d[0] + ' ' * spaces + d[1])
return '\n'.join(dot_aln) | [
"def",
"dot_alignment",
"(",
"self",
",",
"seq_field",
"=",
"'vdj_nt'",
",",
"name_field",
"=",
"'seq_id'",
",",
"uca",
"=",
"None",
",",
"chain",
"=",
"'heavy'",
",",
"uca_name",
"=",
"'UCA'",
",",
"as_fasta",
"=",
"False",
",",
"just_alignment",
"=",
"... | Returns a multiple sequence alignment of all lineage sequence with the UCA
where matches to the UCA are shown as dots and mismatches are shown as the
mismatched residue.
Inputs (optional)
-----------------
seq_field: the sequence field to be used for alignment. Default is 'vdj_nt'.
name_field: field used for the sequence name. Default is 'seq_id'.
chain: either 'heavy' or 'light'. Default is 'heavy'.
Returns
-------
The dot alignment (string) | [
"Returns",
"a",
"multiple",
"sequence",
"alignment",
"of",
"all",
"lineage",
"sequence",
"with",
"the",
"UCA",
"where",
"matches",
"to",
"the",
"UCA",
"are",
"shown",
"as",
"dots",
"and",
"mismatches",
"are",
"shown",
"as",
"the",
"mismatched",
"residue",
".... | 944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b | https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/core/lineage.py#L311-L366 | train | 42,569 |
datacamp/protowhat | protowhat/State.py | State.to_child | def to_child(self, append_message="", **kwargs):
"""Basic implementation of returning a child state"""
bad_pars = set(kwargs) - set(self._child_params)
if bad_pars:
raise KeyError("Invalid init params for State: %s" % ", ".join(bad_pars))
child = copy(self)
for k, v in kwargs.items():
setattr(child, k, v)
child.parent = self
# append messages
if not isinstance(append_message, dict):
append_message = {"msg": append_message, "kwargs": {}}
child.messages = [*self.messages, append_message]
return child | python | def to_child(self, append_message="", **kwargs):
"""Basic implementation of returning a child state"""
bad_pars = set(kwargs) - set(self._child_params)
if bad_pars:
raise KeyError("Invalid init params for State: %s" % ", ".join(bad_pars))
child = copy(self)
for k, v in kwargs.items():
setattr(child, k, v)
child.parent = self
# append messages
if not isinstance(append_message, dict):
append_message = {"msg": append_message, "kwargs": {}}
child.messages = [*self.messages, append_message]
return child | [
"def",
"to_child",
"(",
"self",
",",
"append_message",
"=",
"\"\"",
",",
"*",
"*",
"kwargs",
")",
":",
"bad_pars",
"=",
"set",
"(",
"kwargs",
")",
"-",
"set",
"(",
"self",
".",
"_child_params",
")",
"if",
"bad_pars",
":",
"raise",
"KeyError",
"(",
"\... | Basic implementation of returning a child state | [
"Basic",
"implementation",
"of",
"returning",
"a",
"child",
"state"
] | a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc | https://github.com/datacamp/protowhat/blob/a392b4e51e07a2e50e7b7f6ad918b3f5cbb63edc/protowhat/State.py#L120-L137 | train | 42,570 |
AtteqCom/zsl | src/zsl/utils/rss.py | complex_el_from_dict | def complex_el_from_dict(parent, data, key):
"""Create element from a dict definition and add it to ``parent``.
:param parent: parent element
:type parent: Element
:param data: dictionary with elements definitions, it can be a simple \
{element_name: 'element_value'} or complex \
{element_name: {_attr: {name: value, name1: value1}, _text: 'text'}}
:param key: element name and key in ``data``
:return: created element
"""
el = ET.SubElement(parent, key)
value = data[key]
if isinstance(value, dict):
if '_attr' in value:
for a_name, a_value in viewitems(value['_attr']):
el.set(a_name, a_value)
if '_text' in value:
el.text = value['_text']
else:
el.text = value
return el | python | def complex_el_from_dict(parent, data, key):
"""Create element from a dict definition and add it to ``parent``.
:param parent: parent element
:type parent: Element
:param data: dictionary with elements definitions, it can be a simple \
{element_name: 'element_value'} or complex \
{element_name: {_attr: {name: value, name1: value1}, _text: 'text'}}
:param key: element name and key in ``data``
:return: created element
"""
el = ET.SubElement(parent, key)
value = data[key]
if isinstance(value, dict):
if '_attr' in value:
for a_name, a_value in viewitems(value['_attr']):
el.set(a_name, a_value)
if '_text' in value:
el.text = value['_text']
else:
el.text = value
return el | [
"def",
"complex_el_from_dict",
"(",
"parent",
",",
"data",
",",
"key",
")",
":",
"el",
"=",
"ET",
".",
"SubElement",
"(",
"parent",
",",
"key",
")",
"value",
"=",
"data",
"[",
"key",
"]",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"if... | Create element from a dict definition and add it to ``parent``.
:param parent: parent element
:type parent: Element
:param data: dictionary with elements definitions, it can be a simple \
{element_name: 'element_value'} or complex \
{element_name: {_attr: {name: value, name1: value1}, _text: 'text'}}
:param key: element name and key in ``data``
:return: created element | [
"Create",
"element",
"from",
"a",
"dict",
"definition",
"and",
"add",
"it",
"to",
"parent",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/rss.py#L16-L41 | train | 42,571 |
AtteqCom/zsl | src/zsl/utils/rss.py | rss_create | def rss_create(channel, articles):
"""Create RSS xml feed.
:param channel: channel info [title, link, description, language]
:type channel: dict(str, str)
:param articles: list of articles, an article is a dictionary with some \
required fields [title, description, link] and any optional, which will \
result to `<dict_key>dict_value</dict_key>`
:type articles: list(dict(str,str))
:return: root element
:rtype: ElementTree.Element
"""
channel = channel.copy()
# TODO use deepcopy
# list will not clone the dictionaries in the list and `elemen_from_dict`
# pops items from them
articles = list(articles)
rss = ET.Element('rss')
rss.set('version', '2.0')
channel_node = ET.SubElement(rss, 'channel')
element_from_dict(channel_node, channel, 'title')
element_from_dict(channel_node, channel, 'link')
element_from_dict(channel_node, channel, 'description')
element_from_dict(channel_node, channel, 'language')
for article in articles:
item = ET.SubElement(channel_node, 'item')
element_from_dict(item, article, 'title')
element_from_dict(item, article, 'description')
element_from_dict(item, article, 'link')
for key in article:
complex_el_from_dict(item, article, key)
return ET.ElementTree(rss) | python | def rss_create(channel, articles):
"""Create RSS xml feed.
:param channel: channel info [title, link, description, language]
:type channel: dict(str, str)
:param articles: list of articles, an article is a dictionary with some \
required fields [title, description, link] and any optional, which will \
result to `<dict_key>dict_value</dict_key>`
:type articles: list(dict(str,str))
:return: root element
:rtype: ElementTree.Element
"""
channel = channel.copy()
# TODO use deepcopy
# list will not clone the dictionaries in the list and `elemen_from_dict`
# pops items from them
articles = list(articles)
rss = ET.Element('rss')
rss.set('version', '2.0')
channel_node = ET.SubElement(rss, 'channel')
element_from_dict(channel_node, channel, 'title')
element_from_dict(channel_node, channel, 'link')
element_from_dict(channel_node, channel, 'description')
element_from_dict(channel_node, channel, 'language')
for article in articles:
item = ET.SubElement(channel_node, 'item')
element_from_dict(item, article, 'title')
element_from_dict(item, article, 'description')
element_from_dict(item, article, 'link')
for key in article:
complex_el_from_dict(item, article, key)
return ET.ElementTree(rss) | [
"def",
"rss_create",
"(",
"channel",
",",
"articles",
")",
":",
"channel",
"=",
"channel",
".",
"copy",
"(",
")",
"# TODO use deepcopy",
"# list will not clone the dictionaries in the list and `elemen_from_dict`",
"# pops items from them",
"articles",
"=",
"list",
"(",
"a... | Create RSS xml feed.
:param channel: channel info [title, link, description, language]
:type channel: dict(str, str)
:param articles: list of articles, an article is a dictionary with some \
required fields [title, description, link] and any optional, which will \
result to `<dict_key>dict_value</dict_key>`
:type articles: list(dict(str,str))
:return: root element
:rtype: ElementTree.Element | [
"Create",
"RSS",
"xml",
"feed",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/rss.py#L62-L101 | train | 42,572 |
AtteqCom/zsl | src/zsl/utils/security_helper.py | compute_token | def compute_token(random_token, config):
"""Compute a hash of the given token with a preconfigured secret.
:param random_token: random token
:type random_token: str
:return: hashed token
:rtype: str
"""
secure_token = config[TOKEN_SERVICE_SECURITY_CONFIG]
sha1hash = hashlib.sha1()
sha1hash.update(random_token + secure_token)
return sha1hash.hexdigest().upper() | python | def compute_token(random_token, config):
"""Compute a hash of the given token with a preconfigured secret.
:param random_token: random token
:type random_token: str
:return: hashed token
:rtype: str
"""
secure_token = config[TOKEN_SERVICE_SECURITY_CONFIG]
sha1hash = hashlib.sha1()
sha1hash.update(random_token + secure_token)
return sha1hash.hexdigest().upper() | [
"def",
"compute_token",
"(",
"random_token",
",",
"config",
")",
":",
"secure_token",
"=",
"config",
"[",
"TOKEN_SERVICE_SECURITY_CONFIG",
"]",
"sha1hash",
"=",
"hashlib",
".",
"sha1",
"(",
")",
"sha1hash",
".",
"update",
"(",
"random_token",
"+",
"secure_token"... | Compute a hash of the given token with a preconfigured secret.
:param random_token: random token
:type random_token: str
:return: hashed token
:rtype: str | [
"Compute",
"a",
"hash",
"of",
"the",
"given",
"token",
"with",
"a",
"preconfigured",
"secret",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/security_helper.py#L44-L55 | train | 42,573 |
AtteqCom/zsl | src/zsl/utils/security_helper.py | verify_security_data | def verify_security_data(security):
"""Verify an untrusted security token.
:param security: security token
:type security: dict
:return: True if valid
:rtype: bool
"""
random_token = security[TOKEN_RANDOM]
hashed_token = security[TOKEN_HASHED]
return str(hashed_token) == str(compute_token(random_token)) | python | def verify_security_data(security):
"""Verify an untrusted security token.
:param security: security token
:type security: dict
:return: True if valid
:rtype: bool
"""
random_token = security[TOKEN_RANDOM]
hashed_token = security[TOKEN_HASHED]
return str(hashed_token) == str(compute_token(random_token)) | [
"def",
"verify_security_data",
"(",
"security",
")",
":",
"random_token",
"=",
"security",
"[",
"TOKEN_RANDOM",
"]",
"hashed_token",
"=",
"security",
"[",
"TOKEN_HASHED",
"]",
"return",
"str",
"(",
"hashed_token",
")",
"==",
"str",
"(",
"compute_token",
"(",
"... | Verify an untrusted security token.
:param security: security token
:type security: dict
:return: True if valid
:rtype: bool | [
"Verify",
"an",
"untrusted",
"security",
"token",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/security_helper.py#L58-L68 | train | 42,574 |
briney/abutils | abutils/utils/pipeline.py | initialize | def initialize(log_file, project_dir=None, debug=False):
'''
Initializes an AbTools pipeline.
Initialization includes printing the AbTools splash, setting up logging,
creating the project directory, and logging both the project directory
and the log location.
Args:
log_file (str): Path to the log file. Required.
project_dir (str): Path to the project directory. If not provided,
the project directory won't be created and the location won't be logged.
debug (bool): If ``True``, the logging level will be set to ``logging.DEBUG``.
Default is ``FALSE``, which logs at ``logging.INFO``.
Returns:
logger
'''
print_splash()
log.setup_logging(log_file, print_log_location=False, debug=debug)
logger = log.get_logger('pipeline')
if project_dir is not None:
make_dir(os.path.normpath(project_dir))
logger.info('PROJECT DIRECTORY: {}'.format(project_dir))
logger.info('')
logger.info('LOG LOCATION: {}'.format(log_file))
print('')
return logger | python | def initialize(log_file, project_dir=None, debug=False):
'''
Initializes an AbTools pipeline.
Initialization includes printing the AbTools splash, setting up logging,
creating the project directory, and logging both the project directory
and the log location.
Args:
log_file (str): Path to the log file. Required.
project_dir (str): Path to the project directory. If not provided,
the project directory won't be created and the location won't be logged.
debug (bool): If ``True``, the logging level will be set to ``logging.DEBUG``.
Default is ``FALSE``, which logs at ``logging.INFO``.
Returns:
logger
'''
print_splash()
log.setup_logging(log_file, print_log_location=False, debug=debug)
logger = log.get_logger('pipeline')
if project_dir is not None:
make_dir(os.path.normpath(project_dir))
logger.info('PROJECT DIRECTORY: {}'.format(project_dir))
logger.info('')
logger.info('LOG LOCATION: {}'.format(log_file))
print('')
return logger | [
"def",
"initialize",
"(",
"log_file",
",",
"project_dir",
"=",
"None",
",",
"debug",
"=",
"False",
")",
":",
"print_splash",
"(",
")",
"log",
".",
"setup_logging",
"(",
"log_file",
",",
"print_log_location",
"=",
"False",
",",
"debug",
"=",
"debug",
")",
... | Initializes an AbTools pipeline.
Initialization includes printing the AbTools splash, setting up logging,
creating the project directory, and logging both the project directory
and the log location.
Args:
log_file (str): Path to the log file. Required.
project_dir (str): Path to the project directory. If not provided,
the project directory won't be created and the location won't be logged.
debug (bool): If ``True``, the logging level will be set to ``logging.DEBUG``.
Default is ``FALSE``, which logs at ``logging.INFO``.
Returns:
logger | [
"Initializes",
"an",
"AbTools",
"pipeline",
"."
] | 944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b | https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/utils/pipeline.py#L40-L71 | train | 42,575 |
briney/abutils | abutils/utils/pipeline.py | list_files | def list_files(d, extension=None):
'''
Lists files in a given directory.
Args:
d (str): Path to a directory.
extension (str): If supplied, only files that contain the
specificied extension will be returned. Default is ``False``,
which returns all files in ``d``.
Returns:
list: A sorted list of file paths.
'''
if os.path.isdir(d):
expanded_dir = os.path.expanduser(d)
files = sorted(glob.glob(expanded_dir + '/*'))
else:
files = [d, ]
if extension is not None:
if type(extension) in STR_TYPES:
extension = [extension, ]
files = [f for f in files if any([f.split('.')[-1] in extension,
f.split('.')[-1].upper() in extension,
f.split('.')[-1].lower() in extension])]
return files | python | def list_files(d, extension=None):
'''
Lists files in a given directory.
Args:
d (str): Path to a directory.
extension (str): If supplied, only files that contain the
specificied extension will be returned. Default is ``False``,
which returns all files in ``d``.
Returns:
list: A sorted list of file paths.
'''
if os.path.isdir(d):
expanded_dir = os.path.expanduser(d)
files = sorted(glob.glob(expanded_dir + '/*'))
else:
files = [d, ]
if extension is not None:
if type(extension) in STR_TYPES:
extension = [extension, ]
files = [f for f in files if any([f.split('.')[-1] in extension,
f.split('.')[-1].upper() in extension,
f.split('.')[-1].lower() in extension])]
return files | [
"def",
"list_files",
"(",
"d",
",",
"extension",
"=",
"None",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"d",
")",
":",
"expanded_dir",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"d",
")",
"files",
"=",
"sorted",
"(",
"glob",
".",... | Lists files in a given directory.
Args:
d (str): Path to a directory.
extension (str): If supplied, only files that contain the
specificied extension will be returned. Default is ``False``,
which returns all files in ``d``.
Returns:
list: A sorted list of file paths. | [
"Lists",
"files",
"in",
"a",
"given",
"directory",
"."
] | 944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b | https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/utils/pipeline.py#L86-L113 | train | 42,576 |
AtteqCom/zsl | src/zsl/interface/cli.py | _get_version | def _get_version(ctx, _, value):
"""Click callback for option to show current ZSL version."""
if not value or ctx.resilient_parsing:
return
message = 'Zsl %(version)s\nPython %(python_version)s'
click.echo(message % {
'version': version,
'python_version': sys.version,
}, color=ctx.color)
ctx.exit() | python | def _get_version(ctx, _, value):
"""Click callback for option to show current ZSL version."""
if not value or ctx.resilient_parsing:
return
message = 'Zsl %(version)s\nPython %(python_version)s'
click.echo(message % {
'version': version,
'python_version': sys.version,
}, color=ctx.color)
ctx.exit() | [
"def",
"_get_version",
"(",
"ctx",
",",
"_",
",",
"value",
")",
":",
"if",
"not",
"value",
"or",
"ctx",
".",
"resilient_parsing",
":",
"return",
"message",
"=",
"'Zsl %(version)s\\nPython %(python_version)s'",
"click",
".",
"echo",
"(",
"message",
"%",
"{",
... | Click callback for option to show current ZSL version. | [
"Click",
"callback",
"for",
"option",
"to",
"show",
"current",
"ZSL",
"version",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/interface/cli.py#L22-L32 | train | 42,577 |
AtteqCom/zsl | src/zsl/resource/model_resource.py | dict_pick | def dict_pick(dictionary, allowed_keys):
"""
Return a dictionary only with keys found in `allowed_keys`
"""
return {key: value for key, value in viewitems(dictionary) if key in allowed_keys} | python | def dict_pick(dictionary, allowed_keys):
"""
Return a dictionary only with keys found in `allowed_keys`
"""
return {key: value for key, value in viewitems(dictionary) if key in allowed_keys} | [
"def",
"dict_pick",
"(",
"dictionary",
",",
"allowed_keys",
")",
":",
"return",
"{",
"key",
":",
"value",
"for",
"key",
",",
"value",
"in",
"viewitems",
"(",
"dictionary",
")",
"if",
"key",
"in",
"allowed_keys",
"}"
] | Return a dictionary only with keys found in `allowed_keys` | [
"Return",
"a",
"dictionary",
"only",
"with",
"keys",
"found",
"in",
"allowed_keys"
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/resource/model_resource.py#L39-L43 | train | 42,578 |
AtteqCom/zsl | src/zsl/resource/model_resource.py | ModelResource._create_one | def _create_one(self, ctx):
"""
Creates an instance to be saved when a model is created.
"""
assert isinstance(ctx, ResourceQueryContext)
fields = dict_pick(ctx.data, self._model_columns)
model = self.model_cls(**fields)
return model | python | def _create_one(self, ctx):
"""
Creates an instance to be saved when a model is created.
"""
assert isinstance(ctx, ResourceQueryContext)
fields = dict_pick(ctx.data, self._model_columns)
model = self.model_cls(**fields)
return model | [
"def",
"_create_one",
"(",
"self",
",",
"ctx",
")",
":",
"assert",
"isinstance",
"(",
"ctx",
",",
"ResourceQueryContext",
")",
"fields",
"=",
"dict_pick",
"(",
"ctx",
".",
"data",
",",
"self",
".",
"_model_columns",
")",
"model",
"=",
"self",
".",
"model... | Creates an instance to be saved when a model is created. | [
"Creates",
"an",
"instance",
"to",
"be",
"saved",
"when",
"a",
"model",
"is",
"created",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/resource/model_resource.py#L287-L295 | train | 42,579 |
AtteqCom/zsl | src/zsl/resource/model_resource.py | ModelResource._save_one | def _save_one(self, model, ctx):
"""
Saves the created instance.
"""
assert isinstance(ctx, ResourceQueryContext)
self._orm.add(model)
self._orm.flush() | python | def _save_one(self, model, ctx):
"""
Saves the created instance.
"""
assert isinstance(ctx, ResourceQueryContext)
self._orm.add(model)
self._orm.flush() | [
"def",
"_save_one",
"(",
"self",
",",
"model",
",",
"ctx",
")",
":",
"assert",
"isinstance",
"(",
"ctx",
",",
"ResourceQueryContext",
")",
"self",
".",
"_orm",
".",
"add",
"(",
"model",
")",
"self",
".",
"_orm",
".",
"flush",
"(",
")"
] | Saves the created instance. | [
"Saves",
"the",
"created",
"instance",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/resource/model_resource.py#L297-L304 | train | 42,580 |
AtteqCom/zsl | src/zsl/resource/model_resource.py | ModelResource._create_delete_one_query | def _create_delete_one_query(self, row_id, ctx):
"""
Delete row by id query creation.
:param int row_id: Identifier of the deleted row.
:param ResourceQueryContext ctx: The context of this delete query.
"""
assert isinstance(ctx, ResourceQueryContext)
return self._orm.query(self.model_cls).filter(self._model_pk == row_id) | python | def _create_delete_one_query(self, row_id, ctx):
"""
Delete row by id query creation.
:param int row_id: Identifier of the deleted row.
:param ResourceQueryContext ctx: The context of this delete query.
"""
assert isinstance(ctx, ResourceQueryContext)
return self._orm.query(self.model_cls).filter(self._model_pk == row_id) | [
"def",
"_create_delete_one_query",
"(",
"self",
",",
"row_id",
",",
"ctx",
")",
":",
"assert",
"isinstance",
"(",
"ctx",
",",
"ResourceQueryContext",
")",
"return",
"self",
".",
"_orm",
".",
"query",
"(",
"self",
".",
"model_cls",
")",
".",
"filter",
"(",
... | Delete row by id query creation.
:param int row_id: Identifier of the deleted row.
:param ResourceQueryContext ctx: The context of this delete query. | [
"Delete",
"row",
"by",
"id",
"query",
"creation",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/resource/model_resource.py#L434-L443 | train | 42,581 |
AtteqCom/zsl | src/zsl/resource/model_resource.py | ModelResource._delete_collection | def _delete_collection(self, ctx):
"""
Delete a collection from DB, optionally filtered by ``filter_by``
"""
assert isinstance(ctx, ResourceQueryContext)
filter_by = ctx.get_filter_by()
q = self._orm.query(self.model_cls)
if filter_by is not None:
q = self.to_filter(q, filter_by)
return q.delete() | python | def _delete_collection(self, ctx):
"""
Delete a collection from DB, optionally filtered by ``filter_by``
"""
assert isinstance(ctx, ResourceQueryContext)
filter_by = ctx.get_filter_by()
q = self._orm.query(self.model_cls)
if filter_by is not None:
q = self.to_filter(q, filter_by)
return q.delete() | [
"def",
"_delete_collection",
"(",
"self",
",",
"ctx",
")",
":",
"assert",
"isinstance",
"(",
"ctx",
",",
"ResourceQueryContext",
")",
"filter_by",
"=",
"ctx",
".",
"get_filter_by",
"(",
")",
"q",
"=",
"self",
".",
"_orm",
".",
"query",
"(",
"self",
".",
... | Delete a collection from DB, optionally filtered by ``filter_by`` | [
"Delete",
"a",
"collection",
"from",
"DB",
"optionally",
"filtered",
"by",
"filter_by"
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/resource/model_resource.py#L445-L457 | train | 42,582 |
AtteqCom/zsl | src/zsl/router/task.py | TaskRouter.route | def route(self, path):
# type: (str)->Tuple[Any, Callable]
"""
Returns the task handling the given request path.
"""
logging.getLogger(__name__).debug("Routing path '%s'.", path)
cls = None
for strategy in self._strategies:
if strategy.can_route(path):
cls = strategy.route(path)
break
if cls is None:
raise RoutingError(path)
return self._create_result(cls) | python | def route(self, path):
# type: (str)->Tuple[Any, Callable]
"""
Returns the task handling the given request path.
"""
logging.getLogger(__name__).debug("Routing path '%s'.", path)
cls = None
for strategy in self._strategies:
if strategy.can_route(path):
cls = strategy.route(path)
break
if cls is None:
raise RoutingError(path)
return self._create_result(cls) | [
"def",
"route",
"(",
"self",
",",
"path",
")",
":",
"# type: (str)->Tuple[Any, Callable]",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
".",
"debug",
"(",
"\"Routing path '%s'.\"",
",",
"path",
")",
"cls",
"=",
"None",
"for",
"strategy",
"in",
"self",
... | Returns the task handling the given request path. | [
"Returns",
"the",
"task",
"handling",
"the",
"given",
"request",
"path",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/router/task.py#L220-L236 | train | 42,583 |
briney/abutils | abutils/utils/convert.py | abi_to_fasta | def abi_to_fasta(input, output):
'''
Converts ABI or AB1 files to FASTA format.
Args:
input (str): Path to a file or directory containing abi/ab1 files or
zip archives of abi/ab1 files
output (str): Path to a directory for the output FASTA files
'''
direcs = [input, ]
# unzip any zip archives
zip_files = list_files(input, ['zip'])
if zip_files:
direcs.extend(_process_zip_files(zip_files))
# convert files
for d in direcs:
files = list_files(d, ['ab1', 'abi'])
seqs = [SeqIO.read(open(f, 'rb'), 'abi') for f in files]
# seqs = list(chain.from_iterable(seqs))
fastas = ['>{}\n{}'.format(s.id, str(s.seq)) for s in seqs]
ofile = os.path.basename(os.path.normpath(d)) + '.fasta'
opath = os.path.join(output, ofile)
open(opath, 'w').write('\n'.join(fastas)) | python | def abi_to_fasta(input, output):
'''
Converts ABI or AB1 files to FASTA format.
Args:
input (str): Path to a file or directory containing abi/ab1 files or
zip archives of abi/ab1 files
output (str): Path to a directory for the output FASTA files
'''
direcs = [input, ]
# unzip any zip archives
zip_files = list_files(input, ['zip'])
if zip_files:
direcs.extend(_process_zip_files(zip_files))
# convert files
for d in direcs:
files = list_files(d, ['ab1', 'abi'])
seqs = [SeqIO.read(open(f, 'rb'), 'abi') for f in files]
# seqs = list(chain.from_iterable(seqs))
fastas = ['>{}\n{}'.format(s.id, str(s.seq)) for s in seqs]
ofile = os.path.basename(os.path.normpath(d)) + '.fasta'
opath = os.path.join(output, ofile)
open(opath, 'w').write('\n'.join(fastas)) | [
"def",
"abi_to_fasta",
"(",
"input",
",",
"output",
")",
":",
"direcs",
"=",
"[",
"input",
",",
"]",
"# unzip any zip archives",
"zip_files",
"=",
"list_files",
"(",
"input",
",",
"[",
"'zip'",
"]",
")",
"if",
"zip_files",
":",
"direcs",
".",
"extend",
"... | Converts ABI or AB1 files to FASTA format.
Args:
input (str): Path to a file or directory containing abi/ab1 files or
zip archives of abi/ab1 files
output (str): Path to a directory for the output FASTA files | [
"Converts",
"ABI",
"or",
"AB1",
"files",
"to",
"FASTA",
"format",
"."
] | 944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b | https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/utils/convert.py#L37-L61 | train | 42,584 |
AtteqCom/zsl | src/zsl/utils/reflection_helper.py | extend | def extend(instance, new_class):
"""Adds new_class to the ancestors of instance.
:param instance: Instance that will have a new ancestor.
:param new_class: Ancestor.
"""
instance.__class__ = type(
'%s_extended_with_%s' % (instance.__class__.__name__, new_class.__name__),
(new_class, instance.__class__,),
{}
) | python | def extend(instance, new_class):
"""Adds new_class to the ancestors of instance.
:param instance: Instance that will have a new ancestor.
:param new_class: Ancestor.
"""
instance.__class__ = type(
'%s_extended_with_%s' % (instance.__class__.__name__, new_class.__name__),
(new_class, instance.__class__,),
{}
) | [
"def",
"extend",
"(",
"instance",
",",
"new_class",
")",
":",
"instance",
".",
"__class__",
"=",
"type",
"(",
"'%s_extended_with_%s'",
"%",
"(",
"instance",
".",
"__class__",
".",
"__name__",
",",
"new_class",
".",
"__name__",
")",
",",
"(",
"new_class",
"... | Adds new_class to the ancestors of instance.
:param instance: Instance that will have a new ancestor.
:param new_class: Ancestor. | [
"Adds",
"new_class",
"to",
"the",
"ancestors",
"of",
"instance",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/reflection_helper.py#L15-L25 | train | 42,585 |
AtteqCom/zsl | src/zsl/utils/deploy/js_model_generator.py | generate_js_models | def generate_js_models(module, models, collection_prefix, model_prefix,
model_fn, collection_fn, marker, integrate, js_file):
# type: (str, str, str, str, str, str, str, bool, str) -> Union[str, None]
"""Generate models for Backbone Javascript applications.
:param module: module from which models are imported
:param models: model name, can be a tuple WineCountry/WineCountries as singular/plural
:param model_prefix: namespace prefix for models (app.models.)
:param collection_prefix: namespace prefix for collection (App.collections.)
:param model_fn: name of model constructor (MyApp.bb.Model)
:param collection_fn: name of collection constructor (MyApp.bb.Collection)
:param marker: marker to indicate the auto generated code
:param integrate: integrate to file
:param js_file: file to integrate
:return: generated models or nothing if writing into a file
"""
options = {
'model_prefix': model_prefix,
'collection_prefix': collection_prefix,
'model_fn': model_fn,
'collection_fn': collection_fn
}
generator = ModelGenerator(module,
**{o: options[o] for o in options if options[o] is not None})
models = generator.generate_models(parse_model_arg(models))
if integrate:
sys.stderr.write("Integrate is really experimental")
if not marker:
marker = hashlib.md5("{0}{1}".format(module, models)).hexdigest()
start = "// * -- START AUTOGENERATED %s -- * //\n" % marker
end = "// * -- END AUTOGENERATED %s -- * //\n" % marker
return integrate_to_file("\n".join(models), js_file, start, end)
else:
return "\n".join(models) | python | def generate_js_models(module, models, collection_prefix, model_prefix,
model_fn, collection_fn, marker, integrate, js_file):
# type: (str, str, str, str, str, str, str, bool, str) -> Union[str, None]
"""Generate models for Backbone Javascript applications.
:param module: module from which models are imported
:param models: model name, can be a tuple WineCountry/WineCountries as singular/plural
:param model_prefix: namespace prefix for models (app.models.)
:param collection_prefix: namespace prefix for collection (App.collections.)
:param model_fn: name of model constructor (MyApp.bb.Model)
:param collection_fn: name of collection constructor (MyApp.bb.Collection)
:param marker: marker to indicate the auto generated code
:param integrate: integrate to file
:param js_file: file to integrate
:return: generated models or nothing if writing into a file
"""
options = {
'model_prefix': model_prefix,
'collection_prefix': collection_prefix,
'model_fn': model_fn,
'collection_fn': collection_fn
}
generator = ModelGenerator(module,
**{o: options[o] for o in options if options[o] is not None})
models = generator.generate_models(parse_model_arg(models))
if integrate:
sys.stderr.write("Integrate is really experimental")
if not marker:
marker = hashlib.md5("{0}{1}".format(module, models)).hexdigest()
start = "// * -- START AUTOGENERATED %s -- * //\n" % marker
end = "// * -- END AUTOGENERATED %s -- * //\n" % marker
return integrate_to_file("\n".join(models), js_file, start, end)
else:
return "\n".join(models) | [
"def",
"generate_js_models",
"(",
"module",
",",
"models",
",",
"collection_prefix",
",",
"model_prefix",
",",
"model_fn",
",",
"collection_fn",
",",
"marker",
",",
"integrate",
",",
"js_file",
")",
":",
"# type: (str, str, str, str, str, str, str, bool, str) -> Union[str... | Generate models for Backbone Javascript applications.
:param module: module from which models are imported
:param models: model name, can be a tuple WineCountry/WineCountries as singular/plural
:param model_prefix: namespace prefix for models (app.models.)
:param collection_prefix: namespace prefix for collection (App.collections.)
:param model_fn: name of model constructor (MyApp.bb.Model)
:param collection_fn: name of collection constructor (MyApp.bb.Collection)
:param marker: marker to indicate the auto generated code
:param integrate: integrate to file
:param js_file: file to integrate
:return: generated models or nothing if writing into a file | [
"Generate",
"models",
"for",
"Backbone",
"Javascript",
"applications",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/deploy/js_model_generator.py#L166-L207 | train | 42,586 |
AtteqCom/zsl | src/zsl/utils/deploy/js_model_generator.py | ModelGenerator._map_table_name | def _map_table_name(self, model_names):
"""
Pre foregin_keys potrbejeme pre z nazvu tabulky zistit class,
tak si to namapujme
"""
for model in model_names:
if isinstance(model, tuple):
model = model[0]
try:
model_cls = getattr(self.models, model)
self.table_to_class[class_mapper(model_cls).tables[0].name] = model
except AttributeError:
pass | python | def _map_table_name(self, model_names):
"""
Pre foregin_keys potrbejeme pre z nazvu tabulky zistit class,
tak si to namapujme
"""
for model in model_names:
if isinstance(model, tuple):
model = model[0]
try:
model_cls = getattr(self.models, model)
self.table_to_class[class_mapper(model_cls).tables[0].name] = model
except AttributeError:
pass | [
"def",
"_map_table_name",
"(",
"self",
",",
"model_names",
")",
":",
"for",
"model",
"in",
"model_names",
":",
"if",
"isinstance",
"(",
"model",
",",
"tuple",
")",
":",
"model",
"=",
"model",
"[",
"0",
"]",
"try",
":",
"model_cls",
"=",
"getattr",
"(",... | Pre foregin_keys potrbejeme pre z nazvu tabulky zistit class,
tak si to namapujme | [
"Pre",
"foregin_keys",
"potrbejeme",
"pre",
"z",
"nazvu",
"tabulky",
"zistit",
"class",
"tak",
"si",
"to",
"namapujme"
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/deploy/js_model_generator.py#L56-L70 | train | 42,587 |
AtteqCom/zsl | src/zsl/utils/nginx_push_helper.py | NginxPusher.push_msg | def push_msg(self, channel_id, msg):
"""Push ``msg`` for given ``channel_id``. If ``msg`` is not string, it
will be urlencoded
"""
if type(msg) is not str:
msg = urlencode(msg)
return self.push(channel_id, msg) | python | def push_msg(self, channel_id, msg):
"""Push ``msg`` for given ``channel_id``. If ``msg`` is not string, it
will be urlencoded
"""
if type(msg) is not str:
msg = urlencode(msg)
return self.push(channel_id, msg) | [
"def",
"push_msg",
"(",
"self",
",",
"channel_id",
",",
"msg",
")",
":",
"if",
"type",
"(",
"msg",
")",
"is",
"not",
"str",
":",
"msg",
"=",
"urlencode",
"(",
"msg",
")",
"return",
"self",
".",
"push",
"(",
"channel_id",
",",
"msg",
")"
] | Push ``msg`` for given ``channel_id``. If ``msg`` is not string, it
will be urlencoded | [
"Push",
"msg",
"for",
"given",
"channel_id",
".",
"If",
"msg",
"is",
"not",
"string",
"it",
"will",
"be",
"urlencoded"
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/nginx_push_helper.py#L26-L34 | train | 42,588 |
AtteqCom/zsl | src/zsl/utils/nginx_push_helper.py | NginxPusher.push_object | def push_object(self, channel_id, obj):
"""Push ``obj`` for ``channel_id``. ``obj`` will be encoded as JSON in
the request.
"""
return self.push(channel_id, json.dumps(obj).replace('"', '\\"')) | python | def push_object(self, channel_id, obj):
"""Push ``obj`` for ``channel_id``. ``obj`` will be encoded as JSON in
the request.
"""
return self.push(channel_id, json.dumps(obj).replace('"', '\\"')) | [
"def",
"push_object",
"(",
"self",
",",
"channel_id",
",",
"obj",
")",
":",
"return",
"self",
".",
"push",
"(",
"channel_id",
",",
"json",
".",
"dumps",
"(",
"obj",
")",
".",
"replace",
"(",
"'\"'",
",",
"'\\\\\"'",
")",
")"
] | Push ``obj`` for ``channel_id``. ``obj`` will be encoded as JSON in
the request. | [
"Push",
"obj",
"for",
"channel_id",
".",
"obj",
"will",
"be",
"encoded",
"as",
"JSON",
"in",
"the",
"request",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/nginx_push_helper.py#L36-L41 | train | 42,589 |
AtteqCom/zsl | src/zsl/utils/nginx_push_helper.py | NginxPusher.push | def push(self, channel_id, data):
"""Push message with POST ``data`` for ``channel_id``
"""
channel_path = self.channel_path(channel_id)
response = requests.post(channel_path, data)
return response.json() | python | def push(self, channel_id, data):
"""Push message with POST ``data`` for ``channel_id``
"""
channel_path = self.channel_path(channel_id)
response = requests.post(channel_path, data)
return response.json() | [
"def",
"push",
"(",
"self",
",",
"channel_id",
",",
"data",
")",
":",
"channel_path",
"=",
"self",
".",
"channel_path",
"(",
"channel_id",
")",
"response",
"=",
"requests",
".",
"post",
"(",
"channel_path",
",",
"data",
")",
"return",
"response",
".",
"j... | Push message with POST ``data`` for ``channel_id`` | [
"Push",
"message",
"with",
"POST",
"data",
"for",
"channel_id"
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/nginx_push_helper.py#L43-L50 | train | 42,590 |
AtteqCom/zsl | src/zsl/application/modules/web/web_context_module.py | WebInitializer.initialize | def initialize():
"""
Import in this form is necessary so that we avoid the unwanted behavior and immediate initialization of the
application objects. This makes the initialization procedure run in the time when it is necessary and has every
required resources.
"""
from zsl.interface.web.performers.default import create_not_found_mapping
from zsl.interface.web.performers.resource import create_resource_mapping
create_not_found_mapping()
create_resource_mapping() | python | def initialize():
"""
Import in this form is necessary so that we avoid the unwanted behavior and immediate initialization of the
application objects. This makes the initialization procedure run in the time when it is necessary and has every
required resources.
"""
from zsl.interface.web.performers.default import create_not_found_mapping
from zsl.interface.web.performers.resource import create_resource_mapping
create_not_found_mapping()
create_resource_mapping() | [
"def",
"initialize",
"(",
")",
":",
"from",
"zsl",
".",
"interface",
".",
"web",
".",
"performers",
".",
"default",
"import",
"create_not_found_mapping",
"from",
"zsl",
".",
"interface",
".",
"web",
".",
"performers",
".",
"resource",
"import",
"create_resourc... | Import in this form is necessary so that we avoid the unwanted behavior and immediate initialization of the
application objects. This makes the initialization procedure run in the time when it is necessary and has every
required resources. | [
"Import",
"in",
"this",
"form",
"is",
"necessary",
"so",
"that",
"we",
"avoid",
"the",
"unwanted",
"behavior",
"and",
"immediate",
"initialization",
"of",
"the",
"application",
"objects",
".",
"This",
"makes",
"the",
"initialization",
"procedure",
"run",
"in",
... | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/application/modules/web/web_context_module.py#L23-L33 | train | 42,591 |
AtteqCom/zsl | src/zsl/application/modules/web/web_context_module.py | WebHandler.run_web | def run_web(self, flask, host='127.0.0.1', port=5000, **options):
# type: (Zsl, str, int, **Any)->None
"""Alias for Flask.run"""
return flask.run(
host=flask.config.get('FLASK_HOST', host),
port=flask.config.get('FLASK_PORT', port),
debug=flask.config.get('DEBUG', False),
**options
) | python | def run_web(self, flask, host='127.0.0.1', port=5000, **options):
# type: (Zsl, str, int, **Any)->None
"""Alias for Flask.run"""
return flask.run(
host=flask.config.get('FLASK_HOST', host),
port=flask.config.get('FLASK_PORT', port),
debug=flask.config.get('DEBUG', False),
**options
) | [
"def",
"run_web",
"(",
"self",
",",
"flask",
",",
"host",
"=",
"'127.0.0.1'",
",",
"port",
"=",
"5000",
",",
"*",
"*",
"options",
")",
":",
"# type: (Zsl, str, int, **Any)->None",
"return",
"flask",
".",
"run",
"(",
"host",
"=",
"flask",
".",
"config",
"... | Alias for Flask.run | [
"Alias",
"for",
"Flask",
".",
"run"
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/application/modules/web/web_context_module.py#L66-L74 | train | 42,592 |
AtteqCom/zsl | src/zsl/utils/command_dispatcher.py | CommandDispatcher.bound | def bound(self, instance):
"""
Return a new dispatcher, which will switch all command functions
with bounded methods of given instance matched by name. It will
match only regular methods.
:param instance: object instance
:type instance: object
:return: new Dispatcher
:rtype: CommandDispatcher
"""
bounded_dispatcher = CommandDispatcher()
bounded_dispatcher.commands = self.commands.copy()
for name in self.commands:
method = getattr(instance, name, None)
if method and inspect.ismethod(method) and method.__self__ == instance:
bounded_dispatcher.commands[name] = method
return bounded_dispatcher | python | def bound(self, instance):
"""
Return a new dispatcher, which will switch all command functions
with bounded methods of given instance matched by name. It will
match only regular methods.
:param instance: object instance
:type instance: object
:return: new Dispatcher
:rtype: CommandDispatcher
"""
bounded_dispatcher = CommandDispatcher()
bounded_dispatcher.commands = self.commands.copy()
for name in self.commands:
method = getattr(instance, name, None)
if method and inspect.ismethod(method) and method.__self__ == instance:
bounded_dispatcher.commands[name] = method
return bounded_dispatcher | [
"def",
"bound",
"(",
"self",
",",
"instance",
")",
":",
"bounded_dispatcher",
"=",
"CommandDispatcher",
"(",
")",
"bounded_dispatcher",
".",
"commands",
"=",
"self",
".",
"commands",
".",
"copy",
"(",
")",
"for",
"name",
"in",
"self",
".",
"commands",
":",... | Return a new dispatcher, which will switch all command functions
with bounded methods of given instance matched by name. It will
match only regular methods.
:param instance: object instance
:type instance: object
:return: new Dispatcher
:rtype: CommandDispatcher | [
"Return",
"a",
"new",
"dispatcher",
"which",
"will",
"switch",
"all",
"command",
"functions",
"with",
"bounded",
"methods",
"of",
"given",
"instance",
"matched",
"by",
"name",
".",
"It",
"will",
"match",
"only",
"regular",
"methods",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/command_dispatcher.py#L62-L83 | train | 42,593 |
briney/abutils | abutils/utils/s3.py | compress_and_upload | def compress_and_upload(data, compressed_file, s3_path, multipart_chunk_size_mb=500,
method='gz', delete=False, access_key=None, secret_key=None):
'''
Compresses data and uploads to S3.
S3 upload uses ``s3cmd``, so you must either:
1) Manually configure ``s3cmd`` prior to use (typically using ``s3cmd --configure``).
2) Configure ``s3cmd`` using ``s3.configure()``.
3) Pass your access key and secret key to ``compress_and_upload``, which will automatically configure s3cmd.
.. note:
``s3cmd`` configuration only needs to be done once per computer,
which means that relaunching a cloud instance or Docker image will
require re-configuration of ``s3cmd``.
Args:
data: Can be one of three things:
1) Path to a single file
2) Path to a directory
3) A list of one or more paths to files or directories
compressed_file (str): Path to the compressed file. Required.
s3_path (str): The S3 path, with the filename omitted. The S3 filename
will be the basename of the ``compressed_file``. For example::
compress_and_upload(data='/path/to/data',
compressed_file='/path/to/compressed.tar.gz',
s3_path='s3://my_bucket/path/to/')
will result in an uploaded S3 path of ``s3://my_bucket/path/to/compressed.tar.gz``
method (str): Compression method. Options are ``'gz'`` (gzip) or ``'bz2'`` (bzip2).
Default is ``'gz'``.
delete (bool): If ``True``, the ``compressed_file`` will be deleted after upload
to S3. Default is ``False``.
access_key (str): AWS access key.
secret_key (str): AWS secret key.
'''
logger = log.get_logger('s3')
if all([access_key, secret_key]):
configure(access_key=access_key, secret_key=secret_key, logger=logger)
compress(data, compressed_file, fmt=method, logger=logger)
put(compressed_file, s3_path, multipart_chunk_size_mb=multipart_chunk_size_mb, logger=logger)
if delete:
os.unlink(compressed_file) | python | def compress_and_upload(data, compressed_file, s3_path, multipart_chunk_size_mb=500,
method='gz', delete=False, access_key=None, secret_key=None):
'''
Compresses data and uploads to S3.
S3 upload uses ``s3cmd``, so you must either:
1) Manually configure ``s3cmd`` prior to use (typically using ``s3cmd --configure``).
2) Configure ``s3cmd`` using ``s3.configure()``.
3) Pass your access key and secret key to ``compress_and_upload``, which will automatically configure s3cmd.
.. note:
``s3cmd`` configuration only needs to be done once per computer,
which means that relaunching a cloud instance or Docker image will
require re-configuration of ``s3cmd``.
Args:
data: Can be one of three things:
1) Path to a single file
2) Path to a directory
3) A list of one or more paths to files or directories
compressed_file (str): Path to the compressed file. Required.
s3_path (str): The S3 path, with the filename omitted. The S3 filename
will be the basename of the ``compressed_file``. For example::
compress_and_upload(data='/path/to/data',
compressed_file='/path/to/compressed.tar.gz',
s3_path='s3://my_bucket/path/to/')
will result in an uploaded S3 path of ``s3://my_bucket/path/to/compressed.tar.gz``
method (str): Compression method. Options are ``'gz'`` (gzip) or ``'bz2'`` (bzip2).
Default is ``'gz'``.
delete (bool): If ``True``, the ``compressed_file`` will be deleted after upload
to S3. Default is ``False``.
access_key (str): AWS access key.
secret_key (str): AWS secret key.
'''
logger = log.get_logger('s3')
if all([access_key, secret_key]):
configure(access_key=access_key, secret_key=secret_key, logger=logger)
compress(data, compressed_file, fmt=method, logger=logger)
put(compressed_file, s3_path, multipart_chunk_size_mb=multipart_chunk_size_mb, logger=logger)
if delete:
os.unlink(compressed_file) | [
"def",
"compress_and_upload",
"(",
"data",
",",
"compressed_file",
",",
"s3_path",
",",
"multipart_chunk_size_mb",
"=",
"500",
",",
"method",
"=",
"'gz'",
",",
"delete",
"=",
"False",
",",
"access_key",
"=",
"None",
",",
"secret_key",
"=",
"None",
")",
":",
... | Compresses data and uploads to S3.
S3 upload uses ``s3cmd``, so you must either:
1) Manually configure ``s3cmd`` prior to use (typically using ``s3cmd --configure``).
2) Configure ``s3cmd`` using ``s3.configure()``.
3) Pass your access key and secret key to ``compress_and_upload``, which will automatically configure s3cmd.
.. note:
``s3cmd`` configuration only needs to be done once per computer,
which means that relaunching a cloud instance or Docker image will
require re-configuration of ``s3cmd``.
Args:
data: Can be one of three things:
1) Path to a single file
2) Path to a directory
3) A list of one or more paths to files or directories
compressed_file (str): Path to the compressed file. Required.
s3_path (str): The S3 path, with the filename omitted. The S3 filename
will be the basename of the ``compressed_file``. For example::
compress_and_upload(data='/path/to/data',
compressed_file='/path/to/compressed.tar.gz',
s3_path='s3://my_bucket/path/to/')
will result in an uploaded S3 path of ``s3://my_bucket/path/to/compressed.tar.gz``
method (str): Compression method. Options are ``'gz'`` (gzip) or ``'bz2'`` (bzip2).
Default is ``'gz'``.
delete (bool): If ``True``, the ``compressed_file`` will be deleted after upload
to S3. Default is ``False``.
access_key (str): AWS access key.
secret_key (str): AWS secret key. | [
"Compresses",
"data",
"and",
"uploads",
"to",
"S3",
"."
] | 944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b | https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/utils/s3.py#L37-L93 | train | 42,594 |
briney/abutils | abutils/utils/s3.py | put | def put(f, s3_path, multipart_chunk_size_mb=500, logger=None):
'''
Uploads a single file to S3, using s3cmd.
Args:
f (str): Path to a single file.
s3_path (str): The S3 path, with the filename omitted. The S3 filename
will be the basename of the ``f``. For example::
put(f='/path/to/myfile.tar.gz', s3_path='s3://my_bucket/path/to/')
will result in an uploaded S3 path of ``s3://my_bucket/path/to/myfile.tar.gz``
'''
if not logger:
logger = log.get_logger('s3')
fname = os.path.basename(f)
target = os.path.join(s3_path, fname)
s3cmd_cline = 's3cmd put {} {} --multipart-chunk-size-mb {}'.format(f,
target,
multipart_chunk_size_mb)
print_put_info(fname, target, logger)
s3cmd = sp.Popen(s3cmd_cline,
stdout=sp.PIPE,
stderr=sp.PIPE,
shell=True)
stdout, stderr = s3cmd.communicate() | python | def put(f, s3_path, multipart_chunk_size_mb=500, logger=None):
'''
Uploads a single file to S3, using s3cmd.
Args:
f (str): Path to a single file.
s3_path (str): The S3 path, with the filename omitted. The S3 filename
will be the basename of the ``f``. For example::
put(f='/path/to/myfile.tar.gz', s3_path='s3://my_bucket/path/to/')
will result in an uploaded S3 path of ``s3://my_bucket/path/to/myfile.tar.gz``
'''
if not logger:
logger = log.get_logger('s3')
fname = os.path.basename(f)
target = os.path.join(s3_path, fname)
s3cmd_cline = 's3cmd put {} {} --multipart-chunk-size-mb {}'.format(f,
target,
multipart_chunk_size_mb)
print_put_info(fname, target, logger)
s3cmd = sp.Popen(s3cmd_cline,
stdout=sp.PIPE,
stderr=sp.PIPE,
shell=True)
stdout, stderr = s3cmd.communicate() | [
"def",
"put",
"(",
"f",
",",
"s3_path",
",",
"multipart_chunk_size_mb",
"=",
"500",
",",
"logger",
"=",
"None",
")",
":",
"if",
"not",
"logger",
":",
"logger",
"=",
"log",
".",
"get_logger",
"(",
"'s3'",
")",
"fname",
"=",
"os",
".",
"path",
".",
"... | Uploads a single file to S3, using s3cmd.
Args:
f (str): Path to a single file.
s3_path (str): The S3 path, with the filename omitted. The S3 filename
will be the basename of the ``f``. For example::
put(f='/path/to/myfile.tar.gz', s3_path='s3://my_bucket/path/to/')
will result in an uploaded S3 path of ``s3://my_bucket/path/to/myfile.tar.gz`` | [
"Uploads",
"a",
"single",
"file",
"to",
"S3",
"using",
"s3cmd",
"."
] | 944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b | https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/utils/s3.py#L96-L123 | train | 42,595 |
briney/abutils | abutils/utils/s3.py | configure | def configure(access_key=None, secret_key=None, logger=None):
'''
Configures s3cmd prior to first use.
If no arguments are provided, you will be prompted to enter
the access key and secret key interactively.
Args:
access_key (str): AWS access key
secret_key (str): AWS secret key
'''
if not logger:
logger = log.get_logger('s3')
if not all([access_key, secret_key]):
logger.info('')
access_key = input('AWS Access Key: ')
secret_key = input('AWS Secret Key: ')
_write_config(access_key, secret_key)
logger.info('')
logger.info('Completed writing S3 config file.')
logger.info('') | python | def configure(access_key=None, secret_key=None, logger=None):
'''
Configures s3cmd prior to first use.
If no arguments are provided, you will be prompted to enter
the access key and secret key interactively.
Args:
access_key (str): AWS access key
secret_key (str): AWS secret key
'''
if not logger:
logger = log.get_logger('s3')
if not all([access_key, secret_key]):
logger.info('')
access_key = input('AWS Access Key: ')
secret_key = input('AWS Secret Key: ')
_write_config(access_key, secret_key)
logger.info('')
logger.info('Completed writing S3 config file.')
logger.info('') | [
"def",
"configure",
"(",
"access_key",
"=",
"None",
",",
"secret_key",
"=",
"None",
",",
"logger",
"=",
"None",
")",
":",
"if",
"not",
"logger",
":",
"logger",
"=",
"log",
".",
"get_logger",
"(",
"'s3'",
")",
"if",
"not",
"all",
"(",
"[",
"access_key... | Configures s3cmd prior to first use.
If no arguments are provided, you will be prompted to enter
the access key and secret key interactively.
Args:
access_key (str): AWS access key
secret_key (str): AWS secret key | [
"Configures",
"s3cmd",
"prior",
"to",
"first",
"use",
"."
] | 944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b | https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/utils/s3.py#L201-L223 | train | 42,596 |
AtteqCom/zsl | src/zsl/utils/params_helper.py | required_params | def required_params(data, *r_params):
"""Check if given parameters are in the given dict, if not raise an
exception.
:param data: data to check
:type data: dict
:param r_params: required parameters
:raises RequestException: if params not in data
"""
if not reduce(lambda still_valid, param: still_valid and param in data,
r_params, True):
raise RequestException(msg_err_missing_params(*r_params)) | python | def required_params(data, *r_params):
"""Check if given parameters are in the given dict, if not raise an
exception.
:param data: data to check
:type data: dict
:param r_params: required parameters
:raises RequestException: if params not in data
"""
if not reduce(lambda still_valid, param: still_valid and param in data,
r_params, True):
raise RequestException(msg_err_missing_params(*r_params)) | [
"def",
"required_params",
"(",
"data",
",",
"*",
"r_params",
")",
":",
"if",
"not",
"reduce",
"(",
"lambda",
"still_valid",
",",
"param",
":",
"still_valid",
"and",
"param",
"in",
"data",
",",
"r_params",
",",
"True",
")",
":",
"raise",
"RequestException",... | Check if given parameters are in the given dict, if not raise an
exception.
:param data: data to check
:type data: dict
:param r_params: required parameters
:raises RequestException: if params not in data | [
"Check",
"if",
"given",
"parameters",
"are",
"in",
"the",
"given",
"dict",
"if",
"not",
"raise",
"an",
"exception",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/params_helper.py#L22-L34 | train | 42,597 |
AtteqCom/zsl | src/zsl/utils/params_helper.py | safe_args | def safe_args(fn, args):
"""Check if ``args`` as a dictionary has the required parameters of ``fn``
function and filter any waste parameters so ``fn`` can be safely called
with them.
:param fn: function object
:type fn: Callable
:param args: dictionary of parameters
:type args: dict
:return: dictionary to be used as named params for the ``fn``
:rtype: dict
"""
fn_args = inspect.getargspec(fn)
if fn_args.defaults:
required_params(args, fn_args.args[:-len(fn_args.defaults)])
else:
required_params(args, fn_args)
if not fn_args.keywords:
return {key: value for key, value in viewitems(args) if key in fn_args.args}
else:
return args | python | def safe_args(fn, args):
"""Check if ``args`` as a dictionary has the required parameters of ``fn``
function and filter any waste parameters so ``fn`` can be safely called
with them.
:param fn: function object
:type fn: Callable
:param args: dictionary of parameters
:type args: dict
:return: dictionary to be used as named params for the ``fn``
:rtype: dict
"""
fn_args = inspect.getargspec(fn)
if fn_args.defaults:
required_params(args, fn_args.args[:-len(fn_args.defaults)])
else:
required_params(args, fn_args)
if not fn_args.keywords:
return {key: value for key, value in viewitems(args) if key in fn_args.args}
else:
return args | [
"def",
"safe_args",
"(",
"fn",
",",
"args",
")",
":",
"fn_args",
"=",
"inspect",
".",
"getargspec",
"(",
"fn",
")",
"if",
"fn_args",
".",
"defaults",
":",
"required_params",
"(",
"args",
",",
"fn_args",
".",
"args",
"[",
":",
"-",
"len",
"(",
"fn_arg... | Check if ``args`` as a dictionary has the required parameters of ``fn``
function and filter any waste parameters so ``fn`` can be safely called
with them.
:param fn: function object
:type fn: Callable
:param args: dictionary of parameters
:type args: dict
:return: dictionary to be used as named params for the ``fn``
:rtype: dict | [
"Check",
"if",
"args",
"as",
"a",
"dictionary",
"has",
"the",
"required",
"parameters",
"of",
"fn",
"function",
"and",
"filter",
"any",
"waste",
"parameters",
"so",
"fn",
"can",
"be",
"safely",
"called",
"with",
"them",
"."
] | ab51a96da1780ff642912396d4b85bdcb72560c1 | https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/params_helper.py#L41-L63 | train | 42,598 |
briney/abutils | abutils/utils/mongodb.py | get_db | def get_db(db, ip='localhost', port=27017, user=None, password=None):
'''
Returns a pymongo Database object.
.. note:
Both ``user`` and ``password`` are required when connecting to a MongoDB
database that has authentication enabled.
Arguments:
db (str): Name of the MongoDB database. Required.
ip (str): IP address of the MongoDB server. Default is ``localhost``.
port (int): Port of the MongoDB server. Default is ``27017``.
user (str): Username, if authentication is enabled on the MongoDB database.
Default is ``None``, which results in requesting the connection
without authentication.
password (str): Password, if authentication is enabled on the MongoDB database.
Default is ``None``, which results in requesting the connection
without authentication.
'''
if platform.system().lower() == 'darwin':
connect = False
else:
connect = True
if user and password:
import urllib
pwd = urllib.quote_plus(password)
uri = 'mongodb://{}:{}@{}:{}'.format(user, pwd, ip, port)
conn = MongoClient(uri, connect=connect)
else:
conn = MongoClient(ip, port, connect=connect)
return conn[db] | python | def get_db(db, ip='localhost', port=27017, user=None, password=None):
'''
Returns a pymongo Database object.
.. note:
Both ``user`` and ``password`` are required when connecting to a MongoDB
database that has authentication enabled.
Arguments:
db (str): Name of the MongoDB database. Required.
ip (str): IP address of the MongoDB server. Default is ``localhost``.
port (int): Port of the MongoDB server. Default is ``27017``.
user (str): Username, if authentication is enabled on the MongoDB database.
Default is ``None``, which results in requesting the connection
without authentication.
password (str): Password, if authentication is enabled on the MongoDB database.
Default is ``None``, which results in requesting the connection
without authentication.
'''
if platform.system().lower() == 'darwin':
connect = False
else:
connect = True
if user and password:
import urllib
pwd = urllib.quote_plus(password)
uri = 'mongodb://{}:{}@{}:{}'.format(user, pwd, ip, port)
conn = MongoClient(uri, connect=connect)
else:
conn = MongoClient(ip, port, connect=connect)
return conn[db] | [
"def",
"get_db",
"(",
"db",
",",
"ip",
"=",
"'localhost'",
",",
"port",
"=",
"27017",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"if",
"platform",
".",
"system",
"(",
")",
".",
"lower",
"(",
")",
"==",
"'darwin'",
":",
"con... | Returns a pymongo Database object.
.. note:
Both ``user`` and ``password`` are required when connecting to a MongoDB
database that has authentication enabled.
Arguments:
db (str): Name of the MongoDB database. Required.
ip (str): IP address of the MongoDB server. Default is ``localhost``.
port (int): Port of the MongoDB server. Default is ``27017``.
user (str): Username, if authentication is enabled on the MongoDB database.
Default is ``None``, which results in requesting the connection
without authentication.
password (str): Password, if authentication is enabled on the MongoDB database.
Default is ``None``, which results in requesting the connection
without authentication. | [
"Returns",
"a",
"pymongo",
"Database",
"object",
"."
] | 944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b | https://github.com/briney/abutils/blob/944755fc7d28bfc7d4f1ffad94ca0bf9d74ec54b/abutils/utils/mongodb.py#L79-L115 | train | 42,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.