repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
apragacz/django-rest-registration | rest_registration/utils/users.py | get_object_or_404 | def get_object_or_404(queryset, *filter_args, **filter_kwargs):
"""
Same as Django's standard shortcut, but make sure to also raise 404
if the filter_kwargs don't match the required types.
This function was copied from rest_framework.generics because of issue #36.
"""
try:
return _get_o... | python | def get_object_or_404(queryset, *filter_args, **filter_kwargs):
"""
Same as Django's standard shortcut, but make sure to also raise 404
if the filter_kwargs don't match the required types.
This function was copied from rest_framework.generics because of issue #36.
"""
try:
return _get_o... | [
"def",
"get_object_or_404",
"(",
"queryset",
",",
"*",
"filter_args",
",",
"**",
"filter_kwargs",
")",
":",
"try",
":",
"return",
"_get_object_or_404",
"(",
"queryset",
",",
"*",
"filter_args",
",",
"**",
"filter_kwargs",
")",
"except",
"(",
"TypeError",
",",
... | Same as Django's standard shortcut, but make sure to also raise 404
if the filter_kwargs don't match the required types.
This function was copied from rest_framework.generics because of issue #36. | [
"Same",
"as",
"Django",
"s",
"standard",
"shortcut",
"but",
"make",
"sure",
"to",
"also",
"raise",
"404",
"if",
"the",
"filter_kwargs",
"don",
"t",
"match",
"the",
"required",
"types",
"."
] | 7373571264dd567c2a73a97ff4c45b64f113605b | https://github.com/apragacz/django-rest-registration/blob/7373571264dd567c2a73a97ff4c45b64f113605b/rest_registration/utils/users.py#L13-L23 | train |
apragacz/django-rest-registration | rest_registration/api/views/profile.py | profile | def profile(request):
'''
Get or set user profile.
'''
serializer_class = registration_settings.PROFILE_SERIALIZER_CLASS
if request.method in ['POST', 'PUT', 'PATCH']:
partial = request.method == 'PATCH'
serializer = serializer_class(
instance=request.user,
da... | python | def profile(request):
'''
Get or set user profile.
'''
serializer_class = registration_settings.PROFILE_SERIALIZER_CLASS
if request.method in ['POST', 'PUT', 'PATCH']:
partial = request.method == 'PATCH'
serializer = serializer_class(
instance=request.user,
da... | [
"def",
"profile",
"(",
"request",
")",
":",
"serializer_class",
"=",
"registration_settings",
".",
"PROFILE_SERIALIZER_CLASS",
"if",
"request",
".",
"method",
"in",
"[",
"'POST'",
",",
"'PUT'",
",",
"'PATCH'",
"]",
":",
"partial",
"=",
"request",
".",
"method"... | Get or set user profile. | [
"Get",
"or",
"set",
"user",
"profile",
"."
] | 7373571264dd567c2a73a97ff4c45b64f113605b | https://github.com/apragacz/django-rest-registration/blob/7373571264dd567c2a73a97ff4c45b64f113605b/rest_registration/api/views/profile.py#L13-L30 | train |
apragacz/django-rest-registration | rest_registration/api/views/register.py | register | def register(request):
'''
Register new user.
'''
serializer_class = registration_settings.REGISTER_SERIALIZER_CLASS
serializer = serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
kwargs = {}
if registration_settings.REGISTER_VERIFICATION_ENABLED:
ve... | python | def register(request):
'''
Register new user.
'''
serializer_class = registration_settings.REGISTER_SERIALIZER_CLASS
serializer = serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
kwargs = {}
if registration_settings.REGISTER_VERIFICATION_ENABLED:
ve... | [
"def",
"register",
"(",
"request",
")",
":",
"serializer_class",
"=",
"registration_settings",
".",
"REGISTER_SERIALIZER_CLASS",
"serializer",
"=",
"serializer_class",
"(",
"data",
"=",
"request",
".",
"data",
")",
"serializer",
".",
"is_valid",
"(",
"raise_exceptio... | Register new user. | [
"Register",
"new",
"user",
"."
] | 7373571264dd567c2a73a97ff4c45b64f113605b | https://github.com/apragacz/django-rest-registration/blob/7373571264dd567c2a73a97ff4c45b64f113605b/rest_registration/api/views/register.py#L54-L86 | train |
apragacz/django-rest-registration | rest_registration/api/views/register.py | verify_registration | def verify_registration(request):
"""
Verify registration via signature.
"""
user = process_verify_registration_data(request.data)
extra_data = None
if registration_settings.REGISTER_VERIFICATION_AUTO_LOGIN:
extra_data = perform_login(request, user)
return get_ok_response('User verif... | python | def verify_registration(request):
"""
Verify registration via signature.
"""
user = process_verify_registration_data(request.data)
extra_data = None
if registration_settings.REGISTER_VERIFICATION_AUTO_LOGIN:
extra_data = perform_login(request, user)
return get_ok_response('User verif... | [
"def",
"verify_registration",
"(",
"request",
")",
":",
"user",
"=",
"process_verify_registration_data",
"(",
"request",
".",
"data",
")",
"extra_data",
"=",
"None",
"if",
"registration_settings",
".",
"REGISTER_VERIFICATION_AUTO_LOGIN",
":",
"extra_data",
"=",
"perfo... | Verify registration via signature. | [
"Verify",
"registration",
"via",
"signature",
"."
] | 7373571264dd567c2a73a97ff4c45b64f113605b | https://github.com/apragacz/django-rest-registration/blob/7373571264dd567c2a73a97ff4c45b64f113605b/rest_registration/api/views/register.py#L98-L106 | train |
apragacz/django-rest-registration | setup.py | get_requirements | def get_requirements(requirements_filepath):
'''
Return list of this package requirements via local filepath.
'''
requirements = []
with open(os.path.join(ROOT_DIR, requirements_filepath), 'rt') as f:
for line in f:
if line.startswith('#'):
continue
li... | python | def get_requirements(requirements_filepath):
'''
Return list of this package requirements via local filepath.
'''
requirements = []
with open(os.path.join(ROOT_DIR, requirements_filepath), 'rt') as f:
for line in f:
if line.startswith('#'):
continue
li... | [
"def",
"get_requirements",
"(",
"requirements_filepath",
")",
":",
"requirements",
"=",
"[",
"]",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"ROOT_DIR",
",",
"requirements_filepath",
")",
",",
"'rt'",
")",
"as",
"f",
":",
"for",
"line",
"i... | Return list of this package requirements via local filepath. | [
"Return",
"list",
"of",
"this",
"package",
"requirements",
"via",
"local",
"filepath",
"."
] | 7373571264dd567c2a73a97ff4c45b64f113605b | https://github.com/apragacz/django-rest-registration/blob/7373571264dd567c2a73a97ff4c45b64f113605b/setup.py#L15-L28 | train |
apragacz/django-rest-registration | rest_registration/api/views/reset_password.py | send_reset_password_link | def send_reset_password_link(request):
'''
Send email with reset password link.
'''
if not registration_settings.RESET_PASSWORD_VERIFICATION_ENABLED:
raise Http404()
serializer = SendResetPasswordLinkSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
login = seri... | python | def send_reset_password_link(request):
'''
Send email with reset password link.
'''
if not registration_settings.RESET_PASSWORD_VERIFICATION_ENABLED:
raise Http404()
serializer = SendResetPasswordLinkSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
login = seri... | [
"def",
"send_reset_password_link",
"(",
"request",
")",
":",
"if",
"not",
"registration_settings",
".",
"RESET_PASSWORD_VERIFICATION_ENABLED",
":",
"raise",
"Http404",
"(",
")",
"serializer",
"=",
"SendResetPasswordLinkSerializer",
"(",
"data",
"=",
"request",
".",
"d... | Send email with reset password link. | [
"Send",
"email",
"with",
"reset",
"password",
"link",
"."
] | 7373571264dd567c2a73a97ff4c45b64f113605b | https://github.com/apragacz/django-rest-registration/blob/7373571264dd567c2a73a97ff4c45b64f113605b/rest_registration/api/views/reset_password.py#L61-L89 | train |
apragacz/django-rest-registration | rest_registration/api/views/register_email.py | register_email | def register_email(request):
'''
Register new email.
'''
user = request.user
serializer = RegisterEmailSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
email = serializer.validated_data['email']
template_config = (
registration_settings.REGISTER_EMAIL_VE... | python | def register_email(request):
'''
Register new email.
'''
user = request.user
serializer = RegisterEmailSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
email = serializer.validated_data['email']
template_config = (
registration_settings.REGISTER_EMAIL_VE... | [
"def",
"register_email",
"(",
"request",
")",
":",
"user",
"=",
"request",
".",
"user",
"serializer",
"=",
"RegisterEmailSerializer",
"(",
"data",
"=",
"request",
".",
"data",
")",
"serializer",
".",
"is_valid",
"(",
"raise_exception",
"=",
"True",
")",
"ema... | Register new email. | [
"Register",
"new",
"email",
"."
] | 7373571264dd567c2a73a97ff4c45b64f113605b | https://github.com/apragacz/django-rest-registration/blob/7373571264dd567c2a73a97ff4c45b64f113605b/rest_registration/api/views/register_email.py#L33-L58 | train |
nschloe/matplotlib2tikz | matplotlib2tikz/axes.py | _is_colorbar_heuristic | def _is_colorbar_heuristic(obj):
"""Find out if the object is in fact a color bar.
"""
# TODO come up with something more accurate here
# Might help:
# TODO Are the colorbars exactly the l.collections.PolyCollection's?
try:
aspect = float(obj.get_aspect())
except ValueError:
... | python | def _is_colorbar_heuristic(obj):
"""Find out if the object is in fact a color bar.
"""
# TODO come up with something more accurate here
# Might help:
# TODO Are the colorbars exactly the l.collections.PolyCollection's?
try:
aspect = float(obj.get_aspect())
except ValueError:
... | [
"def",
"_is_colorbar_heuristic",
"(",
"obj",
")",
":",
"try",
":",
"aspect",
"=",
"float",
"(",
"obj",
".",
"get_aspect",
"(",
")",
")",
"except",
"ValueError",
":",
"return",
"False",
"limit_ratio",
"=",
"5.0",
"return",
"(",
"aspect",
">=",
"limit_ratio"... | Find out if the object is in fact a color bar. | [
"Find",
"out",
"if",
"the",
"object",
"is",
"in",
"fact",
"a",
"color",
"bar",
"."
] | ac5daca6f38b834d757f6c6ae6cc34121956f46b | https://github.com/nschloe/matplotlib2tikz/blob/ac5daca6f38b834d757f6c6ae6cc34121956f46b/matplotlib2tikz/axes.py#L582-L605 | train |
nschloe/matplotlib2tikz | matplotlib2tikz/axes.py | _mpl_cmap2pgf_cmap | def _mpl_cmap2pgf_cmap(cmap, data):
"""Converts a color map as given in matplotlib to a color map as
represented in PGFPlots.
"""
if isinstance(cmap, mpl.colors.LinearSegmentedColormap):
return _handle_linear_segmented_color_map(cmap, data)
assert isinstance(
cmap, mpl.colors.Listed... | python | def _mpl_cmap2pgf_cmap(cmap, data):
"""Converts a color map as given in matplotlib to a color map as
represented in PGFPlots.
"""
if isinstance(cmap, mpl.colors.LinearSegmentedColormap):
return _handle_linear_segmented_color_map(cmap, data)
assert isinstance(
cmap, mpl.colors.Listed... | [
"def",
"_mpl_cmap2pgf_cmap",
"(",
"cmap",
",",
"data",
")",
":",
"if",
"isinstance",
"(",
"cmap",
",",
"mpl",
".",
"colors",
".",
"LinearSegmentedColormap",
")",
":",
"return",
"_handle_linear_segmented_color_map",
"(",
"cmap",
",",
"data",
")",
"assert",
"isi... | Converts a color map as given in matplotlib to a color map as
represented in PGFPlots. | [
"Converts",
"a",
"color",
"map",
"as",
"given",
"in",
"matplotlib",
"to",
"a",
"color",
"map",
"as",
"represented",
"in",
"PGFPlots",
"."
] | ac5daca6f38b834d757f6c6ae6cc34121956f46b | https://github.com/nschloe/matplotlib2tikz/blob/ac5daca6f38b834d757f6c6ae6cc34121956f46b/matplotlib2tikz/axes.py#L608-L618 | train |
nschloe/matplotlib2tikz | matplotlib2tikz/axes.py | _scale_to_int | def _scale_to_int(X, max_val=None):
"""
Scales the array X such that it contains only integers.
"""
if max_val is None:
X = X / _gcd_array(X)
else:
X = X / max(1 / max_val, _gcd_array(X))
return [int(entry) for entry in X] | python | def _scale_to_int(X, max_val=None):
"""
Scales the array X such that it contains only integers.
"""
if max_val is None:
X = X / _gcd_array(X)
else:
X = X / max(1 / max_val, _gcd_array(X))
return [int(entry) for entry in X] | [
"def",
"_scale_to_int",
"(",
"X",
",",
"max_val",
"=",
"None",
")",
":",
"if",
"max_val",
"is",
"None",
":",
"X",
"=",
"X",
"/",
"_gcd_array",
"(",
"X",
")",
"else",
":",
"X",
"=",
"X",
"/",
"max",
"(",
"1",
"/",
"max_val",
",",
"_gcd_array",
"... | Scales the array X such that it contains only integers. | [
"Scales",
"the",
"array",
"X",
"such",
"that",
"it",
"contains",
"only",
"integers",
"."
] | ac5daca6f38b834d757f6c6ae6cc34121956f46b | https://github.com/nschloe/matplotlib2tikz/blob/ac5daca6f38b834d757f6c6ae6cc34121956f46b/matplotlib2tikz/axes.py#L771-L780 | train |
nschloe/matplotlib2tikz | matplotlib2tikz/axes.py | _gcd_array | def _gcd_array(X):
"""
Return the largest real value h such that all elements in x are integer
multiples of h.
"""
greatest_common_divisor = 0.0
for x in X:
greatest_common_divisor = _gcd(greatest_common_divisor, x)
return greatest_common_divisor | python | def _gcd_array(X):
"""
Return the largest real value h such that all elements in x are integer
multiples of h.
"""
greatest_common_divisor = 0.0
for x in X:
greatest_common_divisor = _gcd(greatest_common_divisor, x)
return greatest_common_divisor | [
"def",
"_gcd_array",
"(",
"X",
")",
":",
"greatest_common_divisor",
"=",
"0.0",
"for",
"x",
"in",
"X",
":",
"greatest_common_divisor",
"=",
"_gcd",
"(",
"greatest_common_divisor",
",",
"x",
")",
"return",
"greatest_common_divisor"
] | Return the largest real value h such that all elements in x are integer
multiples of h. | [
"Return",
"the",
"largest",
"real",
"value",
"h",
"such",
"that",
"all",
"elements",
"in",
"x",
"are",
"integer",
"multiples",
"of",
"h",
"."
] | ac5daca6f38b834d757f6c6ae6cc34121956f46b | https://github.com/nschloe/matplotlib2tikz/blob/ac5daca6f38b834d757f6c6ae6cc34121956f46b/matplotlib2tikz/axes.py#L783-L792 | train |
nschloe/matplotlib2tikz | matplotlib2tikz/files.py | new_filename | def new_filename(data, file_kind, ext):
"""Returns an available filename.
:param file_kind: Name under which numbering is recorded, such as 'img' or
'table'.
:type file_kind: str
:param ext: Filename extension.
:type ext: str
:returns: (filename, rel_filepath) where file... | python | def new_filename(data, file_kind, ext):
"""Returns an available filename.
:param file_kind: Name under which numbering is recorded, such as 'img' or
'table'.
:type file_kind: str
:param ext: Filename extension.
:type ext: str
:returns: (filename, rel_filepath) where file... | [
"def",
"new_filename",
"(",
"data",
",",
"file_kind",
",",
"ext",
")",
":",
"nb_key",
"=",
"file_kind",
"+",
"\"number\"",
"if",
"nb_key",
"not",
"in",
"data",
".",
"keys",
"(",
")",
":",
"data",
"[",
"nb_key",
"]",
"=",
"-",
"1",
"if",
"not",
"dat... | Returns an available filename.
:param file_kind: Name under which numbering is recorded, such as 'img' or
'table'.
:type file_kind: str
:param ext: Filename extension.
:type ext: str
:returns: (filename, rel_filepath) where filename is a path in the
filesystem ... | [
"Returns",
"an",
"available",
"filename",
"."
] | ac5daca6f38b834d757f6c6ae6cc34121956f46b | https://github.com/nschloe/matplotlib2tikz/blob/ac5daca6f38b834d757f6c6ae6cc34121956f46b/matplotlib2tikz/files.py#L12-L47 | train |
nschloe/matplotlib2tikz | matplotlib2tikz/path.py | mpl_linestyle2pgfplots_linestyle | def mpl_linestyle2pgfplots_linestyle(line_style, line=None):
"""Translates a line style of matplotlib to the corresponding style
in PGFPlots.
"""
# linestyle is a string or dash tuple. Legal string values are
# solid|dashed|dashdot|dotted. The dash tuple is (offset, onoffseq) where onoffseq
# i... | python | def mpl_linestyle2pgfplots_linestyle(line_style, line=None):
"""Translates a line style of matplotlib to the corresponding style
in PGFPlots.
"""
# linestyle is a string or dash tuple. Legal string values are
# solid|dashed|dashdot|dotted. The dash tuple is (offset, onoffseq) where onoffseq
# i... | [
"def",
"mpl_linestyle2pgfplots_linestyle",
"(",
"line_style",
",",
"line",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"line_style",
",",
"tuple",
")",
":",
"if",
"line_style",
"[",
"0",
"]",
"is",
"None",
":",
"return",
"None",
"if",
"len",
"(",
"li... | Translates a line style of matplotlib to the corresponding style
in PGFPlots. | [
"Translates",
"a",
"line",
"style",
"of",
"matplotlib",
"to",
"the",
"corresponding",
"style",
"in",
"PGFPlots",
"."
] | ac5daca6f38b834d757f6c6ae6cc34121956f46b | https://github.com/nschloe/matplotlib2tikz/blob/ac5daca6f38b834d757f6c6ae6cc34121956f46b/matplotlib2tikz/path.py#L296-L349 | train |
nschloe/matplotlib2tikz | matplotlib2tikz/quadmesh.py | draw_quadmesh | def draw_quadmesh(data, obj):
"""Returns the PGFPlots code for an graphics environment holding a
rendering of the object.
"""
content = []
# Generate file name for current object
filename, rel_filepath = files.new_filename(data, "img", ".png")
# Get the dpi for rendering and store the o... | python | def draw_quadmesh(data, obj):
"""Returns the PGFPlots code for an graphics environment holding a
rendering of the object.
"""
content = []
# Generate file name for current object
filename, rel_filepath = files.new_filename(data, "img", ".png")
# Get the dpi for rendering and store the o... | [
"def",
"draw_quadmesh",
"(",
"data",
",",
"obj",
")",
":",
"content",
"=",
"[",
"]",
"filename",
",",
"rel_filepath",
"=",
"files",
".",
"new_filename",
"(",
"data",
",",
"\"img\"",
",",
"\".png\"",
")",
"dpi",
"=",
"data",
"[",
"\"dpi\"",
"]",
"fig_dp... | Returns the PGFPlots code for an graphics environment holding a
rendering of the object. | [
"Returns",
"the",
"PGFPlots",
"code",
"for",
"an",
"graphics",
"environment",
"holding",
"a",
"rendering",
"of",
"the",
"object",
"."
] | ac5daca6f38b834d757f6c6ae6cc34121956f46b | https://github.com/nschloe/matplotlib2tikz/blob/ac5daca6f38b834d757f6c6ae6cc34121956f46b/matplotlib2tikz/quadmesh.py#L8-L66 | train |
nschloe/matplotlib2tikz | matplotlib2tikz/color.py | mpl_color2xcolor | def mpl_color2xcolor(data, matplotlib_color):
"""Translates a matplotlib color specification into a proper LaTeX xcolor.
"""
# Convert it to RGBA.
my_col = numpy.array(mpl.colors.ColorConverter().to_rgba(matplotlib_color))
# If the alpha channel is exactly 0, then the color is really 'none'
# r... | python | def mpl_color2xcolor(data, matplotlib_color):
"""Translates a matplotlib color specification into a proper LaTeX xcolor.
"""
# Convert it to RGBA.
my_col = numpy.array(mpl.colors.ColorConverter().to_rgba(matplotlib_color))
# If the alpha channel is exactly 0, then the color is really 'none'
# r... | [
"def",
"mpl_color2xcolor",
"(",
"data",
",",
"matplotlib_color",
")",
":",
"my_col",
"=",
"numpy",
".",
"array",
"(",
"mpl",
".",
"colors",
".",
"ColorConverter",
"(",
")",
".",
"to_rgba",
"(",
"matplotlib_color",
")",
")",
"if",
"my_col",
"[",
"-",
"1",... | Translates a matplotlib color specification into a proper LaTeX xcolor. | [
"Translates",
"a",
"matplotlib",
"color",
"specification",
"into",
"a",
"proper",
"LaTeX",
"xcolor",
"."
] | ac5daca6f38b834d757f6c6ae6cc34121956f46b | https://github.com/nschloe/matplotlib2tikz/blob/ac5daca6f38b834d757f6c6ae6cc34121956f46b/matplotlib2tikz/color.py#L9-L81 | train |
nschloe/matplotlib2tikz | matplotlib2tikz/patch.py | draw_patch | def draw_patch(data, obj):
"""Return the PGFPlots code for patches.
"""
# Gather the draw options.
data, draw_options = mypath.get_draw_options(
data,
obj,
obj.get_edgecolor(),
obj.get_facecolor(),
obj.get_linestyle(),
obj.get_linewidth(),
)
if is... | python | def draw_patch(data, obj):
"""Return the PGFPlots code for patches.
"""
# Gather the draw options.
data, draw_options = mypath.get_draw_options(
data,
obj,
obj.get_edgecolor(),
obj.get_facecolor(),
obj.get_linestyle(),
obj.get_linewidth(),
)
if is... | [
"def",
"draw_patch",
"(",
"data",
",",
"obj",
")",
":",
"data",
",",
"draw_options",
"=",
"mypath",
".",
"get_draw_options",
"(",
"data",
",",
"obj",
",",
"obj",
".",
"get_edgecolor",
"(",
")",
",",
"obj",
".",
"get_facecolor",
"(",
")",
",",
"obj",
... | Return the PGFPlots code for patches. | [
"Return",
"the",
"PGFPlots",
"code",
"for",
"patches",
"."
] | ac5daca6f38b834d757f6c6ae6cc34121956f46b | https://github.com/nschloe/matplotlib2tikz/blob/ac5daca6f38b834d757f6c6ae6cc34121956f46b/matplotlib2tikz/patch.py#L8-L32 | train |
nschloe/matplotlib2tikz | matplotlib2tikz/patch.py | _draw_rectangle | def _draw_rectangle(data, obj, draw_options):
"""Return the PGFPlots code for rectangles.
"""
# Objects with labels are plot objects (from bar charts, etc). Even those without
# labels explicitly set have a label of "_nolegend_". Everything else should be
# skipped because they likely correspong t... | python | def _draw_rectangle(data, obj, draw_options):
"""Return the PGFPlots code for rectangles.
"""
# Objects with labels are plot objects (from bar charts, etc). Even those without
# labels explicitly set have a label of "_nolegend_". Everything else should be
# skipped because they likely correspong t... | [
"def",
"_draw_rectangle",
"(",
"data",
",",
"obj",
",",
"draw_options",
")",
":",
"label",
"=",
"obj",
".",
"get_label",
"(",
")",
"if",
"label",
"==",
"\"\"",
":",
"return",
"data",
",",
"[",
"]",
"handles",
",",
"labels",
"=",
"obj",
".",
"axes",
... | Return the PGFPlots code for rectangles. | [
"Return",
"the",
"PGFPlots",
"code",
"for",
"rectangles",
"."
] | ac5daca6f38b834d757f6c6ae6cc34121956f46b | https://github.com/nschloe/matplotlib2tikz/blob/ac5daca6f38b834d757f6c6ae6cc34121956f46b/matplotlib2tikz/patch.py#L91-L131 | train |
nschloe/matplotlib2tikz | matplotlib2tikz/patch.py | _draw_ellipse | def _draw_ellipse(data, obj, draw_options):
"""Return the PGFPlots code for ellipses.
"""
if isinstance(obj, mpl.patches.Circle):
# circle specialization
return _draw_circle(data, obj, draw_options)
x, y = obj.center
ff = data["float format"]
if obj.angle != 0:
fmt = "ro... | python | def _draw_ellipse(data, obj, draw_options):
"""Return the PGFPlots code for ellipses.
"""
if isinstance(obj, mpl.patches.Circle):
# circle specialization
return _draw_circle(data, obj, draw_options)
x, y = obj.center
ff = data["float format"]
if obj.angle != 0:
fmt = "ro... | [
"def",
"_draw_ellipse",
"(",
"data",
",",
"obj",
",",
"draw_options",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"mpl",
".",
"patches",
".",
"Circle",
")",
":",
"return",
"_draw_circle",
"(",
"data",
",",
"obj",
",",
"draw_options",
")",
"x",
",",
... | Return the PGFPlots code for ellipses. | [
"Return",
"the",
"PGFPlots",
"code",
"for",
"ellipses",
"."
] | ac5daca6f38b834d757f6c6ae6cc34121956f46b | https://github.com/nschloe/matplotlib2tikz/blob/ac5daca6f38b834d757f6c6ae6cc34121956f46b/matplotlib2tikz/patch.py#L134-L158 | train |
nschloe/matplotlib2tikz | matplotlib2tikz/patch.py | _draw_circle | def _draw_circle(data, obj, draw_options):
"""Return the PGFPlots code for circles.
"""
x, y = obj.center
ff = data["float format"]
cont = ("\\draw[{}] (axis cs:" + ff + "," + ff + ") circle (" + ff + ");\n").format(
",".join(draw_options), x, y, obj.get_radius()
)
return data, cont | python | def _draw_circle(data, obj, draw_options):
"""Return the PGFPlots code for circles.
"""
x, y = obj.center
ff = data["float format"]
cont = ("\\draw[{}] (axis cs:" + ff + "," + ff + ") circle (" + ff + ");\n").format(
",".join(draw_options), x, y, obj.get_radius()
)
return data, cont | [
"def",
"_draw_circle",
"(",
"data",
",",
"obj",
",",
"draw_options",
")",
":",
"x",
",",
"y",
"=",
"obj",
".",
"center",
"ff",
"=",
"data",
"[",
"\"float format\"",
"]",
"cont",
"=",
"(",
"\"\\\\draw[{}] (axis cs:\"",
"+",
"ff",
"+",
"\",\"",
"+",
"ff"... | Return the PGFPlots code for circles. | [
"Return",
"the",
"PGFPlots",
"code",
"for",
"circles",
"."
] | ac5daca6f38b834d757f6c6ae6cc34121956f46b | https://github.com/nschloe/matplotlib2tikz/blob/ac5daca6f38b834d757f6c6ae6cc34121956f46b/matplotlib2tikz/patch.py#L161-L169 | train |
nschloe/matplotlib2tikz | matplotlib2tikz/image.py | draw_image | def draw_image(data, obj):
"""Returns the PGFPlots code for an image environment.
"""
content = []
filename, rel_filepath = files.new_filename(data, "img", ".png")
# store the image as in a file
img_array = obj.get_array()
dims = img_array.shape
if len(dims) == 2: # the values are gi... | python | def draw_image(data, obj):
"""Returns the PGFPlots code for an image environment.
"""
content = []
filename, rel_filepath = files.new_filename(data, "img", ".png")
# store the image as in a file
img_array = obj.get_array()
dims = img_array.shape
if len(dims) == 2: # the values are gi... | [
"def",
"draw_image",
"(",
"data",
",",
"obj",
")",
":",
"content",
"=",
"[",
"]",
"filename",
",",
"rel_filepath",
"=",
"files",
".",
"new_filename",
"(",
"data",
",",
"\"img\"",
",",
"\".png\"",
")",
"img_array",
"=",
"obj",
".",
"get_array",
"(",
")"... | Returns the PGFPlots code for an image environment. | [
"Returns",
"the",
"PGFPlots",
"code",
"for",
"an",
"image",
"environment",
"."
] | ac5daca6f38b834d757f6c6ae6cc34121956f46b | https://github.com/nschloe/matplotlib2tikz/blob/ac5daca6f38b834d757f6c6ae6cc34121956f46b/matplotlib2tikz/image.py#L10-L64 | train |
nschloe/matplotlib2tikz | matplotlib2tikz/util.py | get_legend_text | def get_legend_text(obj):
"""Check if line is in legend.
"""
leg = obj.axes.get_legend()
if leg is None:
return None
keys = [l.get_label() for l in leg.legendHandles if l is not None]
values = [l.get_text() for l in leg.texts]
label = obj.get_label()
d = dict(zip(keys, values))... | python | def get_legend_text(obj):
"""Check if line is in legend.
"""
leg = obj.axes.get_legend()
if leg is None:
return None
keys = [l.get_label() for l in leg.legendHandles if l is not None]
values = [l.get_text() for l in leg.texts]
label = obj.get_label()
d = dict(zip(keys, values))... | [
"def",
"get_legend_text",
"(",
"obj",
")",
":",
"leg",
"=",
"obj",
".",
"axes",
".",
"get_legend",
"(",
")",
"if",
"leg",
"is",
"None",
":",
"return",
"None",
"keys",
"=",
"[",
"l",
".",
"get_label",
"(",
")",
"for",
"l",
"in",
"leg",
".",
"legen... | Check if line is in legend. | [
"Check",
"if",
"line",
"is",
"in",
"legend",
"."
] | ac5daca6f38b834d757f6c6ae6cc34121956f46b | https://github.com/nschloe/matplotlib2tikz/blob/ac5daca6f38b834d757f6c6ae6cc34121956f46b/matplotlib2tikz/util.py#L11-L26 | train |
nschloe/matplotlib2tikz | matplotlib2tikz/save.py | _get_color_definitions | def _get_color_definitions(data):
"""Returns the list of custom color definitions for the TikZ file.
"""
definitions = []
fmt = "\\definecolor{{{}}}{{rgb}}{{" + ",".join(3 * [data["float format"]]) + "}}"
for name, rgb in data["custom colors"].items():
definitions.append(fmt.format(name, rgb... | python | def _get_color_definitions(data):
"""Returns the list of custom color definitions for the TikZ file.
"""
definitions = []
fmt = "\\definecolor{{{}}}{{rgb}}{{" + ",".join(3 * [data["float format"]]) + "}}"
for name, rgb in data["custom colors"].items():
definitions.append(fmt.format(name, rgb... | [
"def",
"_get_color_definitions",
"(",
"data",
")",
":",
"definitions",
"=",
"[",
"]",
"fmt",
"=",
"\"\\\\definecolor{{{}}}{{rgb}}{{\"",
"+",
"\",\"",
".",
"join",
"(",
"3",
"*",
"[",
"data",
"[",
"\"float format\"",
"]",
"]",
")",
"+",
"\"}}\"",
"for",
"na... | Returns the list of custom color definitions for the TikZ file. | [
"Returns",
"the",
"list",
"of",
"custom",
"color",
"definitions",
"for",
"the",
"TikZ",
"file",
"."
] | ac5daca6f38b834d757f6c6ae6cc34121956f46b | https://github.com/nschloe/matplotlib2tikz/blob/ac5daca6f38b834d757f6c6ae6cc34121956f46b/matplotlib2tikz/save.py#L283-L290 | train |
nschloe/matplotlib2tikz | matplotlib2tikz/save.py | _print_pgfplot_libs_message | def _print_pgfplot_libs_message(data):
"""Prints message to screen indicating the use of PGFPlots and its
libraries."""
pgfplotslibs = ",".join(list(data["pgfplots libs"]))
tikzlibs = ",".join(list(data["tikz libs"]))
print(70 * "=")
print("Please add the following lines to your LaTeX preamble:... | python | def _print_pgfplot_libs_message(data):
"""Prints message to screen indicating the use of PGFPlots and its
libraries."""
pgfplotslibs = ",".join(list(data["pgfplots libs"]))
tikzlibs = ",".join(list(data["tikz libs"]))
print(70 * "=")
print("Please add the following lines to your LaTeX preamble:... | [
"def",
"_print_pgfplot_libs_message",
"(",
"data",
")",
":",
"pgfplotslibs",
"=",
"\",\"",
".",
"join",
"(",
"list",
"(",
"data",
"[",
"\"pgfplots libs\"",
"]",
")",
")",
"tikzlibs",
"=",
"\",\"",
".",
"join",
"(",
"list",
"(",
"data",
"[",
"\"tikz libs\""... | Prints message to screen indicating the use of PGFPlots and its
libraries. | [
"Prints",
"message",
"to",
"screen",
"indicating",
"the",
"use",
"of",
"PGFPlots",
"and",
"its",
"libraries",
"."
] | ac5daca6f38b834d757f6c6ae6cc34121956f46b | https://github.com/nschloe/matplotlib2tikz/blob/ac5daca6f38b834d757f6c6ae6cc34121956f46b/matplotlib2tikz/save.py#L293-L309 | train |
nschloe/matplotlib2tikz | matplotlib2tikz/save.py | _ContentManager.extend | def extend(self, content, zorder):
""" Extends with a list and a z-order
"""
if zorder not in self._content:
self._content[zorder] = []
self._content[zorder].extend(content) | python | def extend(self, content, zorder):
""" Extends with a list and a z-order
"""
if zorder not in self._content:
self._content[zorder] = []
self._content[zorder].extend(content) | [
"def",
"extend",
"(",
"self",
",",
"content",
",",
"zorder",
")",
":",
"if",
"zorder",
"not",
"in",
"self",
".",
"_content",
":",
"self",
".",
"_content",
"[",
"zorder",
"]",
"=",
"[",
"]",
"self",
".",
"_content",
"[",
"zorder",
"]",
".",
"extend"... | Extends with a list and a z-order | [
"Extends",
"with",
"a",
"list",
"and",
"a",
"z",
"-",
"order"
] | ac5daca6f38b834d757f6c6ae6cc34121956f46b | https://github.com/nschloe/matplotlib2tikz/blob/ac5daca6f38b834d757f6c6ae6cc34121956f46b/matplotlib2tikz/save.py#L322-L327 | train |
nschloe/matplotlib2tikz | matplotlib2tikz/line2d.py | draw_line2d | def draw_line2d(data, obj):
"""Returns the PGFPlots code for an Line2D environment.
"""
content = []
addplot_options = []
# If line is of length 0, do nothing. Otherwise, an empty \addplot table will be
# created, which will be interpreted as an external data source in either the file
# ''... | python | def draw_line2d(data, obj):
"""Returns the PGFPlots code for an Line2D environment.
"""
content = []
addplot_options = []
# If line is of length 0, do nothing. Otherwise, an empty \addplot table will be
# created, which will be interpreted as an external data source in either the file
# ''... | [
"def",
"draw_line2d",
"(",
"data",
",",
"obj",
")",
":",
"content",
"=",
"[",
"]",
"addplot_options",
"=",
"[",
"]",
"if",
"len",
"(",
"obj",
".",
"get_xdata",
"(",
")",
")",
"==",
"0",
":",
"return",
"data",
",",
"[",
"]",
"line_width",
"=",
"my... | Returns the PGFPlots code for an Line2D environment. | [
"Returns",
"the",
"PGFPlots",
"code",
"for",
"an",
"Line2D",
"environment",
"."
] | ac5daca6f38b834d757f6c6ae6cc34121956f46b | https://github.com/nschloe/matplotlib2tikz/blob/ac5daca6f38b834d757f6c6ae6cc34121956f46b/matplotlib2tikz/line2d.py#L18-L85 | train |
nschloe/matplotlib2tikz | matplotlib2tikz/line2d.py | draw_linecollection | def draw_linecollection(data, obj):
"""Returns Pgfplots code for a number of patch objects.
"""
content = []
edgecolors = obj.get_edgecolors()
linestyles = obj.get_linestyles()
linewidths = obj.get_linewidths()
paths = obj.get_paths()
for i, path in enumerate(paths):
color = ed... | python | def draw_linecollection(data, obj):
"""Returns Pgfplots code for a number of patch objects.
"""
content = []
edgecolors = obj.get_edgecolors()
linestyles = obj.get_linestyles()
linewidths = obj.get_linewidths()
paths = obj.get_paths()
for i, path in enumerate(paths):
color = ed... | [
"def",
"draw_linecollection",
"(",
"data",
",",
"obj",
")",
":",
"content",
"=",
"[",
"]",
"edgecolors",
"=",
"obj",
".",
"get_edgecolors",
"(",
")",
"linestyles",
"=",
"obj",
".",
"get_linestyles",
"(",
")",
"linewidths",
"=",
"obj",
".",
"get_linewidths"... | Returns Pgfplots code for a number of patch objects. | [
"Returns",
"Pgfplots",
"code",
"for",
"a",
"number",
"of",
"patch",
"objects",
"."
] | ac5daca6f38b834d757f6c6ae6cc34121956f46b | https://github.com/nschloe/matplotlib2tikz/blob/ac5daca6f38b834d757f6c6ae6cc34121956f46b/matplotlib2tikz/line2d.py#L88-L111 | train |
nschloe/matplotlib2tikz | matplotlib2tikz/line2d.py | _mpl_marker2pgfp_marker | def _mpl_marker2pgfp_marker(data, mpl_marker, marker_face_color):
"""Translates a marker style of matplotlib to the corresponding style
in PGFPlots.
"""
# try default list
try:
pgfplots_marker = _MP_MARKER2PGF_MARKER[mpl_marker]
except KeyError:
pass
else:
if (marker_... | python | def _mpl_marker2pgfp_marker(data, mpl_marker, marker_face_color):
"""Translates a marker style of matplotlib to the corresponding style
in PGFPlots.
"""
# try default list
try:
pgfplots_marker = _MP_MARKER2PGF_MARKER[mpl_marker]
except KeyError:
pass
else:
if (marker_... | [
"def",
"_mpl_marker2pgfp_marker",
"(",
"data",
",",
"mpl_marker",
",",
"marker_face_color",
")",
":",
"try",
":",
"pgfplots_marker",
"=",
"_MP_MARKER2PGF_MARKER",
"[",
"mpl_marker",
"]",
"except",
"KeyError",
":",
"pass",
"else",
":",
"if",
"(",
"marker_face_color... | Translates a marker style of matplotlib to the corresponding style
in PGFPlots. | [
"Translates",
"a",
"marker",
"style",
"of",
"matplotlib",
"to",
"the",
"corresponding",
"style",
"in",
"PGFPlots",
"."
] | ac5daca6f38b834d757f6c6ae6cc34121956f46b | https://github.com/nschloe/matplotlib2tikz/blob/ac5daca6f38b834d757f6c6ae6cc34121956f46b/matplotlib2tikz/line2d.py#L147-L182 | train |
nschloe/matplotlib2tikz | matplotlib2tikz/text.py | draw_text | def draw_text(data, obj):
"""Paints text on the graph.
"""
content = []
properties = []
style = []
if isinstance(obj, mpl.text.Annotation):
_annotation(obj, data, content)
# 1: coordinates
# 2: properties (shapes, rotation, etc)
# 3: text style
# 4: the text
# ... | python | def draw_text(data, obj):
"""Paints text on the graph.
"""
content = []
properties = []
style = []
if isinstance(obj, mpl.text.Annotation):
_annotation(obj, data, content)
# 1: coordinates
# 2: properties (shapes, rotation, etc)
# 3: text style
# 4: the text
# ... | [
"def",
"draw_text",
"(",
"data",
",",
"obj",
")",
":",
"content",
"=",
"[",
"]",
"properties",
"=",
"[",
"]",
"style",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"obj",
",",
"mpl",
".",
"text",
".",
"Annotation",
")",
":",
"_annotation",
"(",
"obj",
... | Paints text on the graph. | [
"Paints",
"text",
"on",
"the",
"graph",
"."
] | ac5daca6f38b834d757f6c6ae6cc34121956f46b | https://github.com/nschloe/matplotlib2tikz/blob/ac5daca6f38b834d757f6c6ae6cc34121956f46b/matplotlib2tikz/text.py#L8-L126 | train |
nschloe/matplotlib2tikz | matplotlib2tikz/text.py | _transform_positioning | def _transform_positioning(ha, va):
"""Converts matplotlib positioning to pgf node positioning.
Not quite accurate but the results are equivalent more or less."""
if ha == "center" and va == "center":
return None
ha_mpl_to_tikz = {"right": "east", "left": "west", "center": ""}
va_mpl_to_tik... | python | def _transform_positioning(ha, va):
"""Converts matplotlib positioning to pgf node positioning.
Not quite accurate but the results are equivalent more or less."""
if ha == "center" and va == "center":
return None
ha_mpl_to_tikz = {"right": "east", "left": "west", "center": ""}
va_mpl_to_tik... | [
"def",
"_transform_positioning",
"(",
"ha",
",",
"va",
")",
":",
"if",
"ha",
"==",
"\"center\"",
"and",
"va",
"==",
"\"center\"",
":",
"return",
"None",
"ha_mpl_to_tikz",
"=",
"{",
"\"right\"",
":",
"\"east\"",
",",
"\"left\"",
":",
"\"west\"",
",",
"\"cen... | Converts matplotlib positioning to pgf node positioning.
Not quite accurate but the results are equivalent more or less. | [
"Converts",
"matplotlib",
"positioning",
"to",
"pgf",
"node",
"positioning",
".",
"Not",
"quite",
"accurate",
"but",
"the",
"results",
"are",
"equivalent",
"more",
"or",
"less",
"."
] | ac5daca6f38b834d757f6c6ae6cc34121956f46b | https://github.com/nschloe/matplotlib2tikz/blob/ac5daca6f38b834d757f6c6ae6cc34121956f46b/matplotlib2tikz/text.py#L129-L142 | train |
turicas/rows | rows/plugins/plugin_json.py | import_from_json | def import_from_json(filename_or_fobj, encoding="utf-8", *args, **kwargs):
"""Import a JSON file or file-like object into a `rows.Table`.
If a file-like object is provided it MUST be open in text (non-binary) mode
on Python 3 and could be open in both binary or text mode on Python 2.
"""
source = ... | python | def import_from_json(filename_or_fobj, encoding="utf-8", *args, **kwargs):
"""Import a JSON file or file-like object into a `rows.Table`.
If a file-like object is provided it MUST be open in text (non-binary) mode
on Python 3 and could be open in both binary or text mode on Python 2.
"""
source = ... | [
"def",
"import_from_json",
"(",
"filename_or_fobj",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"source",
"=",
"Source",
".",
"from_file",
"(",
"filename_or_fobj",
",",
"mode",
"=",
"\"rb\"",
",",
"plugin_name",
"=",
... | Import a JSON file or file-like object into a `rows.Table`.
If a file-like object is provided it MUST be open in text (non-binary) mode
on Python 3 and could be open in both binary or text mode on Python 2. | [
"Import",
"a",
"JSON",
"file",
"or",
"file",
"-",
"like",
"object",
"into",
"a",
"rows",
".",
"Table",
"."
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/plugins/plugin_json.py#L33-L47 | train |
turicas/rows | rows/plugins/plugin_json.py | export_to_json | def export_to_json(
table, filename_or_fobj=None, encoding="utf-8", indent=None, *args, **kwargs
):
"""Export a `rows.Table` to a JSON file or file-like object.
If a file-like object is provided it MUST be open in binary mode (like in
`open('myfile.json', mode='wb')`).
"""
# TODO: will work onl... | python | def export_to_json(
table, filename_or_fobj=None, encoding="utf-8", indent=None, *args, **kwargs
):
"""Export a `rows.Table` to a JSON file or file-like object.
If a file-like object is provided it MUST be open in binary mode (like in
`open('myfile.json', mode='wb')`).
"""
# TODO: will work onl... | [
"def",
"export_to_json",
"(",
"table",
",",
"filename_or_fobj",
"=",
"None",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"indent",
"=",
"None",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"fields",
"=",
"table",
".",
"fields",
"prepared_table",
"=",
"pr... | Export a `rows.Table` to a JSON file or file-like object.
If a file-like object is provided it MUST be open in binary mode (like in
`open('myfile.json', mode='wb')`). | [
"Export",
"a",
"rows",
".",
"Table",
"to",
"a",
"JSON",
"file",
"or",
"file",
"-",
"like",
"object",
"."
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/plugins/plugin_json.py#L68-L97 | train |
turicas/rows | rows/utils.py | plugin_name_by_uri | def plugin_name_by_uri(uri):
"Return the plugin name based on the URI"
# TODO: parse URIs like 'sqlite://' also
parsed = urlparse(uri)
basename = os.path.basename(parsed.path)
if not basename.strip():
raise RuntimeError("Could not identify file format.")
plugin_name = basename.split("... | python | def plugin_name_by_uri(uri):
"Return the plugin name based on the URI"
# TODO: parse URIs like 'sqlite://' also
parsed = urlparse(uri)
basename = os.path.basename(parsed.path)
if not basename.strip():
raise RuntimeError("Could not identify file format.")
plugin_name = basename.split("... | [
"def",
"plugin_name_by_uri",
"(",
"uri",
")",
":",
"\"Return the plugin name based on the URI\"",
"parsed",
"=",
"urlparse",
"(",
"uri",
")",
"basename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"parsed",
".",
"path",
")",
"if",
"not",
"basename",
".",
... | Return the plugin name based on the URI | [
"Return",
"the",
"plugin",
"name",
"based",
"on",
"the",
"URI"
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/utils.py#L249-L263 | train |
turicas/rows | rows/utils.py | extension_by_source | def extension_by_source(source, mime_type):
"Return the file extension used by this plugin"
# TODO: should get this information from the plugin
extension = source.plugin_name
if extension:
return extension
if mime_type:
return mime_type.split("/")[-1] | python | def extension_by_source(source, mime_type):
"Return the file extension used by this plugin"
# TODO: should get this information from the plugin
extension = source.plugin_name
if extension:
return extension
if mime_type:
return mime_type.split("/")[-1] | [
"def",
"extension_by_source",
"(",
"source",
",",
"mime_type",
")",
":",
"\"Return the file extension used by this plugin\"",
"extension",
"=",
"source",
".",
"plugin_name",
"if",
"extension",
":",
"return",
"extension",
"if",
"mime_type",
":",
"return",
"mime_type",
... | Return the file extension used by this plugin | [
"Return",
"the",
"file",
"extension",
"used",
"by",
"this",
"plugin"
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/utils.py#L266-L275 | train |
turicas/rows | rows/utils.py | plugin_name_by_mime_type | def plugin_name_by_mime_type(mime_type, mime_name, file_extension):
"Return the plugin name based on the MIME type"
return MIME_TYPE_TO_PLUGIN_NAME.get(
normalize_mime_type(mime_type, mime_name, file_extension), None
) | python | def plugin_name_by_mime_type(mime_type, mime_name, file_extension):
"Return the plugin name based on the MIME type"
return MIME_TYPE_TO_PLUGIN_NAME.get(
normalize_mime_type(mime_type, mime_name, file_extension), None
) | [
"def",
"plugin_name_by_mime_type",
"(",
"mime_type",
",",
"mime_name",
",",
"file_extension",
")",
":",
"\"Return the plugin name based on the MIME type\"",
"return",
"MIME_TYPE_TO_PLUGIN_NAME",
".",
"get",
"(",
"normalize_mime_type",
"(",
"mime_type",
",",
"mime_name",
","... | Return the plugin name based on the MIME type | [
"Return",
"the",
"plugin",
"name",
"based",
"on",
"the",
"MIME",
"type"
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/utils.py#L297-L302 | train |
turicas/rows | rows/utils.py | detect_source | def detect_source(uri, verify_ssl, progress, timeout=5):
"""Return a `rows.Source` with information for a given URI
If URI starts with "http" or "https" the file will be downloaded.
This function should only be used if the URI already exists because it's
going to download/open the file to detect its e... | python | def detect_source(uri, verify_ssl, progress, timeout=5):
"""Return a `rows.Source` with information for a given URI
If URI starts with "http" or "https" the file will be downloaded.
This function should only be used if the URI already exists because it's
going to download/open the file to detect its e... | [
"def",
"detect_source",
"(",
"uri",
",",
"verify_ssl",
",",
"progress",
",",
"timeout",
"=",
"5",
")",
":",
"if",
"uri",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"\"http://\"",
")",
"or",
"uri",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
... | Return a `rows.Source` with information for a given URI
If URI starts with "http" or "https" the file will be downloaded.
This function should only be used if the URI already exists because it's
going to download/open the file to detect its encoding and MIME type. | [
"Return",
"a",
"rows",
".",
"Source",
"with",
"information",
"for",
"a",
"given",
"URI"
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/utils.py#L439-L465 | train |
turicas/rows | rows/utils.py | import_from_source | def import_from_source(source, default_encoding, *args, **kwargs):
"Import data described in a `rows.Source` into a `rows.Table`"
# TODO: test open_compressed
plugin_name = source.plugin_name
kwargs["encoding"] = (
kwargs.get("encoding", None) or source.encoding or default_encoding
)
t... | python | def import_from_source(source, default_encoding, *args, **kwargs):
"Import data described in a `rows.Source` into a `rows.Table`"
# TODO: test open_compressed
plugin_name = source.plugin_name
kwargs["encoding"] = (
kwargs.get("encoding", None) or source.encoding or default_encoding
)
t... | [
"def",
"import_from_source",
"(",
"source",
",",
"default_encoding",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"\"Import data described in a `rows.Source` into a `rows.Table`\"",
"plugin_name",
"=",
"source",
".",
"plugin_name",
"kwargs",
"[",
"\"encoding\"",
"]"... | Import data described in a `rows.Source` into a `rows.Table` | [
"Import",
"data",
"described",
"in",
"a",
"rows",
".",
"Source",
"into",
"a",
"rows",
".",
"Table"
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/utils.py#L468-L484 | train |
turicas/rows | rows/utils.py | import_from_uri | def import_from_uri(
uri, default_encoding="utf-8", verify_ssl=True, progress=False, *args, **kwargs
):
"Given an URI, detects plugin and encoding and imports into a `rows.Table`"
# TODO: support '-' also
# TODO: (optimization) if `kwargs.get('encoding', None) is not None` we can
# skip encod... | python | def import_from_uri(
uri, default_encoding="utf-8", verify_ssl=True, progress=False, *args, **kwargs
):
"Given an URI, detects plugin and encoding and imports into a `rows.Table`"
# TODO: support '-' also
# TODO: (optimization) if `kwargs.get('encoding', None) is not None` we can
# skip encod... | [
"def",
"import_from_uri",
"(",
"uri",
",",
"default_encoding",
"=",
"\"utf-8\"",
",",
"verify_ssl",
"=",
"True",
",",
"progress",
"=",
"False",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"\"Given an URI, detects plugin and encoding and imports into a `rows.Table... | Given an URI, detects plugin and encoding and imports into a `rows.Table` | [
"Given",
"an",
"URI",
"detects",
"plugin",
"and",
"encoding",
"and",
"imports",
"into",
"a",
"rows",
".",
"Table"
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/utils.py#L487-L496 | train |
turicas/rows | rows/utils.py | open_compressed | def open_compressed(filename, mode="r", encoding=None):
"Return a text-based file object from a filename, even if compressed"
# TODO: integrate this function in the library itself, using
# get_filename_and_fobj
binary_mode = "b" in mode
extension = str(filename).split(".")[-1].lower()
if binary... | python | def open_compressed(filename, mode="r", encoding=None):
"Return a text-based file object from a filename, even if compressed"
# TODO: integrate this function in the library itself, using
# get_filename_and_fobj
binary_mode = "b" in mode
extension = str(filename).split(".")[-1].lower()
if binary... | [
"def",
"open_compressed",
"(",
"filename",
",",
"mode",
"=",
"\"r\"",
",",
"encoding",
"=",
"None",
")",
":",
"\"Return a text-based file object from a filename, even if compressed\"",
"binary_mode",
"=",
"\"b\"",
"in",
"mode",
"extension",
"=",
"str",
"(",
"filename"... | Return a text-based file object from a filename, even if compressed | [
"Return",
"a",
"text",
"-",
"based",
"file",
"object",
"from",
"a",
"filename",
"even",
"if",
"compressed"
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/utils.py#L513-L557 | train |
turicas/rows | rows/utils.py | csv_to_sqlite | def csv_to_sqlite(
input_filename,
output_filename,
samples=None,
dialect=None,
batch_size=10000,
encoding="utf-8",
callback=None,
force_types=None,
chunk_size=8388608,
table_name="table1",
schema=None,
):
"Export a CSV file to SQLite, based on field type detection from s... | python | def csv_to_sqlite(
input_filename,
output_filename,
samples=None,
dialect=None,
batch_size=10000,
encoding="utf-8",
callback=None,
force_types=None,
chunk_size=8388608,
table_name="table1",
schema=None,
):
"Export a CSV file to SQLite, based on field type detection from s... | [
"def",
"csv_to_sqlite",
"(",
"input_filename",
",",
"output_filename",
",",
"samples",
"=",
"None",
",",
"dialect",
"=",
"None",
",",
"batch_size",
"=",
"10000",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"callback",
"=",
"None",
",",
"force_types",
"=",
"None"... | Export a CSV file to SQLite, based on field type detection from samples | [
"Export",
"a",
"CSV",
"file",
"to",
"SQLite",
"based",
"on",
"field",
"type",
"detection",
"from",
"samples"
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/utils.py#L560-L613 | train |
turicas/rows | rows/utils.py | sqlite_to_csv | def sqlite_to_csv(
input_filename,
table_name,
output_filename,
dialect=csv.excel,
batch_size=10000,
encoding="utf-8",
callback=None,
query=None,
):
"""Export a table inside a SQLite database to CSV"""
# TODO: should be able to specify fields
# TODO: should be able to specif... | python | def sqlite_to_csv(
input_filename,
table_name,
output_filename,
dialect=csv.excel,
batch_size=10000,
encoding="utf-8",
callback=None,
query=None,
):
"""Export a table inside a SQLite database to CSV"""
# TODO: should be able to specify fields
# TODO: should be able to specif... | [
"def",
"sqlite_to_csv",
"(",
"input_filename",
",",
"table_name",
",",
"output_filename",
",",
"dialect",
"=",
"csv",
".",
"excel",
",",
"batch_size",
"=",
"10000",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"callback",
"=",
"None",
",",
"query",
"=",
"None",
... | Export a table inside a SQLite database to CSV | [
"Export",
"a",
"table",
"inside",
"a",
"SQLite",
"database",
"to",
"CSV"
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/utils.py#L616-L650 | train |
turicas/rows | rows/utils.py | execute_command | def execute_command(command):
"""Execute a command and return its output"""
command = shlex.split(command)
try:
process = subprocess.Popen(
command,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
except FileNotFou... | python | def execute_command(command):
"""Execute a command and return its output"""
command = shlex.split(command)
try:
process = subprocess.Popen(
command,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
except FileNotFou... | [
"def",
"execute_command",
"(",
"command",
")",
":",
"command",
"=",
"shlex",
".",
"split",
"(",
"command",
")",
"try",
":",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"command",
",",
"stdin",
"=",
"subprocess",
".",
"PIPE",
",",
"stdout",
"=",
"s... | Execute a command and return its output | [
"Execute",
"a",
"command",
"and",
"return",
"its",
"output"
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/utils.py#L706-L724 | train |
turicas/rows | rows/utils.py | uncompressed_size | def uncompressed_size(filename):
"""Return the uncompressed size for a file by executing commands
Note: due to a limitation in gzip format, uncompressed files greather than
4GiB will have a wrong value.
"""
quoted_filename = shlex.quote(filename)
# TODO: get filetype from file-magic, if avail... | python | def uncompressed_size(filename):
"""Return the uncompressed size for a file by executing commands
Note: due to a limitation in gzip format, uncompressed files greather than
4GiB will have a wrong value.
"""
quoted_filename = shlex.quote(filename)
# TODO: get filetype from file-magic, if avail... | [
"def",
"uncompressed_size",
"(",
"filename",
")",
":",
"quoted_filename",
"=",
"shlex",
".",
"quote",
"(",
"filename",
")",
"if",
"str",
"(",
"filename",
")",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"\".xz\"",
")",
":",
"output",
"=",
"execute_comm... | Return the uncompressed size for a file by executing commands
Note: due to a limitation in gzip format, uncompressed files greather than
4GiB will have a wrong value. | [
"Return",
"the",
"uncompressed",
"size",
"for",
"a",
"file",
"by",
"executing",
"commands"
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/utils.py#L727-L755 | train |
turicas/rows | rows/utils.py | pgimport | def pgimport(
filename,
database_uri,
table_name,
encoding="utf-8",
dialect=None,
create_table=True,
schema=None,
callback=None,
timeout=0.1,
chunk_size=8388608,
max_samples=10000,
):
"""Import data from CSV into PostgreSQL using the fastest method
Required: psql com... | python | def pgimport(
filename,
database_uri,
table_name,
encoding="utf-8",
dialect=None,
create_table=True,
schema=None,
callback=None,
timeout=0.1,
chunk_size=8388608,
max_samples=10000,
):
"""Import data from CSV into PostgreSQL using the fastest method
Required: psql com... | [
"def",
"pgimport",
"(",
"filename",
",",
"database_uri",
",",
"table_name",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"dialect",
"=",
"None",
",",
"create_table",
"=",
"True",
",",
"schema",
"=",
"None",
",",
"callback",
"=",
"None",
",",
"timeout",
"=",
"... | Import data from CSV into PostgreSQL using the fastest method
Required: psql command | [
"Import",
"data",
"from",
"CSV",
"into",
"PostgreSQL",
"using",
"the",
"fastest",
"method"
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/utils.py#L831-L924 | train |
turicas/rows | rows/utils.py | pgexport | def pgexport(
database_uri,
table_name,
filename,
encoding="utf-8",
dialect=csv.excel,
callback=None,
timeout=0.1,
chunk_size=8388608,
):
"""Export data from PostgreSQL into a CSV file using the fastest method
Required: psql command
"""
if isinstance(dialect, six.text_t... | python | def pgexport(
database_uri,
table_name,
filename,
encoding="utf-8",
dialect=csv.excel,
callback=None,
timeout=0.1,
chunk_size=8388608,
):
"""Export data from PostgreSQL into a CSV file using the fastest method
Required: psql command
"""
if isinstance(dialect, six.text_t... | [
"def",
"pgexport",
"(",
"database_uri",
",",
"table_name",
",",
"filename",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"dialect",
"=",
"csv",
".",
"excel",
",",
"callback",
"=",
"None",
",",
"timeout",
"=",
"0.1",
",",
"chunk_size",
"=",
"8388608",
",",
")"... | Export data from PostgreSQL into a CSV file using the fastest method
Required: psql command | [
"Export",
"data",
"from",
"PostgreSQL",
"into",
"a",
"CSV",
"file",
"using",
"the",
"fastest",
"method"
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/utils.py#L927-L980 | train |
turicas/rows | rows/utils.py | load_schema | def load_schema(filename, context=None):
"""Load schema from file in any of the supported formats
The table must have at least the fields `field_name` and `field_type`.
`context` is a `dict` with field_type as key pointing to field class, like:
{"text": rows.fields.TextField, "value": MyCustomField... | python | def load_schema(filename, context=None):
"""Load schema from file in any of the supported formats
The table must have at least the fields `field_name` and `field_type`.
`context` is a `dict` with field_type as key pointing to field class, like:
{"text": rows.fields.TextField, "value": MyCustomField... | [
"def",
"load_schema",
"(",
"filename",
",",
"context",
"=",
"None",
")",
":",
"table",
"=",
"import_from_uri",
"(",
"filename",
")",
"field_names",
"=",
"table",
".",
"field_names",
"assert",
"\"field_name\"",
"in",
"field_names",
"assert",
"\"field_type\"",
"in... | Load schema from file in any of the supported formats
The table must have at least the fields `field_name` and `field_type`.
`context` is a `dict` with field_type as key pointing to field class, like:
{"text": rows.fields.TextField, "value": MyCustomField} | [
"Load",
"schema",
"from",
"file",
"in",
"any",
"of",
"the",
"supported",
"formats"
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/utils.py#L1082-L1104 | train |
turicas/rows | rows/fields.py | slug | def slug(text, separator="_", permitted_chars=SLUG_CHARS):
"""Generate a slug for the `text`.
>>> slug(' ÁLVARO justen% ')
'alvaro_justen'
>>> slug(' ÁLVARO justen% ', separator='-')
'alvaro-justen'
"""
text = six.text_type(text or "")
# Strip non-ASCII characters
# Example: u' ... | python | def slug(text, separator="_", permitted_chars=SLUG_CHARS):
"""Generate a slug for the `text`.
>>> slug(' ÁLVARO justen% ')
'alvaro_justen'
>>> slug(' ÁLVARO justen% ', separator='-')
'alvaro-justen'
"""
text = six.text_type(text or "")
# Strip non-ASCII characters
# Example: u' ... | [
"def",
"slug",
"(",
"text",
",",
"separator",
"=",
"\"_\"",
",",
"permitted_chars",
"=",
"SLUG_CHARS",
")",
":",
"text",
"=",
"six",
".",
"text_type",
"(",
"text",
"or",
"\"\"",
")",
"text",
"=",
"normalize",
"(",
"\"NFKD\"",
",",
"text",
".",
"strip",... | Generate a slug for the `text`.
>>> slug(' ÁLVARO justen% ')
'alvaro_justen'
>>> slug(' ÁLVARO justen% ', separator='-')
'alvaro-justen' | [
"Generate",
"a",
"slug",
"for",
"the",
"text",
"."
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/fields.py#L520-L553 | train |
turicas/rows | rows/fields.py | make_unique_name | def make_unique_name(name, existing_names, name_format="{name}_{index}", start=2):
"""Return a unique name based on `name_format` and `name`."""
index = start
new_name = name
while new_name in existing_names:
new_name = name_format.format(name=name, index=index)
index += 1
return ne... | python | def make_unique_name(name, existing_names, name_format="{name}_{index}", start=2):
"""Return a unique name based on `name_format` and `name`."""
index = start
new_name = name
while new_name in existing_names:
new_name = name_format.format(name=name, index=index)
index += 1
return ne... | [
"def",
"make_unique_name",
"(",
"name",
",",
"existing_names",
",",
"name_format",
"=",
"\"{name}_{index}\"",
",",
"start",
"=",
"2",
")",
":",
"index",
"=",
"start",
"new_name",
"=",
"name",
"while",
"new_name",
"in",
"existing_names",
":",
"new_name",
"=",
... | Return a unique name based on `name_format` and `name`. | [
"Return",
"a",
"unique",
"name",
"based",
"on",
"name_format",
"and",
"name",
"."
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/fields.py#L556-L564 | train |
turicas/rows | rows/fields.py | make_header | def make_header(field_names, permit_not=False):
"""Return unique and slugged field names."""
slug_chars = SLUG_CHARS if not permit_not else SLUG_CHARS + "^"
header = [
slug(field_name, permitted_chars=slug_chars) for field_name in field_names
]
result = []
for index, field_name in enume... | python | def make_header(field_names, permit_not=False):
"""Return unique and slugged field names."""
slug_chars = SLUG_CHARS if not permit_not else SLUG_CHARS + "^"
header = [
slug(field_name, permitted_chars=slug_chars) for field_name in field_names
]
result = []
for index, field_name in enume... | [
"def",
"make_header",
"(",
"field_names",
",",
"permit_not",
"=",
"False",
")",
":",
"slug_chars",
"=",
"SLUG_CHARS",
"if",
"not",
"permit_not",
"else",
"SLUG_CHARS",
"+",
"\"^\"",
"header",
"=",
"[",
"slug",
"(",
"field_name",
",",
"permitted_chars",
"=",
"... | Return unique and slugged field names. | [
"Return",
"unique",
"and",
"slugged",
"field",
"names",
"."
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/fields.py#L567-L587 | train |
turicas/rows | rows/fields.py | Field.deserialize | def deserialize(cls, value, *args, **kwargs):
"""Deserialize a value just after importing it
`cls.deserialize` should always return a value of type `cls.TYPE` or
`None`.
"""
if isinstance(value, cls.TYPE):
return value
elif is_null(value):
return... | python | def deserialize(cls, value, *args, **kwargs):
"""Deserialize a value just after importing it
`cls.deserialize` should always return a value of type `cls.TYPE` or
`None`.
"""
if isinstance(value, cls.TYPE):
return value
elif is_null(value):
return... | [
"def",
"deserialize",
"(",
"cls",
",",
"value",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"cls",
".",
"TYPE",
")",
":",
"return",
"value",
"elif",
"is_null",
"(",
"value",
")",
":",
"return",
"None",
"e... | Deserialize a value just after importing it
`cls.deserialize` should always return a value of type `cls.TYPE` or
`None`. | [
"Deserialize",
"a",
"value",
"just",
"after",
"importing",
"it"
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/fields.py#L91-L103 | train |
turicas/rows | rows/plugins/plugin_pdf.py | ExtractionAlgorithm.selected_objects | def selected_objects(self):
"""Filter out objects outside table boundaries"""
return [
obj
for obj in self.text_objects
if contains_or_overlap(self.table_bbox, obj.bbox)
] | python | def selected_objects(self):
"""Filter out objects outside table boundaries"""
return [
obj
for obj in self.text_objects
if contains_or_overlap(self.table_bbox, obj.bbox)
] | [
"def",
"selected_objects",
"(",
"self",
")",
":",
"return",
"[",
"obj",
"for",
"obj",
"in",
"self",
".",
"text_objects",
"if",
"contains_or_overlap",
"(",
"self",
".",
"table_bbox",
",",
"obj",
".",
"bbox",
")",
"]"
] | Filter out objects outside table boundaries | [
"Filter",
"out",
"objects",
"outside",
"table",
"boundaries"
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/plugins/plugin_pdf.py#L446-L453 | train |
turicas/rows | examples/library/extract_links.py | transform | def transform(row, table):
'Extract links from "project" field and remove HTML from all'
data = row._asdict()
data["links"] = " ".join(extract_links(row.project))
for key, value in data.items():
if isinstance(value, six.text_type):
data[key] = extract_text(value)
return data | python | def transform(row, table):
'Extract links from "project" field and remove HTML from all'
data = row._asdict()
data["links"] = " ".join(extract_links(row.project))
for key, value in data.items():
if isinstance(value, six.text_type):
data[key] = extract_text(value)
return data | [
"def",
"transform",
"(",
"row",
",",
"table",
")",
":",
"'Extract links from \"project\" field and remove HTML from all'",
"data",
"=",
"row",
".",
"_asdict",
"(",
")",
"data",
"[",
"\"links\"",
"]",
"=",
"\" \"",
".",
"join",
"(",
"extract_links",
"(",
"row",
... | Extract links from "project" field and remove HTML from all | [
"Extract",
"links",
"from",
"project",
"field",
"and",
"remove",
"HTML",
"from",
"all"
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/examples/library/extract_links.py#L24-L32 | train |
turicas/rows | examples/library/brazilian_cities_wikipedia.py | transform | def transform(row, table):
'Transform row "link" into full URL and add "state" based on "name"'
data = row._asdict()
data["link"] = urljoin("https://pt.wikipedia.org", data["link"])
data["name"], data["state"] = regexp_city_state.findall(data["name"])[0]
return data | python | def transform(row, table):
'Transform row "link" into full URL and add "state" based on "name"'
data = row._asdict()
data["link"] = urljoin("https://pt.wikipedia.org", data["link"])
data["name"], data["state"] = regexp_city_state.findall(data["name"])[0]
return data | [
"def",
"transform",
"(",
"row",
",",
"table",
")",
":",
"'Transform row \"link\" into full URL and add \"state\" based on \"name\"'",
"data",
"=",
"row",
".",
"_asdict",
"(",
")",
"data",
"[",
"\"link\"",
"]",
"=",
"urljoin",
"(",
"\"https://pt.wikipedia.org\"",
",",
... | Transform row "link" into full URL and add "state" based on "name" | [
"Transform",
"row",
"link",
"into",
"full",
"URL",
"and",
"add",
"state",
"based",
"on",
"name"
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/examples/library/brazilian_cities_wikipedia.py#L34-L40 | train |
turicas/rows | rows/plugins/plugin_parquet.py | import_from_parquet | def import_from_parquet(filename_or_fobj, *args, **kwargs):
"""Import data from a Parquet file and return with rows.Table."""
source = Source.from_file(filename_or_fobj, plugin_name="parquet", mode="rb")
# TODO: should look into `schema.converted_type` also
types = OrderedDict(
[
(s... | python | def import_from_parquet(filename_or_fobj, *args, **kwargs):
"""Import data from a Parquet file and return with rows.Table."""
source = Source.from_file(filename_or_fobj, plugin_name="parquet", mode="rb")
# TODO: should look into `schema.converted_type` also
types = OrderedDict(
[
(s... | [
"def",
"import_from_parquet",
"(",
"filename_or_fobj",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"source",
"=",
"Source",
".",
"from_file",
"(",
"filename_or_fobj",
",",
"plugin_name",
"=",
"\"parquet\"",
",",
"mode",
"=",
"\"rb\"",
")",
"types",
"=",... | Import data from a Parquet file and return with rows.Table. | [
"Import",
"data",
"from",
"a",
"Parquet",
"file",
"and",
"return",
"with",
"rows",
".",
"Table",
"."
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/plugins/plugin_parquet.py#L47-L65 | train |
turicas/rows | rows/plugins/dicts.py | import_from_dicts | def import_from_dicts(data, samples=None, *args, **kwargs):
"""Import data from a iterable of dicts
The algorithm will use the `samples` first `dict`s to determine the field
names (if `samples` is `None` all `dict`s will be used).
"""
data = iter(data)
cached_rows, headers = [], []
for in... | python | def import_from_dicts(data, samples=None, *args, **kwargs):
"""Import data from a iterable of dicts
The algorithm will use the `samples` first `dict`s to determine the field
names (if `samples` is `None` all `dict`s will be used).
"""
data = iter(data)
cached_rows, headers = [], []
for in... | [
"def",
"import_from_dicts",
"(",
"data",
",",
"samples",
"=",
"None",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"data",
"=",
"iter",
"(",
"data",
")",
"cached_rows",
",",
"headers",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"index",
",",
"row",
... | Import data from a iterable of dicts
The algorithm will use the `samples` first `dict`s to determine the field
names (if `samples` is `None` all `dict`s will be used). | [
"Import",
"data",
"from",
"a",
"iterable",
"of",
"dicts"
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/plugins/dicts.py#L25-L52 | train |
turicas/rows | rows/plugins/dicts.py | export_to_dicts | def export_to_dicts(table, *args, **kwargs):
"""Export a `rows.Table` to a list of dicts"""
field_names = table.field_names
return [{key: getattr(row, key) for key in field_names} for row in table] | python | def export_to_dicts(table, *args, **kwargs):
"""Export a `rows.Table` to a list of dicts"""
field_names = table.field_names
return [{key: getattr(row, key) for key in field_names} for row in table] | [
"def",
"export_to_dicts",
"(",
"table",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"field_names",
"=",
"table",
".",
"field_names",
"return",
"[",
"{",
"key",
":",
"getattr",
"(",
"row",
",",
"key",
")",
"for",
"key",
"in",
"field_names",
"}",
... | Export a `rows.Table` to a list of dicts | [
"Export",
"a",
"rows",
".",
"Table",
"to",
"a",
"list",
"of",
"dicts"
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/plugins/dicts.py#L55-L58 | train |
turicas/rows | rows/plugins/xls.py | cell_value | def cell_value(sheet, row, col):
"""Return the cell value of the table passed by argument, based in row and column."""
cell = sheet.cell(row, col)
field_type = CELL_TYPES[cell.ctype]
# TODO: this approach will not work if using locale
value = cell.value
if field_type is None:
return No... | python | def cell_value(sheet, row, col):
"""Return the cell value of the table passed by argument, based in row and column."""
cell = sheet.cell(row, col)
field_type = CELL_TYPES[cell.ctype]
# TODO: this approach will not work if using locale
value = cell.value
if field_type is None:
return No... | [
"def",
"cell_value",
"(",
"sheet",
",",
"row",
",",
"col",
")",
":",
"cell",
"=",
"sheet",
".",
"cell",
"(",
"row",
",",
"col",
")",
"field_type",
"=",
"CELL_TYPES",
"[",
"cell",
".",
"ctype",
"]",
"value",
"=",
"cell",
".",
"value",
"if",
"field_t... | Return the cell value of the table passed by argument, based in row and column. | [
"Return",
"the",
"cell",
"value",
"of",
"the",
"table",
"passed",
"by",
"argument",
"based",
"in",
"row",
"and",
"column",
"."
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/plugins/xls.py#L83-L143 | train |
turicas/rows | rows/plugins/xls.py | import_from_xls | def import_from_xls(
filename_or_fobj,
sheet_name=None,
sheet_index=0,
start_row=None,
start_column=None,
end_row=None,
end_column=None,
*args,
**kwargs
):
"""Return a rows.Table created from imported XLS file."""
source = Source.from_file(filename_or_fobj, mode="rb", plugin... | python | def import_from_xls(
filename_or_fobj,
sheet_name=None,
sheet_index=0,
start_row=None,
start_column=None,
end_row=None,
end_column=None,
*args,
**kwargs
):
"""Return a rows.Table created from imported XLS file."""
source = Source.from_file(filename_or_fobj, mode="rb", plugin... | [
"def",
"import_from_xls",
"(",
"filename_or_fobj",
",",
"sheet_name",
"=",
"None",
",",
"sheet_index",
"=",
"0",
",",
"start_row",
"=",
"None",
",",
"start_column",
"=",
"None",
",",
"end_row",
"=",
"None",
",",
"end_column",
"=",
"None",
",",
"*",
"args",... | Return a rows.Table created from imported XLS file. | [
"Return",
"a",
"rows",
".",
"Table",
"created",
"from",
"imported",
"XLS",
"file",
"."
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/plugins/xls.py#L160-L212 | train |
turicas/rows | rows/plugins/xls.py | export_to_xls | def export_to_xls(table, filename_or_fobj=None, sheet_name="Sheet1", *args, **kwargs):
"""Export the rows.Table to XLS file and return the saved file."""
workbook = xlwt.Workbook()
sheet = workbook.add_sheet(sheet_name)
prepared_table = prepare_to_export(table, *args, **kwargs)
field_names = next... | python | def export_to_xls(table, filename_or_fobj=None, sheet_name="Sheet1", *args, **kwargs):
"""Export the rows.Table to XLS file and return the saved file."""
workbook = xlwt.Workbook()
sheet = workbook.add_sheet(sheet_name)
prepared_table = prepare_to_export(table, *args, **kwargs)
field_names = next... | [
"def",
"export_to_xls",
"(",
"table",
",",
"filename_or_fobj",
"=",
"None",
",",
"sheet_name",
"=",
"\"Sheet1\"",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"workbook",
"=",
"xlwt",
".",
"Workbook",
"(",
")",
"sheet",
"=",
"workbook",
".",
"add_she... | Export the rows.Table to XLS file and return the saved file. | [
"Export",
"the",
"rows",
".",
"Table",
"to",
"XLS",
"file",
"and",
"return",
"the",
"saved",
"file",
"."
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/plugins/xls.py#L215-L250 | train |
turicas/rows | rows/plugins/postgresql.py | _valid_table_name | def _valid_table_name(name):
"""Verify if a given table name is valid for `rows`
Rules:
- Should start with a letter or '_'
- Letters can be capitalized or not
- Accepts letters, numbers and _
"""
if name[0] not in "_" + string.ascii_letters or not set(name).issubset(
"_" + string.... | python | def _valid_table_name(name):
"""Verify if a given table name is valid for `rows`
Rules:
- Should start with a letter or '_'
- Letters can be capitalized or not
- Accepts letters, numbers and _
"""
if name[0] not in "_" + string.ascii_letters or not set(name).issubset(
"_" + string.... | [
"def",
"_valid_table_name",
"(",
"name",
")",
":",
"if",
"name",
"[",
"0",
"]",
"not",
"in",
"\"_\"",
"+",
"string",
".",
"ascii_letters",
"or",
"not",
"set",
"(",
"name",
")",
".",
"issubset",
"(",
"\"_\"",
"+",
"string",
".",
"ascii_letters",
"+",
... | Verify if a given table name is valid for `rows`
Rules:
- Should start with a letter or '_'
- Letters can be capitalized or not
- Accepts letters, numbers and _ | [
"Verify",
"if",
"a",
"given",
"table",
"name",
"is",
"valid",
"for",
"rows"
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/plugins/postgresql.py#L104-L119 | train |
turicas/rows | rows/plugins/txt.py | _parse_col_positions | def _parse_col_positions(frame_style, header_line):
"""Find the position for each column separator in the given line
If frame_style is 'None', this won work
for column names that _start_ with whitespace
(which includes non-lefthand aligned column titles)
"""
separator = re.escape(FRAMES[frame_... | python | def _parse_col_positions(frame_style, header_line):
"""Find the position for each column separator in the given line
If frame_style is 'None', this won work
for column names that _start_ with whitespace
(which includes non-lefthand aligned column titles)
"""
separator = re.escape(FRAMES[frame_... | [
"def",
"_parse_col_positions",
"(",
"frame_style",
",",
"header_line",
")",
":",
"separator",
"=",
"re",
".",
"escape",
"(",
"FRAMES",
"[",
"frame_style",
".",
"lower",
"(",
")",
"]",
"[",
"\"VERTICAL\"",
"]",
")",
"if",
"frame_style",
"==",
"\"None\"",
":... | Find the position for each column separator in the given line
If frame_style is 'None', this won work
for column names that _start_ with whitespace
(which includes non-lefthand aligned column titles) | [
"Find",
"the",
"position",
"for",
"each",
"column",
"separator",
"in",
"the",
"given",
"line"
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/plugins/txt.py#L99-L119 | train |
turicas/rows | rows/plugins/txt.py | import_from_txt | def import_from_txt(
filename_or_fobj, encoding="utf-8", frame_style=FRAME_SENTINEL, *args, **kwargs
):
"""Return a rows.Table created from imported TXT file."""
# TODO: (maybe)
# enable parsing of non-fixed-width-columns
# with old algorithm - that would just split columns
# at the vertical se... | python | def import_from_txt(
filename_or_fobj, encoding="utf-8", frame_style=FRAME_SENTINEL, *args, **kwargs
):
"""Return a rows.Table created from imported TXT file."""
# TODO: (maybe)
# enable parsing of non-fixed-width-columns
# with old algorithm - that would just split columns
# at the vertical se... | [
"def",
"import_from_txt",
"(",
"filename_or_fobj",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"frame_style",
"=",
"FRAME_SENTINEL",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"source",
"=",
"Source",
".",
"from_file",
"(",
"filename_or_fobj",
",",
"mode",
... | Return a rows.Table created from imported TXT file. | [
"Return",
"a",
"rows",
".",
"Table",
"created",
"from",
"imported",
"TXT",
"file",
"."
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/plugins/txt.py#L130-L179 | train |
turicas/rows | rows/plugins/txt.py | export_to_txt | def export_to_txt(
table,
filename_or_fobj=None,
encoding=None,
frame_style="ASCII",
safe_none_frame=True,
*args,
**kwargs
):
"""Export a `rows.Table` to text.
This function can return the result as a string or save into a file (via
filename or file-like object).
`encoding`... | python | def export_to_txt(
table,
filename_or_fobj=None,
encoding=None,
frame_style="ASCII",
safe_none_frame=True,
*args,
**kwargs
):
"""Export a `rows.Table` to text.
This function can return the result as a string or save into a file (via
filename or file-like object).
`encoding`... | [
"def",
"export_to_txt",
"(",
"table",
",",
"filename_or_fobj",
"=",
"None",
",",
"encoding",
"=",
"None",
",",
"frame_style",
"=",
"\"ASCII\"",
",",
"safe_none_frame",
"=",
"True",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"frame_style",
"=",
"_pars... | Export a `rows.Table` to text.
This function can return the result as a string or save into a file (via
filename or file-like object).
`encoding` could be `None` if no filename/file-like object is specified,
then the return type will be `six.text_type`.
`frame_style`: will select the frame style t... | [
"Export",
"a",
"rows",
".",
"Table",
"to",
"text",
"."
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/plugins/txt.py#L182-L270 | train |
turicas/rows | rows/plugins/sqlite.py | import_from_sqlite | def import_from_sqlite(
filename_or_connection,
table_name="table1",
query=None,
query_args=None,
*args,
**kwargs
):
"""Return a rows.Table with data from SQLite database."""
source = get_source(filename_or_connection)
connection = source.fobj
cursor = connection.cursor()
if... | python | def import_from_sqlite(
filename_or_connection,
table_name="table1",
query=None,
query_args=None,
*args,
**kwargs
):
"""Return a rows.Table with data from SQLite database."""
source = get_source(filename_or_connection)
connection = source.fobj
cursor = connection.cursor()
if... | [
"def",
"import_from_sqlite",
"(",
"filename_or_connection",
",",
"table_name",
"=",
"\"table1\"",
",",
"query",
"=",
"None",
",",
"query_args",
"=",
"None",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"source",
"=",
"get_source",
"(",
"filename_or_connect... | Return a rows.Table with data from SQLite database. | [
"Return",
"a",
"rows",
".",
"Table",
"with",
"data",
"from",
"SQLite",
"database",
"."
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/plugins/sqlite.py#L140-L168 | train |
turicas/rows | rows/plugins/xlsx.py | _cell_to_python | def _cell_to_python(cell):
"""Convert a PyOpenXL's `Cell` object to the corresponding Python object."""
data_type, value = cell.data_type, cell.value
if type(cell) is EmptyCell:
return None
elif data_type == "f" and value == "=TRUE()":
return True
elif data_type == "f" and value == ... | python | def _cell_to_python(cell):
"""Convert a PyOpenXL's `Cell` object to the corresponding Python object."""
data_type, value = cell.data_type, cell.value
if type(cell) is EmptyCell:
return None
elif data_type == "f" and value == "=TRUE()":
return True
elif data_type == "f" and value == ... | [
"def",
"_cell_to_python",
"(",
"cell",
")",
":",
"data_type",
",",
"value",
"=",
"cell",
".",
"data_type",
",",
"cell",
".",
"value",
"if",
"type",
"(",
"cell",
")",
"is",
"EmptyCell",
":",
"return",
"None",
"elif",
"data_type",
"==",
"\"f\"",
"and",
"... | Convert a PyOpenXL's `Cell` object to the corresponding Python object. | [
"Convert",
"a",
"PyOpenXL",
"s",
"Cell",
"object",
"to",
"the",
"corresponding",
"Python",
"object",
"."
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/plugins/xlsx.py#L32-L55 | train |
turicas/rows | rows/plugins/xlsx.py | import_from_xlsx | def import_from_xlsx(
filename_or_fobj,
sheet_name=None,
sheet_index=0,
start_row=None,
start_column=None,
end_row=None,
end_column=None,
workbook_kwargs=None,
*args,
**kwargs
):
"""Return a rows.Table created from imported XLSX file.
workbook_kwargs will be passed to op... | python | def import_from_xlsx(
filename_or_fobj,
sheet_name=None,
sheet_index=0,
start_row=None,
start_column=None,
end_row=None,
end_column=None,
workbook_kwargs=None,
*args,
**kwargs
):
"""Return a rows.Table created from imported XLSX file.
workbook_kwargs will be passed to op... | [
"def",
"import_from_xlsx",
"(",
"filename_or_fobj",
",",
"sheet_name",
"=",
"None",
",",
"sheet_index",
"=",
"0",
",",
"start_row",
"=",
"None",
",",
"start_column",
"=",
"None",
",",
"end_row",
"=",
"None",
",",
"end_column",
"=",
"None",
",",
"workbook_kwa... | Return a rows.Table created from imported XLSX file.
workbook_kwargs will be passed to openpyxl.load_workbook | [
"Return",
"a",
"rows",
".",
"Table",
"created",
"from",
"imported",
"XLSX",
"file",
"."
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/plugins/xlsx.py#L58-L113 | train |
turicas/rows | rows/plugins/xlsx.py | export_to_xlsx | def export_to_xlsx(table, filename_or_fobj=None, sheet_name="Sheet1", *args, **kwargs):
"""Export the rows.Table to XLSX file and return the saved file."""
workbook = Workbook()
sheet = workbook.active
sheet.title = sheet_name
prepared_table = prepare_to_export(table, *args, **kwargs)
# Write ... | python | def export_to_xlsx(table, filename_or_fobj=None, sheet_name="Sheet1", *args, **kwargs):
"""Export the rows.Table to XLSX file and return the saved file."""
workbook = Workbook()
sheet = workbook.active
sheet.title = sheet_name
prepared_table = prepare_to_export(table, *args, **kwargs)
# Write ... | [
"def",
"export_to_xlsx",
"(",
"table",
",",
"filename_or_fobj",
"=",
"None",
",",
"sheet_name",
"=",
"\"Sheet1\"",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"workbook",
"=",
"Workbook",
"(",
")",
"sheet",
"=",
"workbook",
".",
"active",
"sheet",
"... | Export the rows.Table to XLSX file and return the saved file. | [
"Export",
"the",
"rows",
".",
"Table",
"to",
"XLSX",
"file",
"and",
"return",
"the",
"saved",
"file",
"."
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/plugins/xlsx.py#L152-L193 | train |
turicas/rows | examples/library/organizaciones.py | download_organizations | def download_organizations():
"Download organizations JSON and extract its properties"
response = requests.get(URL)
data = response.json()
organizations = [organization["properties"] for organization in data["features"]]
return rows.import_from_dicts(organizations) | python | def download_organizations():
"Download organizations JSON and extract its properties"
response = requests.get(URL)
data = response.json()
organizations = [organization["properties"] for organization in data["features"]]
return rows.import_from_dicts(organizations) | [
"def",
"download_organizations",
"(",
")",
":",
"\"Download organizations JSON and extract its properties\"",
"response",
"=",
"requests",
".",
"get",
"(",
"URL",
")",
"data",
"=",
"response",
".",
"json",
"(",
")",
"organizations",
"=",
"[",
"organization",
"[",
... | Download organizations JSON and extract its properties | [
"Download",
"organizations",
"JSON",
"and",
"extract",
"its",
"properties"
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/examples/library/organizaciones.py#L15-L21 | train |
turicas/rows | rows/plugins/plugin_html.py | import_from_html | def import_from_html(
filename_or_fobj,
encoding="utf-8",
index=0,
ignore_colspan=True,
preserve_html=False,
properties=False,
table_tag="table",
row_tag="tr",
column_tag="td|th",
*args,
**kwargs
):
"""Return rows.Table from HTML file."""
source = Source.from_file(
... | python | def import_from_html(
filename_or_fobj,
encoding="utf-8",
index=0,
ignore_colspan=True,
preserve_html=False,
properties=False,
table_tag="table",
row_tag="tr",
column_tag="td|th",
*args,
**kwargs
):
"""Return rows.Table from HTML file."""
source = Source.from_file(
... | [
"def",
"import_from_html",
"(",
"filename_or_fobj",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"index",
"=",
"0",
",",
"ignore_colspan",
"=",
"True",
",",
"preserve_html",
"=",
"False",
",",
"properties",
"=",
"False",
",",
"table_tag",
"=",
"\"table\"",
",",
"... | Return rows.Table from HTML file. | [
"Return",
"rows",
".",
"Table",
"from",
"HTML",
"file",
"."
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/plugins/plugin_html.py#L68-L121 | train |
turicas/rows | rows/plugins/plugin_html.py | export_to_html | def export_to_html(
table, filename_or_fobj=None, encoding="utf-8", caption=False, *args, **kwargs
):
"""Export and return rows.Table data to HTML file."""
serialized_table = serialize(table, *args, **kwargs)
fields = next(serialized_table)
result = ["<table>\n\n"]
if caption and table.name:
... | python | def export_to_html(
table, filename_or_fobj=None, encoding="utf-8", caption=False, *args, **kwargs
):
"""Export and return rows.Table data to HTML file."""
serialized_table = serialize(table, *args, **kwargs)
fields = next(serialized_table)
result = ["<table>\n\n"]
if caption and table.name:
... | [
"def",
"export_to_html",
"(",
"table",
",",
"filename_or_fobj",
"=",
"None",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"caption",
"=",
"False",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"serialized_table",
"=",
"serialize",
"(",
"table",
",",
"*",
"... | Export and return rows.Table data to HTML file. | [
"Export",
"and",
"return",
"rows",
".",
"Table",
"data",
"to",
"HTML",
"file",
"."
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/plugins/plugin_html.py#L124-L148 | train |
turicas/rows | rows/plugins/plugin_html.py | _extract_node_text | def _extract_node_text(node):
"""Extract text from a given lxml node."""
texts = map(
six.text_type.strip, map(six.text_type, map(unescape, node.xpath(".//text()")))
)
return " ".join(text for text in texts if text) | python | def _extract_node_text(node):
"""Extract text from a given lxml node."""
texts = map(
six.text_type.strip, map(six.text_type, map(unescape, node.xpath(".//text()")))
)
return " ".join(text for text in texts if text) | [
"def",
"_extract_node_text",
"(",
"node",
")",
":",
"texts",
"=",
"map",
"(",
"six",
".",
"text_type",
".",
"strip",
",",
"map",
"(",
"six",
".",
"text_type",
",",
"map",
"(",
"unescape",
",",
"node",
".",
"xpath",
"(",
"\".//text()\"",
")",
")",
")"... | Extract text from a given lxml node. | [
"Extract",
"text",
"from",
"a",
"given",
"lxml",
"node",
"."
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/plugins/plugin_html.py#L151-L157 | train |
turicas/rows | rows/plugins/plugin_html.py | count_tables | def count_tables(filename_or_fobj, encoding="utf-8", table_tag="table"):
"""Read a file passed by arg and return your table HTML tag count."""
source = Source.from_file(
filename_or_fobj, plugin_name="html", mode="rb", encoding=encoding
)
html = source.fobj.read().decode(source.encoding)
ht... | python | def count_tables(filename_or_fobj, encoding="utf-8", table_tag="table"):
"""Read a file passed by arg and return your table HTML tag count."""
source = Source.from_file(
filename_or_fobj, plugin_name="html", mode="rb", encoding=encoding
)
html = source.fobj.read().decode(source.encoding)
ht... | [
"def",
"count_tables",
"(",
"filename_or_fobj",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"table_tag",
"=",
"\"table\"",
")",
":",
"source",
"=",
"Source",
".",
"from_file",
"(",
"filename_or_fobj",
",",
"plugin_name",
"=",
"\"html\"",
",",
"mode",
"=",
"\"rb\""... | Read a file passed by arg and return your table HTML tag count. | [
"Read",
"a",
"file",
"passed",
"by",
"arg",
"and",
"return",
"your",
"table",
"HTML",
"tag",
"count",
"."
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/plugins/plugin_html.py#L160-L174 | train |
turicas/rows | rows/plugins/plugin_html.py | tag_to_dict | def tag_to_dict(html):
"""Extract tag's attributes into a `dict`."""
element = document_fromstring(html).xpath("//html/body/child::*")[0]
attributes = dict(element.attrib)
attributes["text"] = element.text_content()
return attributes | python | def tag_to_dict(html):
"""Extract tag's attributes into a `dict`."""
element = document_fromstring(html).xpath("//html/body/child::*")[0]
attributes = dict(element.attrib)
attributes["text"] = element.text_content()
return attributes | [
"def",
"tag_to_dict",
"(",
"html",
")",
":",
"element",
"=",
"document_fromstring",
"(",
"html",
")",
".",
"xpath",
"(",
"\"//html/body/child::*\"",
")",
"[",
"0",
"]",
"attributes",
"=",
"dict",
"(",
"element",
".",
"attrib",
")",
"attributes",
"[",
"\"te... | Extract tag's attributes into a `dict`. | [
"Extract",
"tag",
"s",
"attributes",
"into",
"a",
"dict",
"."
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/plugins/plugin_html.py#L177-L183 | train |
turicas/rows | rows/plugins/utils.py | create_table | def create_table(
data,
meta=None,
fields=None,
skip_header=True,
import_fields=None,
samples=None,
force_types=None,
max_rows=None,
*args,
**kwargs
):
"""Create a rows.Table object based on data rows and some configurations
- `skip_header` is only used if `fields` is se... | python | def create_table(
data,
meta=None,
fields=None,
skip_header=True,
import_fields=None,
samples=None,
force_types=None,
max_rows=None,
*args,
**kwargs
):
"""Create a rows.Table object based on data rows and some configurations
- `skip_header` is only used if `fields` is se... | [
"def",
"create_table",
"(",
"data",
",",
"meta",
"=",
"None",
",",
"fields",
"=",
"None",
",",
"skip_header",
"=",
"True",
",",
"import_fields",
"=",
"None",
",",
"samples",
"=",
"None",
",",
"force_types",
"=",
"None",
",",
"max_rows",
"=",
"None",
",... | Create a rows.Table object based on data rows and some configurations
- `skip_header` is only used if `fields` is set
- `samples` is only used if `fields` is `None`. If samples=None, all data
is filled in memory - use with caution.
- `force_types` is only used if `fields` is `None`
- `import_fiel... | [
"Create",
"a",
"rows",
".",
"Table",
"object",
"based",
"on",
"data",
"rows",
"and",
"some",
"configurations"
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/plugins/utils.py#L75-L189 | train |
turicas/rows | rows/plugins/utils.py | export_data | def export_data(filename_or_fobj, data, mode="w"):
"""Return the object ready to be exported or only data if filename_or_fobj is not passed."""
if filename_or_fobj is None:
return data
_, fobj = get_filename_and_fobj(filename_or_fobj, mode=mode)
source = Source.from_file(filename_or_fobj, mode... | python | def export_data(filename_or_fobj, data, mode="w"):
"""Return the object ready to be exported or only data if filename_or_fobj is not passed."""
if filename_or_fobj is None:
return data
_, fobj = get_filename_and_fobj(filename_or_fobj, mode=mode)
source = Source.from_file(filename_or_fobj, mode... | [
"def",
"export_data",
"(",
"filename_or_fobj",
",",
"data",
",",
"mode",
"=",
"\"w\"",
")",
":",
"if",
"filename_or_fobj",
"is",
"None",
":",
"return",
"data",
"_",
",",
"fobj",
"=",
"get_filename_and_fobj",
"(",
"filename_or_fobj",
",",
"mode",
"=",
"mode",... | Return the object ready to be exported or only data if filename_or_fobj is not passed. | [
"Return",
"the",
"object",
"ready",
"to",
"be",
"exported",
"or",
"only",
"data",
"if",
"filename_or_fobj",
"is",
"not",
"passed",
"."
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/plugins/utils.py#L236-L246 | train |
turicas/rows | rows/plugins/plugin_csv.py | read_sample | def read_sample(fobj, sample):
"""Read `sample` bytes from `fobj` and return the cursor to where it was."""
cursor = fobj.tell()
data = fobj.read(sample)
fobj.seek(cursor)
return data | python | def read_sample(fobj, sample):
"""Read `sample` bytes from `fobj` and return the cursor to where it was."""
cursor = fobj.tell()
data = fobj.read(sample)
fobj.seek(cursor)
return data | [
"def",
"read_sample",
"(",
"fobj",
",",
"sample",
")",
":",
"cursor",
"=",
"fobj",
".",
"tell",
"(",
")",
"data",
"=",
"fobj",
".",
"read",
"(",
"sample",
")",
"fobj",
".",
"seek",
"(",
"cursor",
")",
"return",
"data"
] | Read `sample` bytes from `fobj` and return the cursor to where it was. | [
"Read",
"sample",
"bytes",
"from",
"fobj",
"and",
"return",
"the",
"cursor",
"to",
"where",
"it",
"was",
"."
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/plugins/plugin_csv.py#L103-L108 | train |
turicas/rows | rows/plugins/plugin_csv.py | export_to_csv | def export_to_csv(
table,
filename_or_fobj=None,
encoding="utf-8",
dialect=unicodecsv.excel,
batch_size=100,
callback=None,
*args,
**kwargs
):
"""Export a `rows.Table` to a CSV file.
If a file-like object is provided it MUST be in binary mode, like in
`open(filename, mode='... | python | def export_to_csv(
table,
filename_or_fobj=None,
encoding="utf-8",
dialect=unicodecsv.excel,
batch_size=100,
callback=None,
*args,
**kwargs
):
"""Export a `rows.Table` to a CSV file.
If a file-like object is provided it MUST be in binary mode, like in
`open(filename, mode='... | [
"def",
"export_to_csv",
"(",
"table",
",",
"filename_or_fobj",
"=",
"None",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"dialect",
"=",
"unicodecsv",
".",
"excel",
",",
"batch_size",
"=",
"100",
",",
"callback",
"=",
"None",
",",
"*",
"args",
",",
"**",
"kwa... | Export a `rows.Table` to a CSV file.
If a file-like object is provided it MUST be in binary mode, like in
`open(filename, mode='wb')`.
If not filename/fobj is provided, the function returns a string with CSV
contents. | [
"Export",
"a",
"rows",
".",
"Table",
"to",
"a",
"CSV",
"file",
"."
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/plugins/plugin_csv.py#L139-L201 | train |
turicas/rows | rows/operations.py | join | def join(keys, tables):
"""Merge a list of `Table` objects using `keys` to group rows"""
# Make new (merged) Table fields
fields = OrderedDict()
for table in tables:
fields.update(table.fields)
# TODO: may raise an error if a same field is different in some tables
# Check if all keys a... | python | def join(keys, tables):
"""Merge a list of `Table` objects using `keys` to group rows"""
# Make new (merged) Table fields
fields = OrderedDict()
for table in tables:
fields.update(table.fields)
# TODO: may raise an error if a same field is different in some tables
# Check if all keys a... | [
"def",
"join",
"(",
"keys",
",",
"tables",
")",
":",
"fields",
"=",
"OrderedDict",
"(",
")",
"for",
"table",
"in",
"tables",
":",
"fields",
".",
"update",
"(",
"table",
".",
"fields",
")",
"fields_keys",
"=",
"set",
"(",
"fields",
".",
"keys",
"(",
... | Merge a list of `Table` objects using `keys` to group rows | [
"Merge",
"a",
"list",
"of",
"Table",
"objects",
"using",
"keys",
"to",
"group",
"rows"
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/operations.py#L26-L53 | train |
turicas/rows | rows/operations.py | transform | def transform(fields, function, *tables):
"Return a new table based on other tables and a transformation function"
new_table = Table(fields=fields)
for table in tables:
for row in filter(bool, map(lambda row: function(row, table), table)):
new_table.append(row)
return new_table | python | def transform(fields, function, *tables):
"Return a new table based on other tables and a transformation function"
new_table = Table(fields=fields)
for table in tables:
for row in filter(bool, map(lambda row: function(row, table), table)):
new_table.append(row)
return new_table | [
"def",
"transform",
"(",
"fields",
",",
"function",
",",
"*",
"tables",
")",
":",
"\"Return a new table based on other tables and a transformation function\"",
"new_table",
"=",
"Table",
"(",
"fields",
"=",
"fields",
")",
"for",
"table",
"in",
"tables",
":",
"for",
... | Return a new table based on other tables and a transformation function | [
"Return",
"a",
"new",
"table",
"based",
"on",
"other",
"tables",
"and",
"a",
"transformation",
"function"
] | c74da41ae9ed091356b803a64f8a30c641c5fc45 | https://github.com/turicas/rows/blob/c74da41ae9ed091356b803a64f8a30c641c5fc45/rows/operations.py#L56-L65 | train |
jupyterhub/kubespawner | kubespawner/objects.py | make_pvc | def make_pvc(
name,
storage_class,
access_modes,
storage,
labels=None,
annotations=None,
):
"""
Make a k8s pvc specification for running a user notebook.
Parameters
----------
name:
Name of persistent volume claim. Must be unique within the namespace the object is
... | python | def make_pvc(
name,
storage_class,
access_modes,
storage,
labels=None,
annotations=None,
):
"""
Make a k8s pvc specification for running a user notebook.
Parameters
----------
name:
Name of persistent volume claim. Must be unique within the namespace the object is
... | [
"def",
"make_pvc",
"(",
"name",
",",
"storage_class",
",",
"access_modes",
",",
"storage",
",",
"labels",
"=",
"None",
",",
"annotations",
"=",
"None",
",",
")",
":",
"pvc",
"=",
"V1PersistentVolumeClaim",
"(",
")",
"pvc",
".",
"kind",
"=",
"\"PersistentVo... | Make a k8s pvc specification for running a user notebook.
Parameters
----------
name:
Name of persistent volume claim. Must be unique within the namespace the object is
going to be created in. Must be a valid DNS label.
storage_class:
String of the name of the k8s Storage Class ... | [
"Make",
"a",
"k8s",
"pvc",
"specification",
"for",
"running",
"a",
"user",
"notebook",
"."
] | 46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13 | https://github.com/jupyterhub/kubespawner/blob/46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13/kubespawner/objects.py#L393-L433 | train |
jupyterhub/kubespawner | kubespawner/objects.py | make_ingress | def make_ingress(
name,
routespec,
target,
data
):
"""
Returns an ingress, service, endpoint object that'll work for this service
"""
# move beta imports here,
# which are more sensitive to kubernetes version
# and will change when they move out of beta
from ... | python | def make_ingress(
name,
routespec,
target,
data
):
"""
Returns an ingress, service, endpoint object that'll work for this service
"""
# move beta imports here,
# which are more sensitive to kubernetes version
# and will change when they move out of beta
from ... | [
"def",
"make_ingress",
"(",
"name",
",",
"routespec",
",",
"target",
",",
"data",
")",
":",
"from",
"kubernetes",
".",
"client",
".",
"models",
"import",
"(",
"V1beta1Ingress",
",",
"V1beta1IngressSpec",
",",
"V1beta1IngressRule",
",",
"V1beta1HTTPIngressRuleValue... | Returns an ingress, service, endpoint object that'll work for this service | [
"Returns",
"an",
"ingress",
"service",
"endpoint",
"object",
"that",
"ll",
"work",
"for",
"this",
"service"
] | 46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13 | https://github.com/jupyterhub/kubespawner/blob/46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13/kubespawner/objects.py#L435-L541 | train |
jupyterhub/kubespawner | kubespawner/clients.py | shared_client | def shared_client(ClientType, *args, **kwargs):
"""Return a single shared kubernetes client instance
A weak reference to the instance is cached,
so that concurrent calls to shared_client
will all return the same instance until
all references to the client are cleared.
"""
kwarg_key = tuple(... | python | def shared_client(ClientType, *args, **kwargs):
"""Return a single shared kubernetes client instance
A weak reference to the instance is cached,
so that concurrent calls to shared_client
will all return the same instance until
all references to the client are cleared.
"""
kwarg_key = tuple(... | [
"def",
"shared_client",
"(",
"ClientType",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"kwarg_key",
"=",
"tuple",
"(",
"(",
"key",
",",
"kwargs",
"[",
"key",
"]",
")",
"for",
"key",
"in",
"sorted",
"(",
"kwargs",
")",
")",
"cache_key",
"=",
"(... | Return a single shared kubernetes client instance
A weak reference to the instance is cached,
so that concurrent calls to shared_client
will all return the same instance until
all references to the client are cleared. | [
"Return",
"a",
"single",
"shared",
"kubernetes",
"client",
"instance"
] | 46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13 | https://github.com/jupyterhub/kubespawner/blob/46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13/kubespawner/clients.py#L25-L46 | train |
jupyterhub/kubespawner | kubespawner/utils.py | generate_hashed_slug | def generate_hashed_slug(slug, limit=63, hash_length=6):
"""
Generate a unique name that's within a certain length limit
Most k8s objects have a 63 char name limit. We wanna be able to compress
larger names down to that if required, while still maintaining some
amount of legibility about what the o... | python | def generate_hashed_slug(slug, limit=63, hash_length=6):
"""
Generate a unique name that's within a certain length limit
Most k8s objects have a 63 char name limit. We wanna be able to compress
larger names down to that if required, while still maintaining some
amount of legibility about what the o... | [
"def",
"generate_hashed_slug",
"(",
"slug",
",",
"limit",
"=",
"63",
",",
"hash_length",
"=",
"6",
")",
":",
"if",
"len",
"(",
"slug",
")",
"<",
"(",
"limit",
"-",
"hash_length",
")",
":",
"return",
"slug",
"slug_hash",
"=",
"hashlib",
".",
"sha256",
... | Generate a unique name that's within a certain length limit
Most k8s objects have a 63 char name limit. We wanna be able to compress
larger names down to that if required, while still maintaining some
amount of legibility about what the objects really are.
If the length of the slug is shorter than the... | [
"Generate",
"a",
"unique",
"name",
"that",
"s",
"within",
"a",
"certain",
"length",
"limit"
] | 46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13 | https://github.com/jupyterhub/kubespawner/blob/46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13/kubespawner/utils.py#L7-L29 | train |
jupyterhub/kubespawner | kubespawner/utils.py | get_k8s_model | def get_k8s_model(model_type, model_dict):
"""
Returns an instance of type specified model_type from an model instance or
represantative dictionary.
"""
model_dict = copy.deepcopy(model_dict)
if isinstance(model_dict, model_type):
return model_dict
elif isinstance(model_dict, dict):... | python | def get_k8s_model(model_type, model_dict):
"""
Returns an instance of type specified model_type from an model instance or
represantative dictionary.
"""
model_dict = copy.deepcopy(model_dict)
if isinstance(model_dict, model_type):
return model_dict
elif isinstance(model_dict, dict):... | [
"def",
"get_k8s_model",
"(",
"model_type",
",",
"model_dict",
")",
":",
"model_dict",
"=",
"copy",
".",
"deepcopy",
"(",
"model_dict",
")",
"if",
"isinstance",
"(",
"model_dict",
",",
"model_type",
")",
":",
"return",
"model_dict",
"elif",
"isinstance",
"(",
... | Returns an instance of type specified model_type from an model instance or
represantative dictionary. | [
"Returns",
"an",
"instance",
"of",
"type",
"specified",
"model_type",
"from",
"an",
"model",
"instance",
"or",
"represantative",
"dictionary",
"."
] | 46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13 | https://github.com/jupyterhub/kubespawner/blob/46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13/kubespawner/utils.py#L75-L90 | train |
jupyterhub/kubespawner | kubespawner/utils.py | _get_k8s_model_dict | def _get_k8s_model_dict(model_type, model):
"""
Returns a dictionary representation of a provided model type
"""
model = copy.deepcopy(model)
if isinstance(model, model_type):
return model.to_dict()
elif isinstance(model, dict):
return _map_dict_keys_to_model_attributes(model_ty... | python | def _get_k8s_model_dict(model_type, model):
"""
Returns a dictionary representation of a provided model type
"""
model = copy.deepcopy(model)
if isinstance(model, model_type):
return model.to_dict()
elif isinstance(model, dict):
return _map_dict_keys_to_model_attributes(model_ty... | [
"def",
"_get_k8s_model_dict",
"(",
"model_type",
",",
"model",
")",
":",
"model",
"=",
"copy",
".",
"deepcopy",
"(",
"model",
")",
"if",
"isinstance",
"(",
"model",
",",
"model_type",
")",
":",
"return",
"model",
".",
"to_dict",
"(",
")",
"elif",
"isinst... | Returns a dictionary representation of a provided model type | [
"Returns",
"a",
"dictionary",
"representation",
"of",
"a",
"provided",
"model",
"type"
] | 46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13 | https://github.com/jupyterhub/kubespawner/blob/46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13/kubespawner/utils.py#L92-L103 | train |
jupyterhub/kubespawner | kubespawner/reflector.py | NamespacedResourceReflector._list_and_update | def _list_and_update(self):
"""
Update current list of resources by doing a full fetch.
Overwrites all current resource info.
"""
initial_resources = getattr(self.api, self.list_method_name)(
self.namespace,
label_selector=self.label_selector,
... | python | def _list_and_update(self):
"""
Update current list of resources by doing a full fetch.
Overwrites all current resource info.
"""
initial_resources = getattr(self.api, self.list_method_name)(
self.namespace,
label_selector=self.label_selector,
... | [
"def",
"_list_and_update",
"(",
"self",
")",
":",
"initial_resources",
"=",
"getattr",
"(",
"self",
".",
"api",
",",
"self",
".",
"list_method_name",
")",
"(",
"self",
".",
"namespace",
",",
"label_selector",
"=",
"self",
".",
"label_selector",
",",
"field_s... | Update current list of resources by doing a full fetch.
Overwrites all current resource info. | [
"Update",
"current",
"list",
"of",
"resources",
"by",
"doing",
"a",
"full",
"fetch",
"."
] | 46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13 | https://github.com/jupyterhub/kubespawner/blob/46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13/kubespawner/reflector.py#L147-L162 | train |
jupyterhub/kubespawner | kubespawner/reflector.py | NamespacedResourceReflector._watch_and_update | def _watch_and_update(self):
"""
Keeps the current list of resources up-to-date
This method is to be run not on the main thread!
We first fetch the list of current resources, and store that. Then we
register to be notified of changes to those resources, and keep our
loc... | python | def _watch_and_update(self):
"""
Keeps the current list of resources up-to-date
This method is to be run not on the main thread!
We first fetch the list of current resources, and store that. Then we
register to be notified of changes to those resources, and keep our
loc... | [
"def",
"_watch_and_update",
"(",
"self",
")",
":",
"selectors",
"=",
"[",
"]",
"log_name",
"=",
"\"\"",
"if",
"self",
".",
"label_selector",
":",
"selectors",
".",
"append",
"(",
"\"label selector=%r\"",
"%",
"self",
".",
"label_selector",
")",
"if",
"self",... | Keeps the current list of resources up-to-date
This method is to be run not on the main thread!
We first fetch the list of current resources, and store that. Then we
register to be notified of changes to those resources, and keep our
local store up-to-date based on these notifications.... | [
"Keeps",
"the",
"current",
"list",
"of",
"resources",
"up",
"-",
"to",
"-",
"date"
] | 46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13 | https://github.com/jupyterhub/kubespawner/blob/46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13/kubespawner/reflector.py#L164-L269 | train |
jupyterhub/kubespawner | kubespawner/reflector.py | NamespacedResourceReflector.start | def start(self):
"""
Start the reflection process!
We'll do a blocking read of all resources first, so that we don't
race with any operations that are checking the state of the pod
store - such as polls. This should be called only once at the
start of program initializat... | python | def start(self):
"""
Start the reflection process!
We'll do a blocking read of all resources first, so that we don't
race with any operations that are checking the state of the pod
store - such as polls. This should be called only once at the
start of program initializat... | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'watch_thread'",
")",
":",
"raise",
"ValueError",
"(",
"'Thread watching for resources is already running'",
")",
"self",
".",
"_list_and_update",
"(",
")",
"self",
".",
"watch_thread",
"... | Start the reflection process!
We'll do a blocking read of all resources first, so that we don't
race with any operations that are checking the state of the pod
store - such as polls. This should be called only once at the
start of program initialization (when the singleton is being crea... | [
"Start",
"the",
"reflection",
"process!"
] | 46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13 | https://github.com/jupyterhub/kubespawner/blob/46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13/kubespawner/reflector.py#L271-L288 | train |
jupyterhub/kubespawner | kubespawner/spawner.py | KubeSpawner.get_pod_manifest | def get_pod_manifest(self):
"""
Make a pod manifest that will spawn current user's notebook pod.
"""
if callable(self.uid):
uid = yield gen.maybe_future(self.uid(self))
else:
uid = self.uid
if callable(self.gid):
gid = yield gen.maybe_... | python | def get_pod_manifest(self):
"""
Make a pod manifest that will spawn current user's notebook pod.
"""
if callable(self.uid):
uid = yield gen.maybe_future(self.uid(self))
else:
uid = self.uid
if callable(self.gid):
gid = yield gen.maybe_... | [
"def",
"get_pod_manifest",
"(",
"self",
")",
":",
"if",
"callable",
"(",
"self",
".",
"uid",
")",
":",
"uid",
"=",
"yield",
"gen",
".",
"maybe_future",
"(",
"self",
".",
"uid",
"(",
"self",
")",
")",
"else",
":",
"uid",
"=",
"self",
".",
"uid",
"... | Make a pod manifest that will spawn current user's notebook pod. | [
"Make",
"a",
"pod",
"manifest",
"that",
"will",
"spawn",
"current",
"user",
"s",
"notebook",
"pod",
"."
] | 46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13 | https://github.com/jupyterhub/kubespawner/blob/46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13/kubespawner/spawner.py#L1303-L1376 | train |
jupyterhub/kubespawner | kubespawner/spawner.py | KubeSpawner.get_pvc_manifest | def get_pvc_manifest(self):
"""
Make a pvc manifest that will spawn current user's pvc.
"""
labels = self._build_common_labels(self._expand_all(self.storage_extra_labels))
labels.update({
'component': 'singleuser-storage'
})
annotations = self._build_... | python | def get_pvc_manifest(self):
"""
Make a pvc manifest that will spawn current user's pvc.
"""
labels = self._build_common_labels(self._expand_all(self.storage_extra_labels))
labels.update({
'component': 'singleuser-storage'
})
annotations = self._build_... | [
"def",
"get_pvc_manifest",
"(",
"self",
")",
":",
"labels",
"=",
"self",
".",
"_build_common_labels",
"(",
"self",
".",
"_expand_all",
"(",
"self",
".",
"storage_extra_labels",
")",
")",
"labels",
".",
"update",
"(",
"{",
"'component'",
":",
"'singleuser-stora... | Make a pvc manifest that will spawn current user's pvc. | [
"Make",
"a",
"pvc",
"manifest",
"that",
"will",
"spawn",
"current",
"user",
"s",
"pvc",
"."
] | 46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13 | https://github.com/jupyterhub/kubespawner/blob/46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13/kubespawner/spawner.py#L1378-L1396 | train |
jupyterhub/kubespawner | kubespawner/spawner.py | KubeSpawner.is_pod_running | def is_pod_running(self, pod):
"""
Check if the given pod is running
pod must be a dictionary representing a Pod kubernetes API object.
"""
# FIXME: Validate if this is really the best way
is_running = (
pod is not None and
pod.status.phase == 'Ru... | python | def is_pod_running(self, pod):
"""
Check if the given pod is running
pod must be a dictionary representing a Pod kubernetes API object.
"""
# FIXME: Validate if this is really the best way
is_running = (
pod is not None and
pod.status.phase == 'Ru... | [
"def",
"is_pod_running",
"(",
"self",
",",
"pod",
")",
":",
"is_running",
"=",
"(",
"pod",
"is",
"not",
"None",
"and",
"pod",
".",
"status",
".",
"phase",
"==",
"'Running'",
"and",
"pod",
".",
"status",
".",
"pod_ip",
"is",
"not",
"None",
"and",
"pod... | Check if the given pod is running
pod must be a dictionary representing a Pod kubernetes API object. | [
"Check",
"if",
"the",
"given",
"pod",
"is",
"running"
] | 46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13 | https://github.com/jupyterhub/kubespawner/blob/46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13/kubespawner/spawner.py#L1398-L1412 | train |
jupyterhub/kubespawner | kubespawner/spawner.py | KubeSpawner.get_env | def get_env(self):
"""Return the environment dict to use for the Spawner.
See also: jupyterhub.Spawner.get_env
"""
env = super(KubeSpawner, self).get_env()
# deprecate image
env['JUPYTER_IMAGE_SPEC'] = self.image
env['JUPYTER_IMAGE'] = self.image
return... | python | def get_env(self):
"""Return the environment dict to use for the Spawner.
See also: jupyterhub.Spawner.get_env
"""
env = super(KubeSpawner, self).get_env()
# deprecate image
env['JUPYTER_IMAGE_SPEC'] = self.image
env['JUPYTER_IMAGE'] = self.image
return... | [
"def",
"get_env",
"(",
"self",
")",
":",
"env",
"=",
"super",
"(",
"KubeSpawner",
",",
"self",
")",
".",
"get_env",
"(",
")",
"env",
"[",
"'JUPYTER_IMAGE_SPEC'",
"]",
"=",
"self",
".",
"image",
"env",
"[",
"'JUPYTER_IMAGE'",
"]",
"=",
"self",
".",
"i... | Return the environment dict to use for the Spawner.
See also: jupyterhub.Spawner.get_env | [
"Return",
"the",
"environment",
"dict",
"to",
"use",
"for",
"the",
"Spawner",
"."
] | 46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13 | https://github.com/jupyterhub/kubespawner/blob/46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13/kubespawner/spawner.py#L1429-L1440 | train |
jupyterhub/kubespawner | kubespawner/spawner.py | KubeSpawner.poll | def poll(self):
"""
Check if the pod is still running.
Uses the same interface as subprocess.Popen.poll(): if the pod is
still running, returns None. If the pod has exited, return the
exit code if we can determine it, or 1 if it has exited but we
don't know how. These ... | python | def poll(self):
"""
Check if the pod is still running.
Uses the same interface as subprocess.Popen.poll(): if the pod is
still running, returns None. If the pod has exited, return the
exit code if we can determine it, or 1 if it has exited but we
don't know how. These ... | [
"def",
"poll",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"pod_reflector",
".",
"first_load_future",
".",
"done",
"(",
")",
":",
"yield",
"self",
".",
"pod_reflector",
".",
"first_load_future",
"data",
"=",
"self",
".",
"pod_reflector",
".",
"pods",
... | Check if the pod is still running.
Uses the same interface as subprocess.Popen.poll(): if the pod is
still running, returns None. If the pod has exited, return the
exit code if we can determine it, or 1 if it has exited but we
don't know how. These are the return values JupyterHub exp... | [
"Check",
"if",
"the",
"pod",
"is",
"still",
"running",
"."
] | 46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13 | https://github.com/jupyterhub/kubespawner/blob/46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13/kubespawner/spawner.py#L1456-L1492 | train |
jupyterhub/kubespawner | kubespawner/spawner.py | KubeSpawner.events | def events(self):
"""Filter event-reflector to just our events
Returns list of all events that match our pod_name
since our ._last_event (if defined).
._last_event is set at the beginning of .start().
"""
if not self.event_reflector:
return []
events... | python | def events(self):
"""Filter event-reflector to just our events
Returns list of all events that match our pod_name
since our ._last_event (if defined).
._last_event is set at the beginning of .start().
"""
if not self.event_reflector:
return []
events... | [
"def",
"events",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"event_reflector",
":",
"return",
"[",
"]",
"events",
"=",
"[",
"]",
"for",
"event",
"in",
"self",
".",
"event_reflector",
".",
"events",
":",
"if",
"event",
".",
"involved_object",
".",... | Filter event-reflector to just our events
Returns list of all events that match our pod_name
since our ._last_event (if defined).
._last_event is set at the beginning of .start(). | [
"Filter",
"event",
"-",
"reflector",
"to",
"just",
"our",
"events"
] | 46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13 | https://github.com/jupyterhub/kubespawner/blob/46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13/kubespawner/spawner.py#L1499-L1522 | train |
jupyterhub/kubespawner | kubespawner/spawner.py | KubeSpawner._start_reflector | def _start_reflector(self, key, ReflectorClass, replace=False, **kwargs):
"""Start a shared reflector on the KubeSpawner class
key: key for the reflector (e.g. 'pod' or 'events')
Reflector: Reflector class to be instantiated
kwargs: extra keyword-args to be relayed to ReflectorClass
... | python | def _start_reflector(self, key, ReflectorClass, replace=False, **kwargs):
"""Start a shared reflector on the KubeSpawner class
key: key for the reflector (e.g. 'pod' or 'events')
Reflector: Reflector class to be instantiated
kwargs: extra keyword-args to be relayed to ReflectorClass
... | [
"def",
"_start_reflector",
"(",
"self",
",",
"key",
",",
"ReflectorClass",
",",
"replace",
"=",
"False",
",",
"**",
"kwargs",
")",
":",
"main_loop",
"=",
"IOLoop",
".",
"current",
"(",
")",
"def",
"on_reflector_failure",
"(",
")",
":",
"self",
".",
"log"... | Start a shared reflector on the KubeSpawner class
key: key for the reflector (e.g. 'pod' or 'events')
Reflector: Reflector class to be instantiated
kwargs: extra keyword-args to be relayed to ReflectorClass
If replace=False and the pod reflector is already running,
do nothing.... | [
"Start",
"a",
"shared",
"reflector",
"on",
"the",
"KubeSpawner",
"class"
] | 46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13 | https://github.com/jupyterhub/kubespawner/blob/46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13/kubespawner/spawner.py#L1566-L1603 | train |
jupyterhub/kubespawner | kubespawner/spawner.py | KubeSpawner._start_watching_events | def _start_watching_events(self, replace=False):
"""Start the events reflector
If replace=False and the event reflector is already running,
do nothing.
If replace=True, a running pod reflector will be stopped
and a new one started (for recovering from possible errors).
... | python | def _start_watching_events(self, replace=False):
"""Start the events reflector
If replace=False and the event reflector is already running,
do nothing.
If replace=True, a running pod reflector will be stopped
and a new one started (for recovering from possible errors).
... | [
"def",
"_start_watching_events",
"(",
"self",
",",
"replace",
"=",
"False",
")",
":",
"return",
"self",
".",
"_start_reflector",
"(",
"\"events\"",
",",
"EventReflector",
",",
"fields",
"=",
"{",
"\"involvedObject.kind\"",
":",
"\"Pod\"",
"}",
",",
"replace",
... | Start the events reflector
If replace=False and the event reflector is already running,
do nothing.
If replace=True, a running pod reflector will be stopped
and a new one started (for recovering from possible errors). | [
"Start",
"the",
"events",
"reflector"
] | 46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13 | https://github.com/jupyterhub/kubespawner/blob/46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13/kubespawner/spawner.py#L1606-L1620 | train |
jupyterhub/kubespawner | kubespawner/spawner.py | KubeSpawner._options_form_default | def _options_form_default(self):
'''
Build the form template according to the `profile_list` setting.
Returns:
'' when no `profile_list` has been defined
The rendered template (using jinja2) when `profile_list` is defined.
'''
if not self.profile_list:
... | python | def _options_form_default(self):
'''
Build the form template according to the `profile_list` setting.
Returns:
'' when no `profile_list` has been defined
The rendered template (using jinja2) when `profile_list` is defined.
'''
if not self.profile_list:
... | [
"def",
"_options_form_default",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"profile_list",
":",
"return",
"''",
"if",
"callable",
"(",
"self",
".",
"profile_list",
")",
":",
"return",
"self",
".",
"_render_options_form_dynamically",
"else",
":",
"return"... | Build the form template according to the `profile_list` setting.
Returns:
'' when no `profile_list` has been defined
The rendered template (using jinja2) when `profile_list` is defined. | [
"Build",
"the",
"form",
"template",
"according",
"to",
"the",
"profile_list",
"setting",
"."
] | 46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13 | https://github.com/jupyterhub/kubespawner/blob/46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13/kubespawner/spawner.py#L1824-L1837 | train |
jupyterhub/kubespawner | kubespawner/spawner.py | KubeSpawner.options_from_form | def options_from_form(self, formdata):
"""get the option selected by the user on the form
This only constructs the user_options dict,
it should not actually load any options.
That is done later in `.load_user_options()`
Args:
formdata: user selection returned by the... | python | def options_from_form(self, formdata):
"""get the option selected by the user on the form
This only constructs the user_options dict,
it should not actually load any options.
That is done later in `.load_user_options()`
Args:
formdata: user selection returned by the... | [
"def",
"options_from_form",
"(",
"self",
",",
"formdata",
")",
":",
"if",
"not",
"self",
".",
"profile_list",
"or",
"self",
".",
"_profile_list",
"is",
"None",
":",
"return",
"formdata",
"try",
":",
"selected_profile",
"=",
"int",
"(",
"formdata",
".",
"ge... | get the option selected by the user on the form
This only constructs the user_options dict,
it should not actually load any options.
That is done later in `.load_user_options()`
Args:
formdata: user selection returned by the form
To access to the value, you can use... | [
"get",
"the",
"option",
"selected",
"by",
"the",
"user",
"on",
"the",
"form"
] | 46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13 | https://github.com/jupyterhub/kubespawner/blob/46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13/kubespawner/spawner.py#L1839-L1873 | train |
jupyterhub/kubespawner | kubespawner/spawner.py | KubeSpawner._load_profile | def _load_profile(self, profile_name):
"""Load a profile by name
Called by load_user_options
"""
# find the profile
default_profile = self._profile_list[0]
for profile in self._profile_list:
if profile.get('default', False):
# explicit defaul... | python | def _load_profile(self, profile_name):
"""Load a profile by name
Called by load_user_options
"""
# find the profile
default_profile = self._profile_list[0]
for profile in self._profile_list:
if profile.get('default', False):
# explicit defaul... | [
"def",
"_load_profile",
"(",
"self",
",",
"profile_name",
")",
":",
"default_profile",
"=",
"self",
".",
"_profile_list",
"[",
"0",
"]",
"for",
"profile",
"in",
"self",
".",
"_profile_list",
":",
"if",
"profile",
".",
"get",
"(",
"'default'",
",",
"False",... | Load a profile by name
Called by load_user_options | [
"Load",
"a",
"profile",
"by",
"name"
] | 46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13 | https://github.com/jupyterhub/kubespawner/blob/46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13/kubespawner/spawner.py#L1876-L1909 | train |
jupyterhub/kubespawner | kubespawner/spawner.py | KubeSpawner.load_user_options | def load_user_options(self):
"""Load user options from self.user_options dict
This can be set via POST to the API or via options_from_form
Only supported argument by default is 'profile'.
Override in subclasses to support other options.
"""
if self._profile_list is None... | python | def load_user_options(self):
"""Load user options from self.user_options dict
This can be set via POST to the API or via options_from_form
Only supported argument by default is 'profile'.
Override in subclasses to support other options.
"""
if self._profile_list is None... | [
"def",
"load_user_options",
"(",
"self",
")",
":",
"if",
"self",
".",
"_profile_list",
"is",
"None",
":",
"if",
"callable",
"(",
"self",
".",
"profile_list",
")",
":",
"self",
".",
"_profile_list",
"=",
"yield",
"gen",
".",
"maybe_future",
"(",
"self",
"... | Load user options from self.user_options dict
This can be set via POST to the API or via options_from_form
Only supported argument by default is 'profile'.
Override in subclasses to support other options. | [
"Load",
"user",
"options",
"from",
"self",
".",
"user_options",
"dict"
] | 46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13 | https://github.com/jupyterhub/kubespawner/blob/46a4b109c5e657a4c3d5bfa8ea4731ec6564ea13/kubespawner/spawner.py#L1912-L1926 | train |
ev3dev/ev3dev-lang-python | ev3dev2/motor.py | list_motors | def list_motors(name_pattern=Motor.SYSTEM_DEVICE_NAME_CONVENTION, **kwargs):
"""
This is a generator function that enumerates all tacho motors that match
the provided arguments.
Parameters:
name_pattern: pattern that device name should match.
For example, 'motor*'. Default value: '*... | python | def list_motors(name_pattern=Motor.SYSTEM_DEVICE_NAME_CONVENTION, **kwargs):
"""
This is a generator function that enumerates all tacho motors that match
the provided arguments.
Parameters:
name_pattern: pattern that device name should match.
For example, 'motor*'. Default value: '*... | [
"def",
"list_motors",
"(",
"name_pattern",
"=",
"Motor",
".",
"SYSTEM_DEVICE_NAME_CONVENTION",
",",
"**",
"kwargs",
")",
":",
"class_path",
"=",
"abspath",
"(",
"Device",
".",
"DEVICE_ROOT_PATH",
"+",
"'/'",
"+",
"Motor",
".",
"SYSTEM_CLASS_NAME",
")",
"return",... | This is a generator function that enumerates all tacho motors that match
the provided arguments.
Parameters:
name_pattern: pattern that device name should match.
For example, 'motor*'. Default value: '*'.
keyword arguments: used for matching the corresponding device
attr... | [
"This",
"is",
"a",
"generator",
"function",
"that",
"enumerates",
"all",
"tacho",
"motors",
"that",
"match",
"the",
"provided",
"arguments",
"."
] | afc98d35004b533dc161a01f7c966e78607d7c1e | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/motor.py#L1060-L1077 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.