repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
mgaitan/waliki | waliki/templatetags/waliki_tags.py | entry_point | def entry_point(context, block_name):
"""include an snippet at the bottom of a block, if it exists
For example, if the plugin with slug 'attachments' is registered
waliki/attachments_edit_content.html will be included with
{% entry_point 'edit_content' %}
which is declared at the bottom of the block 'content' in edit.html
"""
from waliki.plugins import get_plugins
includes = []
for plugin in get_plugins():
template_name = 'waliki/%s_%s.html' % (plugin.slug, block_name)
try:
# template exists
template.loader.get_template(template_name)
includes.append(template_name)
except template.TemplateDoesNotExist:
continue
context.update({'includes': includes})
return context | python | def entry_point(context, block_name):
"""include an snippet at the bottom of a block, if it exists
For example, if the plugin with slug 'attachments' is registered
waliki/attachments_edit_content.html will be included with
{% entry_point 'edit_content' %}
which is declared at the bottom of the block 'content' in edit.html
"""
from waliki.plugins import get_plugins
includes = []
for plugin in get_plugins():
template_name = 'waliki/%s_%s.html' % (plugin.slug, block_name)
try:
# template exists
template.loader.get_template(template_name)
includes.append(template_name)
except template.TemplateDoesNotExist:
continue
context.update({'includes': includes})
return context | [
"def",
"entry_point",
"(",
"context",
",",
"block_name",
")",
":",
"from",
"waliki",
".",
"plugins",
"import",
"get_plugins",
"includes",
"=",
"[",
"]",
"for",
"plugin",
"in",
"get_plugins",
"(",
")",
":",
"template_name",
"=",
"'waliki/%s_%s.html'",
"%",
"(... | include an snippet at the bottom of a block, if it exists
For example, if the plugin with slug 'attachments' is registered
waliki/attachments_edit_content.html will be included with
{% entry_point 'edit_content' %}
which is declared at the bottom of the block 'content' in edit.html | [
"include",
"an",
"snippet",
"at",
"the",
"bottom",
"of",
"a",
"block",
"if",
"it",
"exists"
] | 5baaf6f043275920a1174ff233726f7ff4bfb5cf | https://github.com/mgaitan/waliki/blob/5baaf6f043275920a1174ff233726f7ff4bfb5cf/waliki/templatetags/waliki_tags.py#L30-L52 | train | 37,200 |
mgaitan/waliki | waliki/templatetags/waliki_tags.py | waliki_box | def waliki_box(context, slug, show_edit=True, *args, **kwargs):
"""
A templatetag to render a wiki page content as a box in any webpage,
and allow rapid edition if you have permission.
It's inspired in `django-boxes`_
.. _django-boxes: https://github.com/eldarion/django-boxes
"""
request = context["request"]
try:
page = Page.objects.get(slug=slug)
except Page.DoesNotExist:
page = None
if (page and check_perms_helper('change_page', request.user, slug)
or (not page and check_perms_helper('add_page', request.user, slug))):
form = PageForm(instance=page, initial={'slug': slug})
form_action = reverse("waliki_edit", args=[slug])
else:
form = None
form_action = None
return {
"request": request,
"slug": slug,
"label": slug.replace('/', '_'),
"page": page,
"form": form,
"form_action": form_action,
} | python | def waliki_box(context, slug, show_edit=True, *args, **kwargs):
"""
A templatetag to render a wiki page content as a box in any webpage,
and allow rapid edition if you have permission.
It's inspired in `django-boxes`_
.. _django-boxes: https://github.com/eldarion/django-boxes
"""
request = context["request"]
try:
page = Page.objects.get(slug=slug)
except Page.DoesNotExist:
page = None
if (page and check_perms_helper('change_page', request.user, slug)
or (not page and check_perms_helper('add_page', request.user, slug))):
form = PageForm(instance=page, initial={'slug': slug})
form_action = reverse("waliki_edit", args=[slug])
else:
form = None
form_action = None
return {
"request": request,
"slug": slug,
"label": slug.replace('/', '_'),
"page": page,
"form": form,
"form_action": form_action,
} | [
"def",
"waliki_box",
"(",
"context",
",",
"slug",
",",
"show_edit",
"=",
"True",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"request",
"=",
"context",
"[",
"\"request\"",
"]",
"try",
":",
"page",
"=",
"Page",
".",
"objects",
".",
"get",
"... | A templatetag to render a wiki page content as a box in any webpage,
and allow rapid edition if you have permission.
It's inspired in `django-boxes`_
.. _django-boxes: https://github.com/eldarion/django-boxes | [
"A",
"templatetag",
"to",
"render",
"a",
"wiki",
"page",
"content",
"as",
"a",
"box",
"in",
"any",
"webpage",
"and",
"allow",
"rapid",
"edition",
"if",
"you",
"have",
"permission",
"."
] | 5baaf6f043275920a1174ff233726f7ff4bfb5cf | https://github.com/mgaitan/waliki/blob/5baaf6f043275920a1174ff233726f7ff4bfb5cf/waliki/templatetags/waliki_tags.py#L138-L169 | train | 37,201 |
mgaitan/waliki | waliki/acl.py | check_perms | def check_perms(perms, user, slug, raise_exception=False):
"""a helper user to check if a user has the permissions
for a given slug"""
if isinstance(perms, string_types):
perms = {perms}
else:
perms = set(perms)
allowed_users = ACLRule.get_users_for(perms, slug)
if allowed_users:
return user in allowed_users
if perms.issubset(set(WALIKI_ANONYMOUS_USER_PERMISSIONS)):
return True
if is_authenticated(user) and perms.issubset(set(WALIKI_LOGGED_USER_PERMISSIONS)):
return True
# First check if the user has the permission (even anon users)
if user.has_perms(['waliki.%s' % p for p in perms]):
return True
# In case the 403 handler should be called raise the exception
if raise_exception:
raise PermissionDenied
# As the last resort, show the login form
return False | python | def check_perms(perms, user, slug, raise_exception=False):
"""a helper user to check if a user has the permissions
for a given slug"""
if isinstance(perms, string_types):
perms = {perms}
else:
perms = set(perms)
allowed_users = ACLRule.get_users_for(perms, slug)
if allowed_users:
return user in allowed_users
if perms.issubset(set(WALIKI_ANONYMOUS_USER_PERMISSIONS)):
return True
if is_authenticated(user) and perms.issubset(set(WALIKI_LOGGED_USER_PERMISSIONS)):
return True
# First check if the user has the permission (even anon users)
if user.has_perms(['waliki.%s' % p for p in perms]):
return True
# In case the 403 handler should be called raise the exception
if raise_exception:
raise PermissionDenied
# As the last resort, show the login form
return False | [
"def",
"check_perms",
"(",
"perms",
",",
"user",
",",
"slug",
",",
"raise_exception",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"perms",
",",
"string_types",
")",
":",
"perms",
"=",
"{",
"perms",
"}",
"else",
":",
"perms",
"=",
"set",
"(",
"pe... | a helper user to check if a user has the permissions
for a given slug | [
"a",
"helper",
"user",
"to",
"check",
"if",
"a",
"user",
"has",
"the",
"permissions",
"for",
"a",
"given",
"slug"
] | 5baaf6f043275920a1174ff233726f7ff4bfb5cf | https://github.com/mgaitan/waliki/blob/5baaf6f043275920a1174ff233726f7ff4bfb5cf/waliki/acl.py#L19-L45 | train | 37,202 |
mgaitan/waliki | waliki/acl.py | permission_required | def permission_required(perms, login_url=None, raise_exception=False, redirect_field_name=REDIRECT_FIELD_NAME):
"""
this is analog to django's builtin ``permission_required`` decorator, but
improved to check per slug ACLRules and default permissions for
anonymous and logged in users
if there is a rule affecting a slug, the user needs to be part of the
rule's allowed users. If there isn't a matching rule, defaults permissions
apply.
"""
def decorator(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
if check_perms(perms, request.user, kwargs['slug'], raise_exception=raise_exception):
return view_func(request, *args, **kwargs)
if is_authenticated(request.user):
if WALIKI_RENDER_403:
return render(request, 'waliki/403.html', kwargs, status=403)
else:
raise PermissionDenied
path = request.build_absolute_uri()
# urlparse chokes on lazy objects in Python 3, force to str
resolved_login_url = force_str(
resolve_url(login_url or settings.LOGIN_URL))
# If the login url is the same scheme and net location then just
# use the path as the "next" url.
login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
current_scheme, current_netloc = urlparse(path)[:2]
if ((not login_scheme or login_scheme == current_scheme) and
(not login_netloc or login_netloc == current_netloc)):
path = request.get_full_path()
from django.contrib.auth.views import redirect_to_login
return redirect_to_login(
path, resolved_login_url, redirect_field_name)
return _wrapped_view
return decorator | python | def permission_required(perms, login_url=None, raise_exception=False, redirect_field_name=REDIRECT_FIELD_NAME):
"""
this is analog to django's builtin ``permission_required`` decorator, but
improved to check per slug ACLRules and default permissions for
anonymous and logged in users
if there is a rule affecting a slug, the user needs to be part of the
rule's allowed users. If there isn't a matching rule, defaults permissions
apply.
"""
def decorator(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
if check_perms(perms, request.user, kwargs['slug'], raise_exception=raise_exception):
return view_func(request, *args, **kwargs)
if is_authenticated(request.user):
if WALIKI_RENDER_403:
return render(request, 'waliki/403.html', kwargs, status=403)
else:
raise PermissionDenied
path = request.build_absolute_uri()
# urlparse chokes on lazy objects in Python 3, force to str
resolved_login_url = force_str(
resolve_url(login_url or settings.LOGIN_URL))
# If the login url is the same scheme and net location then just
# use the path as the "next" url.
login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
current_scheme, current_netloc = urlparse(path)[:2]
if ((not login_scheme or login_scheme == current_scheme) and
(not login_netloc or login_netloc == current_netloc)):
path = request.get_full_path()
from django.contrib.auth.views import redirect_to_login
return redirect_to_login(
path, resolved_login_url, redirect_field_name)
return _wrapped_view
return decorator | [
"def",
"permission_required",
"(",
"perms",
",",
"login_url",
"=",
"None",
",",
"raise_exception",
"=",
"False",
",",
"redirect_field_name",
"=",
"REDIRECT_FIELD_NAME",
")",
":",
"def",
"decorator",
"(",
"view_func",
")",
":",
"@",
"wraps",
"(",
"view_func",
"... | this is analog to django's builtin ``permission_required`` decorator, but
improved to check per slug ACLRules and default permissions for
anonymous and logged in users
if there is a rule affecting a slug, the user needs to be part of the
rule's allowed users. If there isn't a matching rule, defaults permissions
apply. | [
"this",
"is",
"analog",
"to",
"django",
"s",
"builtin",
"permission_required",
"decorator",
"but",
"improved",
"to",
"check",
"per",
"slug",
"ACLRules",
"and",
"default",
"permissions",
"for",
"anonymous",
"and",
"logged",
"in",
"users"
] | 5baaf6f043275920a1174ff233726f7ff4bfb5cf | https://github.com/mgaitan/waliki/blob/5baaf6f043275920a1174ff233726f7ff4bfb5cf/waliki/acl.py#L48-L87 | train | 37,203 |
mgaitan/waliki | waliki/plugins.py | get_module | def get_module(app, modname, verbose=False, failfast=False):
"""
Internal function to load a module from a single app.
taken from https://github.com/ojii/django-load.
"""
module_name = '%s.%s' % (app, modname)
try:
module = import_module(module_name)
except ImportError as e:
if failfast:
raise e
elif verbose:
print("Could not load %r from %r: %s" % (modname, app, e))
return None
if verbose:
print("Loaded %r from %r" % (modname, app))
return module | python | def get_module(app, modname, verbose=False, failfast=False):
"""
Internal function to load a module from a single app.
taken from https://github.com/ojii/django-load.
"""
module_name = '%s.%s' % (app, modname)
try:
module = import_module(module_name)
except ImportError as e:
if failfast:
raise e
elif verbose:
print("Could not load %r from %r: %s" % (modname, app, e))
return None
if verbose:
print("Loaded %r from %r" % (modname, app))
return module | [
"def",
"get_module",
"(",
"app",
",",
"modname",
",",
"verbose",
"=",
"False",
",",
"failfast",
"=",
"False",
")",
":",
"module_name",
"=",
"'%s.%s'",
"%",
"(",
"app",
",",
"modname",
")",
"try",
":",
"module",
"=",
"import_module",
"(",
"module_name",
... | Internal function to load a module from a single app.
taken from https://github.com/ojii/django-load. | [
"Internal",
"function",
"to",
"load",
"a",
"module",
"from",
"a",
"single",
"app",
"."
] | 5baaf6f043275920a1174ff233726f7ff4bfb5cf | https://github.com/mgaitan/waliki/blob/5baaf6f043275920a1174ff233726f7ff4bfb5cf/waliki/plugins.py#L28-L45 | train | 37,204 |
mgaitan/waliki | waliki/plugins.py | load | def load(modname, verbose=False, failfast=False):
"""
Loads all modules with name 'modname' from all installed apps.
If verbose is True, debug information will be printed to stdout.
If failfast is True, import errors will not be surpressed.
"""
for app in settings.INSTALLED_APPS:
get_module(app, modname, verbose, failfast) | python | def load(modname, verbose=False, failfast=False):
"""
Loads all modules with name 'modname' from all installed apps.
If verbose is True, debug information will be printed to stdout.
If failfast is True, import errors will not be surpressed.
"""
for app in settings.INSTALLED_APPS:
get_module(app, modname, verbose, failfast) | [
"def",
"load",
"(",
"modname",
",",
"verbose",
"=",
"False",
",",
"failfast",
"=",
"False",
")",
":",
"for",
"app",
"in",
"settings",
".",
"INSTALLED_APPS",
":",
"get_module",
"(",
"app",
",",
"modname",
",",
"verbose",
",",
"failfast",
")"
] | Loads all modules with name 'modname' from all installed apps.
If verbose is True, debug information will be printed to stdout.
If failfast is True, import errors will not be surpressed. | [
"Loads",
"all",
"modules",
"with",
"name",
"modname",
"from",
"all",
"installed",
"apps",
".",
"If",
"verbose",
"is",
"True",
"debug",
"information",
"will",
"be",
"printed",
"to",
"stdout",
".",
"If",
"failfast",
"is",
"True",
"import",
"errors",
"will",
... | 5baaf6f043275920a1174ff233726f7ff4bfb5cf | https://github.com/mgaitan/waliki/blob/5baaf6f043275920a1174ff233726f7ff4bfb5cf/waliki/plugins.py#L48-L55 | train | 37,205 |
mgaitan/waliki | waliki/plugins.py | register | def register(PluginClass):
"""
Register a plugin class. This function will call back your plugin's
constructor.
"""
if PluginClass in _cache.keys():
raise Exception("Plugin class already registered")
plugin = PluginClass()
_cache[PluginClass] = plugin
if getattr(PluginClass, 'extra_page_actions', False):
for key in plugin.extra_page_actions:
if key not in _extra_page_actions:
_extra_page_actions[key] = []
_extra_page_actions[key].extend(plugin.extra_page_actions[key])
if getattr(PluginClass, 'extra_edit_actions', False):
for key in plugin.extra_edit_actions:
if key not in _extra_edit_actions:
_extra_edit_actions[key] = []
_extra_edit_actions[key].extend(plugin.extra_edit_actions[key])
if getattr(PluginClass, 'navbar_links', False):
_navbar_links.extend(list(plugin.navbar_links)) | python | def register(PluginClass):
"""
Register a plugin class. This function will call back your plugin's
constructor.
"""
if PluginClass in _cache.keys():
raise Exception("Plugin class already registered")
plugin = PluginClass()
_cache[PluginClass] = plugin
if getattr(PluginClass, 'extra_page_actions', False):
for key in plugin.extra_page_actions:
if key not in _extra_page_actions:
_extra_page_actions[key] = []
_extra_page_actions[key].extend(plugin.extra_page_actions[key])
if getattr(PluginClass, 'extra_edit_actions', False):
for key in plugin.extra_edit_actions:
if key not in _extra_edit_actions:
_extra_edit_actions[key] = []
_extra_edit_actions[key].extend(plugin.extra_edit_actions[key])
if getattr(PluginClass, 'navbar_links', False):
_navbar_links.extend(list(plugin.navbar_links)) | [
"def",
"register",
"(",
"PluginClass",
")",
":",
"if",
"PluginClass",
"in",
"_cache",
".",
"keys",
"(",
")",
":",
"raise",
"Exception",
"(",
"\"Plugin class already registered\"",
")",
"plugin",
"=",
"PluginClass",
"(",
")",
"_cache",
"[",
"PluginClass",
"]",
... | Register a plugin class. This function will call back your plugin's
constructor. | [
"Register",
"a",
"plugin",
"class",
".",
"This",
"function",
"will",
"call",
"back",
"your",
"plugin",
"s",
"constructor",
"."
] | 5baaf6f043275920a1174ff233726f7ff4bfb5cf | https://github.com/mgaitan/waliki/blob/5baaf6f043275920a1174ff233726f7ff4bfb5cf/waliki/plugins.py#L62-L86 | train | 37,206 |
mgaitan/waliki | waliki/context_processors.py | settings | def settings(request):
"""inject few waliki's settings to the context to be used in templates"""
from waliki.settings import WALIKI_USE_MATHJAX # NOQA
return {k: v for (k, v) in locals().items() if k.startswith('WALIKI')} | python | def settings(request):
"""inject few waliki's settings to the context to be used in templates"""
from waliki.settings import WALIKI_USE_MATHJAX # NOQA
return {k: v for (k, v) in locals().items() if k.startswith('WALIKI')} | [
"def",
"settings",
"(",
"request",
")",
":",
"from",
"waliki",
".",
"settings",
"import",
"WALIKI_USE_MATHJAX",
"# NOQA",
"return",
"{",
"k",
":",
"v",
"for",
"(",
"k",
",",
"v",
")",
"in",
"locals",
"(",
")",
".",
"items",
"(",
")",
"if",
"k",
"."... | inject few waliki's settings to the context to be used in templates | [
"inject",
"few",
"waliki",
"s",
"settings",
"to",
"the",
"context",
"to",
"be",
"used",
"in",
"templates"
] | 5baaf6f043275920a1174ff233726f7ff4bfb5cf | https://github.com/mgaitan/waliki/blob/5baaf6f043275920a1174ff233726f7ff4bfb5cf/waliki/context_processors.py#L2-L5 | train | 37,207 |
ccnmtl/fdfgen | fdfgen/__init__.py | smart_encode_str | def smart_encode_str(s):
"""Create a UTF-16 encoded PDF string literal for `s`."""
try:
utf16 = s.encode('utf_16_be')
except AttributeError: # ints and floats
utf16 = str(s).encode('utf_16_be')
safe = utf16.replace(b'\x00)', b'\x00\\)').replace(b'\x00(', b'\x00\\(')
return b''.join((codecs.BOM_UTF16_BE, safe)) | python | def smart_encode_str(s):
"""Create a UTF-16 encoded PDF string literal for `s`."""
try:
utf16 = s.encode('utf_16_be')
except AttributeError: # ints and floats
utf16 = str(s).encode('utf_16_be')
safe = utf16.replace(b'\x00)', b'\x00\\)').replace(b'\x00(', b'\x00\\(')
return b''.join((codecs.BOM_UTF16_BE, safe)) | [
"def",
"smart_encode_str",
"(",
"s",
")",
":",
"try",
":",
"utf16",
"=",
"s",
".",
"encode",
"(",
"'utf_16_be'",
")",
"except",
"AttributeError",
":",
"# ints and floats",
"utf16",
"=",
"str",
"(",
"s",
")",
".",
"encode",
"(",
"'utf_16_be'",
")",
"safe"... | Create a UTF-16 encoded PDF string literal for `s`. | [
"Create",
"a",
"UTF",
"-",
"16",
"encoded",
"PDF",
"string",
"literal",
"for",
"s",
"."
] | 7db306b78e65058da408a76a3ff96ba917b70763 | https://github.com/ccnmtl/fdfgen/blob/7db306b78e65058da408a76a3ff96ba917b70763/fdfgen/__init__.py#L23-L30 | train | 37,208 |
ccnmtl/fdfgen | fdfgen/__init__.py | forge_fdf | def forge_fdf(pdf_form_url=None, fdf_data_strings=[], fdf_data_names=[],
fields_hidden=[], fields_readonly=[],
checkbox_checked_name=b"Yes"):
"""Generates fdf string from fields specified
* pdf_form_url (default: None): just the url for the form.
* fdf_data_strings (default: []): array of (string, value) tuples for the
form fields (or dicts). Value is passed as a UTF-16 encoded string,
unless True/False, in which case it is assumed to be a checkbox
(and passes names, '/Yes' (by default) or '/Off').
* fdf_data_names (default: []): array of (string, value) tuples for the
form fields (or dicts). Value is passed to FDF as a name, '/value'
* fields_hidden (default: []): list of field names that should be set
hidden.
* fields_readonly (default: []): list of field names that should be set
readonly.
* checkbox_checked_value (default: "Yes"): By default means a checked
checkboxes gets passed the value "/Yes". You may find that the default
does not work with your PDF, in which case you might want to try "On".
The result is a string suitable for writing to a .fdf file.
"""
fdf = [b'%FDF-1.2\x0a%\xe2\xe3\xcf\xd3\x0d\x0a']
fdf.append(b'1 0 obj\x0a<</FDF')
fdf.append(b'<</Fields[')
fdf.append(b''.join(handle_data_strings(fdf_data_strings,
fields_hidden, fields_readonly,
checkbox_checked_name)))
fdf.append(b''.join(handle_data_names(fdf_data_names,
fields_hidden, fields_readonly)))
if pdf_form_url:
fdf.append(b''.join(b'/F (', smart_encode_str(pdf_form_url), b')\x0a'))
fdf.append(b']\x0a')
fdf.append(b'>>\x0a')
fdf.append(b'>>\x0aendobj\x0a')
fdf.append(b'trailer\x0a\x0a<<\x0a/Root 1 0 R\x0a>>\x0a')
fdf.append(b'%%EOF\x0a\x0a')
return b''.join(fdf) | python | def forge_fdf(pdf_form_url=None, fdf_data_strings=[], fdf_data_names=[],
fields_hidden=[], fields_readonly=[],
checkbox_checked_name=b"Yes"):
"""Generates fdf string from fields specified
* pdf_form_url (default: None): just the url for the form.
* fdf_data_strings (default: []): array of (string, value) tuples for the
form fields (or dicts). Value is passed as a UTF-16 encoded string,
unless True/False, in which case it is assumed to be a checkbox
(and passes names, '/Yes' (by default) or '/Off').
* fdf_data_names (default: []): array of (string, value) tuples for the
form fields (or dicts). Value is passed to FDF as a name, '/value'
* fields_hidden (default: []): list of field names that should be set
hidden.
* fields_readonly (default: []): list of field names that should be set
readonly.
* checkbox_checked_value (default: "Yes"): By default means a checked
checkboxes gets passed the value "/Yes". You may find that the default
does not work with your PDF, in which case you might want to try "On".
The result is a string suitable for writing to a .fdf file.
"""
fdf = [b'%FDF-1.2\x0a%\xe2\xe3\xcf\xd3\x0d\x0a']
fdf.append(b'1 0 obj\x0a<</FDF')
fdf.append(b'<</Fields[')
fdf.append(b''.join(handle_data_strings(fdf_data_strings,
fields_hidden, fields_readonly,
checkbox_checked_name)))
fdf.append(b''.join(handle_data_names(fdf_data_names,
fields_hidden, fields_readonly)))
if pdf_form_url:
fdf.append(b''.join(b'/F (', smart_encode_str(pdf_form_url), b')\x0a'))
fdf.append(b']\x0a')
fdf.append(b'>>\x0a')
fdf.append(b'>>\x0aendobj\x0a')
fdf.append(b'trailer\x0a\x0a<<\x0a/Root 1 0 R\x0a>>\x0a')
fdf.append(b'%%EOF\x0a\x0a')
return b''.join(fdf) | [
"def",
"forge_fdf",
"(",
"pdf_form_url",
"=",
"None",
",",
"fdf_data_strings",
"=",
"[",
"]",
",",
"fdf_data_names",
"=",
"[",
"]",
",",
"fields_hidden",
"=",
"[",
"]",
",",
"fields_readonly",
"=",
"[",
"]",
",",
"checkbox_checked_name",
"=",
"b\"Yes\"",
"... | Generates fdf string from fields specified
* pdf_form_url (default: None): just the url for the form.
* fdf_data_strings (default: []): array of (string, value) tuples for the
form fields (or dicts). Value is passed as a UTF-16 encoded string,
unless True/False, in which case it is assumed to be a checkbox
(and passes names, '/Yes' (by default) or '/Off').
* fdf_data_names (default: []): array of (string, value) tuples for the
form fields (or dicts). Value is passed to FDF as a name, '/value'
* fields_hidden (default: []): list of field names that should be set
hidden.
* fields_readonly (default: []): list of field names that should be set
readonly.
* checkbox_checked_value (default: "Yes"): By default means a checked
checkboxes gets passed the value "/Yes". You may find that the default
does not work with your PDF, in which case you might want to try "On".
The result is a string suitable for writing to a .fdf file. | [
"Generates",
"fdf",
"string",
"from",
"fields",
"specified"
] | 7db306b78e65058da408a76a3ff96ba917b70763 | https://github.com/ccnmtl/fdfgen/blob/7db306b78e65058da408a76a3ff96ba917b70763/fdfgen/__init__.py#L109-L147 | train | 37,209 |
vxgmichel/aiostream | aiostream/stream/advanced.py | base_combine | async def base_combine(source, switch=False, ordered=False, task_limit=None):
"""Base operator for managing an asynchronous sequence of sequences.
The sequences are awaited concurrently, although it's possible to limit
the amount of running sequences using the `task_limit` argument.
The ``switch`` argument enables the switch mecanism, which cause the
previous subsequence to be discarded when a new one is created.
The items can either be generated in order or as soon as they're received,
depending on the ``ordered`` argument.
"""
# Task limit
if task_limit is not None and not task_limit > 0:
raise ValueError('The task limit must be None or greater than 0')
# Safe context
async with StreamerManager() as manager:
main_streamer = await manager.enter_and_create_task(source)
# Loop over events
while manager.tasks:
# Extract streamer groups
substreamers = manager.streamers[1:]
mainstreamers = [main_streamer] if main_streamer in manager.tasks else []
# Switch - use the main streamer then the substreamer
if switch:
filters = mainstreamers + substreamers
# Concat - use the first substreamer then the main streamer
elif ordered:
filters = substreamers[:1] + mainstreamers
# Flat - use the substreamers then the main streamer
else:
filters = substreamers + mainstreamers
# Wait for next event
streamer, task = await manager.wait_single_event(filters)
# Get result
try:
result = task.result()
# End of stream
except StopAsyncIteration:
# Main streamer is finished
if streamer is main_streamer:
main_streamer = None
# A substreamer is finished
else:
await manager.clean_streamer(streamer)
# Re-schedule the main streamer if necessary
if main_streamer is not None and main_streamer not in manager.tasks:
manager.create_task(main_streamer)
# Process result
else:
# Switch mecanism
if switch and streamer is main_streamer:
await manager.clean_streamers(substreamers)
# Setup a new source
if streamer is main_streamer:
await manager.enter_and_create_task(result)
# Re-schedule the main streamer if task limit allows it
if task_limit is None or task_limit > len(manager.tasks):
manager.create_task(streamer)
# Yield the result
else:
yield result
# Re-schedule the streamer
manager.create_task(streamer) | python | async def base_combine(source, switch=False, ordered=False, task_limit=None):
"""Base operator for managing an asynchronous sequence of sequences.
The sequences are awaited concurrently, although it's possible to limit
the amount of running sequences using the `task_limit` argument.
The ``switch`` argument enables the switch mecanism, which cause the
previous subsequence to be discarded when a new one is created.
The items can either be generated in order or as soon as they're received,
depending on the ``ordered`` argument.
"""
# Task limit
if task_limit is not None and not task_limit > 0:
raise ValueError('The task limit must be None or greater than 0')
# Safe context
async with StreamerManager() as manager:
main_streamer = await manager.enter_and_create_task(source)
# Loop over events
while manager.tasks:
# Extract streamer groups
substreamers = manager.streamers[1:]
mainstreamers = [main_streamer] if main_streamer in manager.tasks else []
# Switch - use the main streamer then the substreamer
if switch:
filters = mainstreamers + substreamers
# Concat - use the first substreamer then the main streamer
elif ordered:
filters = substreamers[:1] + mainstreamers
# Flat - use the substreamers then the main streamer
else:
filters = substreamers + mainstreamers
# Wait for next event
streamer, task = await manager.wait_single_event(filters)
# Get result
try:
result = task.result()
# End of stream
except StopAsyncIteration:
# Main streamer is finished
if streamer is main_streamer:
main_streamer = None
# A substreamer is finished
else:
await manager.clean_streamer(streamer)
# Re-schedule the main streamer if necessary
if main_streamer is not None and main_streamer not in manager.tasks:
manager.create_task(main_streamer)
# Process result
else:
# Switch mecanism
if switch and streamer is main_streamer:
await manager.clean_streamers(substreamers)
# Setup a new source
if streamer is main_streamer:
await manager.enter_and_create_task(result)
# Re-schedule the main streamer if task limit allows it
if task_limit is None or task_limit > len(manager.tasks):
manager.create_task(streamer)
# Yield the result
else:
yield result
# Re-schedule the streamer
manager.create_task(streamer) | [
"async",
"def",
"base_combine",
"(",
"source",
",",
"switch",
"=",
"False",
",",
"ordered",
"=",
"False",
",",
"task_limit",
"=",
"None",
")",
":",
"# Task limit",
"if",
"task_limit",
"is",
"not",
"None",
"and",
"not",
"task_limit",
">",
"0",
":",
"raise... | Base operator for managing an asynchronous sequence of sequences.
The sequences are awaited concurrently, although it's possible to limit
the amount of running sequences using the `task_limit` argument.
The ``switch`` argument enables the switch mecanism, which cause the
previous subsequence to be discarded when a new one is created.
The items can either be generated in order or as soon as they're received,
depending on the ``ordered`` argument. | [
"Base",
"operator",
"for",
"managing",
"an",
"asynchronous",
"sequence",
"of",
"sequences",
"."
] | 43bdf04ab19108a3f1b5a472062e1392a26cbcf8 | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/advanced.py#L15-L96 | train | 37,210 |
vxgmichel/aiostream | aiostream/stream/advanced.py | concat | def concat(source, task_limit=None):
"""Given an asynchronous sequence of sequences, generate the elements
of the sequences in order.
The sequences are awaited concurrently, although it's possible to limit
the amount of running sequences using the `task_limit` argument.
Errors raised in the source or an element sequence are propagated.
"""
return base_combine.raw(
source, task_limit=task_limit, switch=False, ordered=True) | python | def concat(source, task_limit=None):
"""Given an asynchronous sequence of sequences, generate the elements
of the sequences in order.
The sequences are awaited concurrently, although it's possible to limit
the amount of running sequences using the `task_limit` argument.
Errors raised in the source or an element sequence are propagated.
"""
return base_combine.raw(
source, task_limit=task_limit, switch=False, ordered=True) | [
"def",
"concat",
"(",
"source",
",",
"task_limit",
"=",
"None",
")",
":",
"return",
"base_combine",
".",
"raw",
"(",
"source",
",",
"task_limit",
"=",
"task_limit",
",",
"switch",
"=",
"False",
",",
"ordered",
"=",
"True",
")"
] | Given an asynchronous sequence of sequences, generate the elements
of the sequences in order.
The sequences are awaited concurrently, although it's possible to limit
the amount of running sequences using the `task_limit` argument.
Errors raised in the source or an element sequence are propagated. | [
"Given",
"an",
"asynchronous",
"sequence",
"of",
"sequences",
"generate",
"the",
"elements",
"of",
"the",
"sequences",
"in",
"order",
"."
] | 43bdf04ab19108a3f1b5a472062e1392a26cbcf8 | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/advanced.py#L102-L112 | train | 37,211 |
vxgmichel/aiostream | aiostream/stream/advanced.py | flatten | def flatten(source, task_limit=None):
"""Given an asynchronous sequence of sequences, generate the elements
of the sequences as soon as they're received.
The sequences are awaited concurrently, although it's possible to limit
the amount of running sequences using the `task_limit` argument.
Errors raised in the source or an element sequence are propagated.
"""
return base_combine.raw(
source, task_limit=task_limit, switch=False, ordered=False) | python | def flatten(source, task_limit=None):
"""Given an asynchronous sequence of sequences, generate the elements
of the sequences as soon as they're received.
The sequences are awaited concurrently, although it's possible to limit
the amount of running sequences using the `task_limit` argument.
Errors raised in the source or an element sequence are propagated.
"""
return base_combine.raw(
source, task_limit=task_limit, switch=False, ordered=False) | [
"def",
"flatten",
"(",
"source",
",",
"task_limit",
"=",
"None",
")",
":",
"return",
"base_combine",
".",
"raw",
"(",
"source",
",",
"task_limit",
"=",
"task_limit",
",",
"switch",
"=",
"False",
",",
"ordered",
"=",
"False",
")"
] | Given an asynchronous sequence of sequences, generate the elements
of the sequences as soon as they're received.
The sequences are awaited concurrently, although it's possible to limit
the amount of running sequences using the `task_limit` argument.
Errors raised in the source or an element sequence are propagated. | [
"Given",
"an",
"asynchronous",
"sequence",
"of",
"sequences",
"generate",
"the",
"elements",
"of",
"the",
"sequences",
"as",
"soon",
"as",
"they",
"re",
"received",
"."
] | 43bdf04ab19108a3f1b5a472062e1392a26cbcf8 | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/advanced.py#L116-L126 | train | 37,212 |
vxgmichel/aiostream | aiostream/stream/advanced.py | concatmap | def concatmap(source, func, *more_sources, task_limit=None):
"""Apply a given function that creates a sequence from the elements of one
or several asynchronous sequences, and generate the elements of the created
sequences in order.
The function is applied as described in `map`, and must return an
asynchronous sequence. The returned sequences are awaited concurrently,
although it's possible to limit the amount of running sequences using
the `task_limit` argument.
"""
return concat.raw(
combine.smap.raw(source, func, *more_sources), task_limit=task_limit) | python | def concatmap(source, func, *more_sources, task_limit=None):
"""Apply a given function that creates a sequence from the elements of one
or several asynchronous sequences, and generate the elements of the created
sequences in order.
The function is applied as described in `map`, and must return an
asynchronous sequence. The returned sequences are awaited concurrently,
although it's possible to limit the amount of running sequences using
the `task_limit` argument.
"""
return concat.raw(
combine.smap.raw(source, func, *more_sources), task_limit=task_limit) | [
"def",
"concatmap",
"(",
"source",
",",
"func",
",",
"*",
"more_sources",
",",
"task_limit",
"=",
"None",
")",
":",
"return",
"concat",
".",
"raw",
"(",
"combine",
".",
"smap",
".",
"raw",
"(",
"source",
",",
"func",
",",
"*",
"more_sources",
")",
",... | Apply a given function that creates a sequence from the elements of one
or several asynchronous sequences, and generate the elements of the created
sequences in order.
The function is applied as described in `map`, and must return an
asynchronous sequence. The returned sequences are awaited concurrently,
although it's possible to limit the amount of running sequences using
the `task_limit` argument. | [
"Apply",
"a",
"given",
"function",
"that",
"creates",
"a",
"sequence",
"from",
"the",
"elements",
"of",
"one",
"or",
"several",
"asynchronous",
"sequences",
"and",
"generate",
"the",
"elements",
"of",
"the",
"created",
"sequences",
"in",
"order",
"."
] | 43bdf04ab19108a3f1b5a472062e1392a26cbcf8 | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/advanced.py#L147-L158 | train | 37,213 |
vxgmichel/aiostream | aiostream/stream/advanced.py | flatmap | def flatmap(source, func, *more_sources, task_limit=None):
"""Apply a given function that creates a sequence from the elements of one
or several asynchronous sequences, and generate the elements of the created
sequences as soon as they arrive.
The function is applied as described in `map`, and must return an
asynchronous sequence. The returned sequences are awaited concurrently,
although it's possible to limit the amount of running sequences using
the `task_limit` argument.
Errors raised in a source or output sequence are propagated.
"""
return flatten.raw(
combine.smap.raw(source, func, *more_sources), task_limit=task_limit) | python | def flatmap(source, func, *more_sources, task_limit=None):
"""Apply a given function that creates a sequence from the elements of one
or several asynchronous sequences, and generate the elements of the created
sequences as soon as they arrive.
The function is applied as described in `map`, and must return an
asynchronous sequence. The returned sequences are awaited concurrently,
although it's possible to limit the amount of running sequences using
the `task_limit` argument.
Errors raised in a source or output sequence are propagated.
"""
return flatten.raw(
combine.smap.raw(source, func, *more_sources), task_limit=task_limit) | [
"def",
"flatmap",
"(",
"source",
",",
"func",
",",
"*",
"more_sources",
",",
"task_limit",
"=",
"None",
")",
":",
"return",
"flatten",
".",
"raw",
"(",
"combine",
".",
"smap",
".",
"raw",
"(",
"source",
",",
"func",
",",
"*",
"more_sources",
")",
","... | Apply a given function that creates a sequence from the elements of one
or several asynchronous sequences, and generate the elements of the created
sequences as soon as they arrive.
The function is applied as described in `map`, and must return an
asynchronous sequence. The returned sequences are awaited concurrently,
although it's possible to limit the amount of running sequences using
the `task_limit` argument.
Errors raised in a source or output sequence are propagated. | [
"Apply",
"a",
"given",
"function",
"that",
"creates",
"a",
"sequence",
"from",
"the",
"elements",
"of",
"one",
"or",
"several",
"asynchronous",
"sequences",
"and",
"generate",
"the",
"elements",
"of",
"the",
"created",
"sequences",
"as",
"soon",
"as",
"they",
... | 43bdf04ab19108a3f1b5a472062e1392a26cbcf8 | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/advanced.py#L162-L175 | train | 37,214 |
vxgmichel/aiostream | aiostream/stream/advanced.py | switchmap | def switchmap(source, func, *more_sources):
"""Apply a given function that creates a sequence from the elements of one
or several asynchronous sequences and generate the elements of the most
recently created sequence.
The function is applied as described in `map`, and must return an
asynchronous sequence. Errors raised in a source or output sequence (that
was not already closed) are propagated.
"""
return switch.raw(combine.smap.raw(source, func, *more_sources)) | python | def switchmap(source, func, *more_sources):
"""Apply a given function that creates a sequence from the elements of one
or several asynchronous sequences and generate the elements of the most
recently created sequence.
The function is applied as described in `map`, and must return an
asynchronous sequence. Errors raised in a source or output sequence (that
was not already closed) are propagated.
"""
return switch.raw(combine.smap.raw(source, func, *more_sources)) | [
"def",
"switchmap",
"(",
"source",
",",
"func",
",",
"*",
"more_sources",
")",
":",
"return",
"switch",
".",
"raw",
"(",
"combine",
".",
"smap",
".",
"raw",
"(",
"source",
",",
"func",
",",
"*",
"more_sources",
")",
")"
] | Apply a given function that creates a sequence from the elements of one
or several asynchronous sequences and generate the elements of the most
recently created sequence.
The function is applied as described in `map`, and must return an
asynchronous sequence. Errors raised in a source or output sequence (that
was not already closed) are propagated. | [
"Apply",
"a",
"given",
"function",
"that",
"creates",
"a",
"sequence",
"from",
"the",
"elements",
"of",
"one",
"or",
"several",
"asynchronous",
"sequences",
"and",
"generate",
"the",
"elements",
"of",
"the",
"most",
"recently",
"created",
"sequence",
"."
] | 43bdf04ab19108a3f1b5a472062e1392a26cbcf8 | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/advanced.py#L179-L188 | train | 37,215 |
vxgmichel/aiostream | aiostream/stream/aggregate.py | reduce | def reduce(source, func, initializer=None):
"""Apply a function of two arguments cumulatively to the items
of an asynchronous sequence, reducing the sequence to a single value.
If ``initializer`` is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
"""
acc = accumulate.raw(source, func, initializer)
return select.item.raw(acc, -1) | python | def reduce(source, func, initializer=None):
"""Apply a function of two arguments cumulatively to the items
of an asynchronous sequence, reducing the sequence to a single value.
If ``initializer`` is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
"""
acc = accumulate.raw(source, func, initializer)
return select.item.raw(acc, -1) | [
"def",
"reduce",
"(",
"source",
",",
"func",
",",
"initializer",
"=",
"None",
")",
":",
"acc",
"=",
"accumulate",
".",
"raw",
"(",
"source",
",",
"func",
",",
"initializer",
")",
"return",
"select",
".",
"item",
".",
"raw",
"(",
"acc",
",",
"-",
"1... | Apply a function of two arguments cumulatively to the items
of an asynchronous sequence, reducing the sequence to a single value.
If ``initializer`` is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty. | [
"Apply",
"a",
"function",
"of",
"two",
"arguments",
"cumulatively",
"to",
"the",
"items",
"of",
"an",
"asynchronous",
"sequence",
"reducing",
"the",
"sequence",
"to",
"a",
"single",
"value",
"."
] | 43bdf04ab19108a3f1b5a472062e1392a26cbcf8 | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/aggregate.py#L43-L52 | train | 37,216 |
vxgmichel/aiostream | aiostream/stream/aggregate.py | list | async def list(source):
"""Generate a single list from an asynchronous sequence."""
result = []
async with streamcontext(source) as streamer:
async for item in streamer:
result.append(item)
yield result | python | async def list(source):
"""Generate a single list from an asynchronous sequence."""
result = []
async with streamcontext(source) as streamer:
async for item in streamer:
result.append(item)
yield result | [
"async",
"def",
"list",
"(",
"source",
")",
":",
"result",
"=",
"[",
"]",
"async",
"with",
"streamcontext",
"(",
"source",
")",
"as",
"streamer",
":",
"async",
"for",
"item",
"in",
"streamer",
":",
"result",
".",
"append",
"(",
"item",
")",
"yield",
... | Generate a single list from an asynchronous sequence. | [
"Generate",
"a",
"single",
"list",
"from",
"an",
"asynchronous",
"sequence",
"."
] | 43bdf04ab19108a3f1b5a472062e1392a26cbcf8 | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/aggregate.py#L56-L62 | train | 37,217 |
vxgmichel/aiostream | aiostream/core.py | wait_stream | async def wait_stream(aiterable):
"""Wait for an asynchronous iterable to finish and return the last item.
The iterable is executed within a safe stream context.
A StreamEmpty exception is raised if the sequence is empty.
"""
async with streamcontext(aiterable) as streamer:
async for item in streamer:
item
try:
return item
except NameError:
raise StreamEmpty() | python | async def wait_stream(aiterable):
"""Wait for an asynchronous iterable to finish and return the last item.
The iterable is executed within a safe stream context.
A StreamEmpty exception is raised if the sequence is empty.
"""
async with streamcontext(aiterable) as streamer:
async for item in streamer:
item
try:
return item
except NameError:
raise StreamEmpty() | [
"async",
"def",
"wait_stream",
"(",
"aiterable",
")",
":",
"async",
"with",
"streamcontext",
"(",
"aiterable",
")",
"as",
"streamer",
":",
"async",
"for",
"item",
"in",
"streamer",
":",
"item",
"try",
":",
"return",
"item",
"except",
"NameError",
":",
"rai... | Wait for an asynchronous iterable to finish and return the last item.
The iterable is executed within a safe stream context.
A StreamEmpty exception is raised if the sequence is empty. | [
"Wait",
"for",
"an",
"asynchronous",
"iterable",
"to",
"finish",
"and",
"return",
"the",
"last",
"item",
"."
] | 43bdf04ab19108a3f1b5a472062e1392a26cbcf8 | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/core.py#L22-L34 | train | 37,218 |
vxgmichel/aiostream | aiostream/stream/misc.py | action | def action(source, func):
"""Perform an action for each element of an asynchronous sequence
without modifying it.
The given function can be synchronous or asynchronous.
"""
if asyncio.iscoroutinefunction(func):
async def innerfunc(arg):
await func(arg)
return arg
else:
def innerfunc(arg):
func(arg)
return arg
return map.raw(source, innerfunc) | python | def action(source, func):
"""Perform an action for each element of an asynchronous sequence
without modifying it.
The given function can be synchronous or asynchronous.
"""
if asyncio.iscoroutinefunction(func):
async def innerfunc(arg):
await func(arg)
return arg
else:
def innerfunc(arg):
func(arg)
return arg
return map.raw(source, innerfunc) | [
"def",
"action",
"(",
"source",
",",
"func",
")",
":",
"if",
"asyncio",
".",
"iscoroutinefunction",
"(",
"func",
")",
":",
"async",
"def",
"innerfunc",
"(",
"arg",
")",
":",
"await",
"func",
"(",
"arg",
")",
"return",
"arg",
"else",
":",
"def",
"inne... | Perform an action for each element of an asynchronous sequence
without modifying it.
The given function can be synchronous or asynchronous. | [
"Perform",
"an",
"action",
"for",
"each",
"element",
"of",
"an",
"asynchronous",
"sequence",
"without",
"modifying",
"it",
"."
] | 43bdf04ab19108a3f1b5a472062e1392a26cbcf8 | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/misc.py#L12-L26 | train | 37,219 |
vxgmichel/aiostream | aiostream/stream/misc.py | print | def print(source, template=None, **kwargs):
"""Print each element of an asynchronous sequence without modifying it.
An optional template can be provided to be formatted with the elements.
All the keyword arguments are forwarded to the builtin function print.
"""
def func(value):
if template:
value = template.format(value)
builtins.print(value, **kwargs)
return action.raw(source, func) | python | def print(source, template=None, **kwargs):
"""Print each element of an asynchronous sequence without modifying it.
An optional template can be provided to be formatted with the elements.
All the keyword arguments are forwarded to the builtin function print.
"""
def func(value):
if template:
value = template.format(value)
builtins.print(value, **kwargs)
return action.raw(source, func) | [
"def",
"print",
"(",
"source",
",",
"template",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"func",
"(",
"value",
")",
":",
"if",
"template",
":",
"value",
"=",
"template",
".",
"format",
"(",
"value",
")",
"builtins",
".",
"print",
"(",... | Print each element of an asynchronous sequence without modifying it.
An optional template can be provided to be formatted with the elements.
All the keyword arguments are forwarded to the builtin function print. | [
"Print",
"each",
"element",
"of",
"an",
"asynchronous",
"sequence",
"without",
"modifying",
"it",
"."
] | 43bdf04ab19108a3f1b5a472062e1392a26cbcf8 | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/misc.py#L30-L40 | train | 37,220 |
vxgmichel/aiostream | aiostream/aiter_utils.py | async_ | def async_(fn):
"""Wrap the given function into a coroutine function."""
@functools.wraps(fn)
async def wrapper(*args, **kwargs):
return await fn(*args, **kwargs)
return wrapper | python | def async_(fn):
"""Wrap the given function into a coroutine function."""
@functools.wraps(fn)
async def wrapper(*args, **kwargs):
return await fn(*args, **kwargs)
return wrapper | [
"def",
"async_",
"(",
"fn",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"fn",
")",
"async",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"await",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"retu... | Wrap the given function into a coroutine function. | [
"Wrap",
"the",
"given",
"function",
"into",
"a",
"coroutine",
"function",
"."
] | 43bdf04ab19108a3f1b5a472062e1392a26cbcf8 | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/aiter_utils.py#L40-L45 | train | 37,221 |
vxgmichel/aiostream | aiostream/aiter_utils.py | aitercontext | def aitercontext(aiterable, *, cls=AsyncIteratorContext):
"""Return an asynchronous context manager from an asynchronous iterable.
The context management makes sure the aclose asynchronous method
has run before it exits. It also issues warnings and RuntimeError
if it is used incorrectly.
It is safe to use with any asynchronous iterable and prevent
asynchronous iterator context to be wrapped twice.
Correct usage::
ait = some_asynchronous_iterable()
async with aitercontext(ait) as safe_ait:
async for item in safe_ait:
<block>
An optional subclass of AsyncIteratorContext can be provided.
This class will be used to wrap the given iterable.
"""
assert issubclass(cls, AsyncIteratorContext)
aiterator = aiter(aiterable)
if isinstance(aiterator, cls):
return aiterator
return cls(aiterator) | python | def aitercontext(aiterable, *, cls=AsyncIteratorContext):
"""Return an asynchronous context manager from an asynchronous iterable.
The context management makes sure the aclose asynchronous method
has run before it exits. It also issues warnings and RuntimeError
if it is used incorrectly.
It is safe to use with any asynchronous iterable and prevent
asynchronous iterator context to be wrapped twice.
Correct usage::
ait = some_asynchronous_iterable()
async with aitercontext(ait) as safe_ait:
async for item in safe_ait:
<block>
An optional subclass of AsyncIteratorContext can be provided.
This class will be used to wrap the given iterable.
"""
assert issubclass(cls, AsyncIteratorContext)
aiterator = aiter(aiterable)
if isinstance(aiterator, cls):
return aiterator
return cls(aiterator) | [
"def",
"aitercontext",
"(",
"aiterable",
",",
"*",
",",
"cls",
"=",
"AsyncIteratorContext",
")",
":",
"assert",
"issubclass",
"(",
"cls",
",",
"AsyncIteratorContext",
")",
"aiterator",
"=",
"aiter",
"(",
"aiterable",
")",
"if",
"isinstance",
"(",
"aiterator",
... | Return an asynchronous context manager from an asynchronous iterable.
The context management makes sure the aclose asynchronous method
has run before it exits. It also issues warnings and RuntimeError
if it is used incorrectly.
It is safe to use with any asynchronous iterable and prevent
asynchronous iterator context to be wrapped twice.
Correct usage::
ait = some_asynchronous_iterable()
async with aitercontext(ait) as safe_ait:
async for item in safe_ait:
<block>
An optional subclass of AsyncIteratorContext can be provided.
This class will be used to wrap the given iterable. | [
"Return",
"an",
"asynchronous",
"context",
"manager",
"from",
"an",
"asynchronous",
"iterable",
"."
] | 43bdf04ab19108a3f1b5a472062e1392a26cbcf8 | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/aiter_utils.py#L180-L204 | train | 37,222 |
vxgmichel/aiostream | aiostream/stream/select.py | takelast | async def takelast(source, n):
"""Forward the last ``n`` elements from an asynchronous sequence.
If ``n`` is negative, it simply terminates after iterating the source.
Note: it is required to reach the end of the source before the first
element is generated.
"""
queue = collections.deque(maxlen=n if n > 0 else 0)
async with streamcontext(source) as streamer:
async for item in streamer:
queue.append(item)
for item in queue:
yield item | python | async def takelast(source, n):
"""Forward the last ``n`` elements from an asynchronous sequence.
If ``n`` is negative, it simply terminates after iterating the source.
Note: it is required to reach the end of the source before the first
element is generated.
"""
queue = collections.deque(maxlen=n if n > 0 else 0)
async with streamcontext(source) as streamer:
async for item in streamer:
queue.append(item)
for item in queue:
yield item | [
"async",
"def",
"takelast",
"(",
"source",
",",
"n",
")",
":",
"queue",
"=",
"collections",
".",
"deque",
"(",
"maxlen",
"=",
"n",
"if",
"n",
">",
"0",
"else",
"0",
")",
"async",
"with",
"streamcontext",
"(",
"source",
")",
"as",
"streamer",
":",
"... | Forward the last ``n`` elements from an asynchronous sequence.
If ``n`` is negative, it simply terminates after iterating the source.
Note: it is required to reach the end of the source before the first
element is generated. | [
"Forward",
"the",
"last",
"n",
"elements",
"from",
"an",
"asynchronous",
"sequence",
"."
] | 43bdf04ab19108a3f1b5a472062e1392a26cbcf8 | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/select.py#L32-L45 | train | 37,223 |
vxgmichel/aiostream | aiostream/stream/select.py | skip | async def skip(source, n):
"""Forward an asynchronous sequence, skipping the first ``n`` elements.
If ``n`` is negative, no elements are skipped.
"""
source = transform.enumerate.raw(source)
async with streamcontext(source) as streamer:
async for i, item in streamer:
if i >= n:
yield item | python | async def skip(source, n):
"""Forward an asynchronous sequence, skipping the first ``n`` elements.
If ``n`` is negative, no elements are skipped.
"""
source = transform.enumerate.raw(source)
async with streamcontext(source) as streamer:
async for i, item in streamer:
if i >= n:
yield item | [
"async",
"def",
"skip",
"(",
"source",
",",
"n",
")",
":",
"source",
"=",
"transform",
".",
"enumerate",
".",
"raw",
"(",
"source",
")",
"async",
"with",
"streamcontext",
"(",
"source",
")",
"as",
"streamer",
":",
"async",
"for",
"i",
",",
"item",
"i... | Forward an asynchronous sequence, skipping the first ``n`` elements.
If ``n`` is negative, no elements are skipped. | [
"Forward",
"an",
"asynchronous",
"sequence",
"skipping",
"the",
"first",
"n",
"elements",
"."
] | 43bdf04ab19108a3f1b5a472062e1392a26cbcf8 | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/select.py#L49-L58 | train | 37,224 |
vxgmichel/aiostream | aiostream/stream/select.py | skiplast | async def skiplast(source, n):
"""Forward an asynchronous sequence, skipping the last ``n`` elements.
If ``n`` is negative, no elements are skipped.
Note: it is required to reach the ``n+1`` th element of the source
before the first element is generated.
"""
queue = collections.deque(maxlen=n if n > 0 else 0)
async with streamcontext(source) as streamer:
async for item in streamer:
if n <= 0:
yield item
continue
if len(queue) == n:
yield queue[0]
queue.append(item) | python | async def skiplast(source, n):
"""Forward an asynchronous sequence, skipping the last ``n`` elements.
If ``n`` is negative, no elements are skipped.
Note: it is required to reach the ``n+1`` th element of the source
before the first element is generated.
"""
queue = collections.deque(maxlen=n if n > 0 else 0)
async with streamcontext(source) as streamer:
async for item in streamer:
if n <= 0:
yield item
continue
if len(queue) == n:
yield queue[0]
queue.append(item) | [
"async",
"def",
"skiplast",
"(",
"source",
",",
"n",
")",
":",
"queue",
"=",
"collections",
".",
"deque",
"(",
"maxlen",
"=",
"n",
"if",
"n",
">",
"0",
"else",
"0",
")",
"async",
"with",
"streamcontext",
"(",
"source",
")",
"as",
"streamer",
":",
"... | Forward an asynchronous sequence, skipping the last ``n`` elements.
If ``n`` is negative, no elements are skipped.
Note: it is required to reach the ``n+1`` th element of the source
before the first element is generated. | [
"Forward",
"an",
"asynchronous",
"sequence",
"skipping",
"the",
"last",
"n",
"elements",
"."
] | 43bdf04ab19108a3f1b5a472062e1392a26cbcf8 | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/select.py#L62-L78 | train | 37,225 |
vxgmichel/aiostream | aiostream/stream/select.py | filterindex | async def filterindex(source, func):
"""Filter an asynchronous sequence using the index of the elements.
The given function is synchronous, takes the index as an argument,
and returns ``True`` if the corresponding should be forwarded,
``False`` otherwise.
"""
source = transform.enumerate.raw(source)
async with streamcontext(source) as streamer:
async for i, item in streamer:
if func(i):
yield item | python | async def filterindex(source, func):
"""Filter an asynchronous sequence using the index of the elements.
The given function is synchronous, takes the index as an argument,
and returns ``True`` if the corresponding should be forwarded,
``False`` otherwise.
"""
source = transform.enumerate.raw(source)
async with streamcontext(source) as streamer:
async for i, item in streamer:
if func(i):
yield item | [
"async",
"def",
"filterindex",
"(",
"source",
",",
"func",
")",
":",
"source",
"=",
"transform",
".",
"enumerate",
".",
"raw",
"(",
"source",
")",
"async",
"with",
"streamcontext",
"(",
"source",
")",
"as",
"streamer",
":",
"async",
"for",
"i",
",",
"i... | Filter an asynchronous sequence using the index of the elements.
The given function is synchronous, takes the index as an argument,
and returns ``True`` if the corresponding should be forwarded,
``False`` otherwise. | [
"Filter",
"an",
"asynchronous",
"sequence",
"using",
"the",
"index",
"of",
"the",
"elements",
"."
] | 43bdf04ab19108a3f1b5a472062e1392a26cbcf8 | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/select.py#L82-L93 | train | 37,226 |
vxgmichel/aiostream | aiostream/stream/select.py | slice | def slice(source, *args):
"""Slice an asynchronous sequence.
The arguments are the same as the builtin type slice.
There are two limitations compare to regular slices:
- Positive stop index with negative start index is not supported
- Negative step is not supported
"""
s = builtins.slice(*args)
start, stop, step = s.start or 0, s.stop, s.step or 1
# Filter the first items
if start < 0:
source = takelast.raw(source, abs(start))
elif start > 0:
source = skip.raw(source, start)
# Filter the last items
if stop is not None:
if stop >= 0 and start < 0:
raise ValueError(
"Positive stop with negative start is not supported")
elif stop >= 0:
source = take.raw(source, stop - start)
else:
source = skiplast.raw(source, abs(stop))
# Filter step items
if step is not None:
if step > 1:
source = filterindex.raw(source, lambda i: i % step == 0)
elif step < 0:
raise ValueError("Negative step not supported")
# Return
return source | python | def slice(source, *args):
"""Slice an asynchronous sequence.
The arguments are the same as the builtin type slice.
There are two limitations compare to regular slices:
- Positive stop index with negative start index is not supported
- Negative step is not supported
"""
s = builtins.slice(*args)
start, stop, step = s.start or 0, s.stop, s.step or 1
# Filter the first items
if start < 0:
source = takelast.raw(source, abs(start))
elif start > 0:
source = skip.raw(source, start)
# Filter the last items
if stop is not None:
if stop >= 0 and start < 0:
raise ValueError(
"Positive stop with negative start is not supported")
elif stop >= 0:
source = take.raw(source, stop - start)
else:
source = skiplast.raw(source, abs(stop))
# Filter step items
if step is not None:
if step > 1:
source = filterindex.raw(source, lambda i: i % step == 0)
elif step < 0:
raise ValueError("Negative step not supported")
# Return
return source | [
"def",
"slice",
"(",
"source",
",",
"*",
"args",
")",
":",
"s",
"=",
"builtins",
".",
"slice",
"(",
"*",
"args",
")",
"start",
",",
"stop",
",",
"step",
"=",
"s",
".",
"start",
"or",
"0",
",",
"s",
".",
"stop",
",",
"s",
".",
"step",
"or",
... | Slice an asynchronous sequence.
The arguments are the same as the builtin type slice.
There are two limitations compare to regular slices:
- Positive stop index with negative start index is not supported
- Negative step is not supported | [
"Slice",
"an",
"asynchronous",
"sequence",
"."
] | 43bdf04ab19108a3f1b5a472062e1392a26cbcf8 | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/select.py#L97-L129 | train | 37,227 |
vxgmichel/aiostream | aiostream/stream/select.py | item | async def item(source, index):
"""Forward the ``n``th element of an asynchronous sequence.
The index can be negative and works like regular indexing.
If the index is out of range, and ``IndexError`` is raised.
"""
# Prepare
if index >= 0:
source = skip.raw(source, index)
else:
source = takelast(source, abs(index))
async with streamcontext(source) as streamer:
# Get first item
try:
result = await anext(streamer)
except StopAsyncIteration:
raise IndexError("Index out of range")
# Check length
if index < 0:
count = 1
async for _ in streamer:
count += 1
if count != abs(index):
raise IndexError("Index out of range")
# Yield result
yield result | python | async def item(source, index):
"""Forward the ``n``th element of an asynchronous sequence.
The index can be negative and works like regular indexing.
If the index is out of range, and ``IndexError`` is raised.
"""
# Prepare
if index >= 0:
source = skip.raw(source, index)
else:
source = takelast(source, abs(index))
async with streamcontext(source) as streamer:
# Get first item
try:
result = await anext(streamer)
except StopAsyncIteration:
raise IndexError("Index out of range")
# Check length
if index < 0:
count = 1
async for _ in streamer:
count += 1
if count != abs(index):
raise IndexError("Index out of range")
# Yield result
yield result | [
"async",
"def",
"item",
"(",
"source",
",",
"index",
")",
":",
"# Prepare",
"if",
"index",
">=",
"0",
":",
"source",
"=",
"skip",
".",
"raw",
"(",
"source",
",",
"index",
")",
"else",
":",
"source",
"=",
"takelast",
"(",
"source",
",",
"abs",
"(",
... | Forward the ``n``th element of an asynchronous sequence.
The index can be negative and works like regular indexing.
If the index is out of range, and ``IndexError`` is raised. | [
"Forward",
"the",
"n",
"th",
"element",
"of",
"an",
"asynchronous",
"sequence",
"."
] | 43bdf04ab19108a3f1b5a472062e1392a26cbcf8 | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/select.py#L133-L158 | train | 37,228 |
vxgmichel/aiostream | aiostream/stream/select.py | getitem | def getitem(source, index):
"""Forward one or several items from an asynchronous sequence.
The argument can either be a slice or an integer.
See the slice and item operators for more information.
"""
if isinstance(index, builtins.slice):
return slice.raw(source, index.start, index.stop, index.step)
if isinstance(index, int):
return item.raw(source, index)
raise TypeError("Not a valid index (int or slice)") | python | def getitem(source, index):
"""Forward one or several items from an asynchronous sequence.
The argument can either be a slice or an integer.
See the slice and item operators for more information.
"""
if isinstance(index, builtins.slice):
return slice.raw(source, index.start, index.stop, index.step)
if isinstance(index, int):
return item.raw(source, index)
raise TypeError("Not a valid index (int or slice)") | [
"def",
"getitem",
"(",
"source",
",",
"index",
")",
":",
"if",
"isinstance",
"(",
"index",
",",
"builtins",
".",
"slice",
")",
":",
"return",
"slice",
".",
"raw",
"(",
"source",
",",
"index",
".",
"start",
",",
"index",
".",
"stop",
",",
"index",
"... | Forward one or several items from an asynchronous sequence.
The argument can either be a slice or an integer.
See the slice and item operators for more information. | [
"Forward",
"one",
"or",
"several",
"items",
"from",
"an",
"asynchronous",
"sequence",
"."
] | 43bdf04ab19108a3f1b5a472062e1392a26cbcf8 | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/select.py#L162-L172 | train | 37,229 |
vxgmichel/aiostream | aiostream/stream/select.py | takewhile | async def takewhile(source, func):
"""Forward an asynchronous sequence while a condition is met.
The given function takes the item as an argument and returns a boolean
corresponding to the condition to meet. The function can either be
synchronous or asynchronous.
"""
iscorofunc = asyncio.iscoroutinefunction(func)
async with streamcontext(source) as streamer:
async for item in streamer:
result = func(item)
if iscorofunc:
result = await result
if not result:
return
yield item | python | async def takewhile(source, func):
"""Forward an asynchronous sequence while a condition is met.
The given function takes the item as an argument and returns a boolean
corresponding to the condition to meet. The function can either be
synchronous or asynchronous.
"""
iscorofunc = asyncio.iscoroutinefunction(func)
async with streamcontext(source) as streamer:
async for item in streamer:
result = func(item)
if iscorofunc:
result = await result
if not result:
return
yield item | [
"async",
"def",
"takewhile",
"(",
"source",
",",
"func",
")",
":",
"iscorofunc",
"=",
"asyncio",
".",
"iscoroutinefunction",
"(",
"func",
")",
"async",
"with",
"streamcontext",
"(",
"source",
")",
"as",
"streamer",
":",
"async",
"for",
"item",
"in",
"strea... | Forward an asynchronous sequence while a condition is met.
The given function takes the item as an argument and returns a boolean
corresponding to the condition to meet. The function can either be
synchronous or asynchronous. | [
"Forward",
"an",
"asynchronous",
"sequence",
"while",
"a",
"condition",
"is",
"met",
"."
] | 43bdf04ab19108a3f1b5a472062e1392a26cbcf8 | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/select.py#L194-L209 | train | 37,230 |
vxgmichel/aiostream | aiostream/pipe.py | update_pipe_module | def update_pipe_module():
"""Populate the pipe module dynamically."""
module_dir = __all__
operators = stream.__dict__
for key, value in operators.items():
if getattr(value, 'pipe', None):
globals()[key] = value.pipe
if key not in module_dir:
module_dir.append(key) | python | def update_pipe_module():
"""Populate the pipe module dynamically."""
module_dir = __all__
operators = stream.__dict__
for key, value in operators.items():
if getattr(value, 'pipe', None):
globals()[key] = value.pipe
if key not in module_dir:
module_dir.append(key) | [
"def",
"update_pipe_module",
"(",
")",
":",
"module_dir",
"=",
"__all__",
"operators",
"=",
"stream",
".",
"__dict__",
"for",
"key",
",",
"value",
"in",
"operators",
".",
"items",
"(",
")",
":",
"if",
"getattr",
"(",
"value",
",",
"'pipe'",
",",
"None",
... | Populate the pipe module dynamically. | [
"Populate",
"the",
"pipe",
"module",
"dynamically",
"."
] | 43bdf04ab19108a3f1b5a472062e1392a26cbcf8 | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/pipe.py#L8-L16 | train | 37,231 |
vxgmichel/aiostream | aiostream/stream/transform.py | starmap | def starmap(source, func, ordered=True, task_limit=None):
"""Apply a given function to the unpacked elements of
an asynchronous sequence.
Each element is unpacked before applying the function.
The given function can either be synchronous or asynchronous.
The results can either be returned in or out of order, depending on
the corresponding ``ordered`` argument. This argument is ignored if
the provided function is synchronous.
The coroutines run concurrently but their amount can be limited using
the ``task_limit`` argument. A value of ``1`` will cause the coroutines
to run sequentially. This argument is ignored if the provided function
is synchronous.
"""
if asyncio.iscoroutinefunction(func):
async def starfunc(args):
return await func(*args)
else:
def starfunc(args):
return func(*args)
return map.raw(source, starfunc, ordered=ordered, task_limit=task_limit) | python | def starmap(source, func, ordered=True, task_limit=None):
"""Apply a given function to the unpacked elements of
an asynchronous sequence.
Each element is unpacked before applying the function.
The given function can either be synchronous or asynchronous.
The results can either be returned in or out of order, depending on
the corresponding ``ordered`` argument. This argument is ignored if
the provided function is synchronous.
The coroutines run concurrently but their amount can be limited using
the ``task_limit`` argument. A value of ``1`` will cause the coroutines
to run sequentially. This argument is ignored if the provided function
is synchronous.
"""
if asyncio.iscoroutinefunction(func):
async def starfunc(args):
return await func(*args)
else:
def starfunc(args):
return func(*args)
return map.raw(source, starfunc, ordered=ordered, task_limit=task_limit) | [
"def",
"starmap",
"(",
"source",
",",
"func",
",",
"ordered",
"=",
"True",
",",
"task_limit",
"=",
"None",
")",
":",
"if",
"asyncio",
".",
"iscoroutinefunction",
"(",
"func",
")",
":",
"async",
"def",
"starfunc",
"(",
"args",
")",
":",
"return",
"await... | Apply a given function to the unpacked elements of
an asynchronous sequence.
Each element is unpacked before applying the function.
The given function can either be synchronous or asynchronous.
The results can either be returned in or out of order, depending on
the corresponding ``ordered`` argument. This argument is ignored if
the provided function is synchronous.
The coroutines run concurrently but their amount can be limited using
the ``task_limit`` argument. A value of ``1`` will cause the coroutines
to run sequentially. This argument is ignored if the provided function
is synchronous. | [
"Apply",
"a",
"given",
"function",
"to",
"the",
"unpacked",
"elements",
"of",
"an",
"asynchronous",
"sequence",
"."
] | 43bdf04ab19108a3f1b5a472062e1392a26cbcf8 | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/transform.py#L33-L55 | train | 37,232 |
vxgmichel/aiostream | aiostream/stream/transform.py | cycle | async def cycle(source):
"""Iterate indefinitely over an asynchronous sequence.
Note: it does not perform any buffering, but re-iterate over
the same given sequence instead. If the sequence is not
re-iterable, the generator might end up looping indefinitely
without yielding any item.
"""
while True:
async with streamcontext(source) as streamer:
async for item in streamer:
yield item
# Prevent blocking while loop if the stream is empty
await asyncio.sleep(0) | python | async def cycle(source):
"""Iterate indefinitely over an asynchronous sequence.
Note: it does not perform any buffering, but re-iterate over
the same given sequence instead. If the sequence is not
re-iterable, the generator might end up looping indefinitely
without yielding any item.
"""
while True:
async with streamcontext(source) as streamer:
async for item in streamer:
yield item
# Prevent blocking while loop if the stream is empty
await asyncio.sleep(0) | [
"async",
"def",
"cycle",
"(",
"source",
")",
":",
"while",
"True",
":",
"async",
"with",
"streamcontext",
"(",
"source",
")",
"as",
"streamer",
":",
"async",
"for",
"item",
"in",
"streamer",
":",
"yield",
"item",
"# Prevent blocking while loop if the stream is e... | Iterate indefinitely over an asynchronous sequence.
Note: it does not perform any buffering, but re-iterate over
the same given sequence instead. If the sequence is not
re-iterable, the generator might end up looping indefinitely
without yielding any item. | [
"Iterate",
"indefinitely",
"over",
"an",
"asynchronous",
"sequence",
"."
] | 43bdf04ab19108a3f1b5a472062e1392a26cbcf8 | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/transform.py#L59-L72 | train | 37,233 |
vxgmichel/aiostream | examples/extra.py | random | async def random(offset=0., width=1., interval=0.1):
"""Generate a stream of random numbers."""
while True:
await asyncio.sleep(interval)
yield offset + width * random_module.random() | python | async def random(offset=0., width=1., interval=0.1):
"""Generate a stream of random numbers."""
while True:
await asyncio.sleep(interval)
yield offset + width * random_module.random() | [
"async",
"def",
"random",
"(",
"offset",
"=",
"0.",
",",
"width",
"=",
"1.",
",",
"interval",
"=",
"0.1",
")",
":",
"while",
"True",
":",
"await",
"asyncio",
".",
"sleep",
"(",
"interval",
")",
"yield",
"offset",
"+",
"width",
"*",
"random_module",
"... | Generate a stream of random numbers. | [
"Generate",
"a",
"stream",
"of",
"random",
"numbers",
"."
] | 43bdf04ab19108a3f1b5a472062e1392a26cbcf8 | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/examples/extra.py#L8-L12 | train | 37,234 |
vxgmichel/aiostream | examples/extra.py | power | async def power(source, exponent):
"""Raise the elements of an asynchronous sequence to the given power."""
async with streamcontext(source) as streamer:
async for item in streamer:
yield item ** exponent | python | async def power(source, exponent):
"""Raise the elements of an asynchronous sequence to the given power."""
async with streamcontext(source) as streamer:
async for item in streamer:
yield item ** exponent | [
"async",
"def",
"power",
"(",
"source",
",",
"exponent",
")",
":",
"async",
"with",
"streamcontext",
"(",
"source",
")",
"as",
"streamer",
":",
"async",
"for",
"item",
"in",
"streamer",
":",
"yield",
"item",
"**",
"exponent"
] | Raise the elements of an asynchronous sequence to the given power. | [
"Raise",
"the",
"elements",
"of",
"an",
"asynchronous",
"sequence",
"to",
"the",
"given",
"power",
"."
] | 43bdf04ab19108a3f1b5a472062e1392a26cbcf8 | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/examples/extra.py#L16-L20 | train | 37,235 |
vxgmichel/aiostream | aiostream/stream/time.py | spaceout | async def spaceout(source, interval):
"""Make sure the elements of an asynchronous sequence are separated
in time by the given interval.
"""
timeout = 0
loop = asyncio.get_event_loop()
async with streamcontext(source) as streamer:
async for item in streamer:
delta = timeout - loop.time()
delay = delta if delta > 0 else 0
await asyncio.sleep(delay)
yield item
timeout = loop.time() + interval | python | async def spaceout(source, interval):
"""Make sure the elements of an asynchronous sequence are separated
in time by the given interval.
"""
timeout = 0
loop = asyncio.get_event_loop()
async with streamcontext(source) as streamer:
async for item in streamer:
delta = timeout - loop.time()
delay = delta if delta > 0 else 0
await asyncio.sleep(delay)
yield item
timeout = loop.time() + interval | [
"async",
"def",
"spaceout",
"(",
"source",
",",
"interval",
")",
":",
"timeout",
"=",
"0",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"async",
"with",
"streamcontext",
"(",
"source",
")",
"as",
"streamer",
":",
"async",
"for",
"item",
"in",... | Make sure the elements of an asynchronous sequence are separated
in time by the given interval. | [
"Make",
"sure",
"the",
"elements",
"of",
"an",
"asynchronous",
"sequence",
"are",
"separated",
"in",
"time",
"by",
"the",
"given",
"interval",
"."
] | 43bdf04ab19108a3f1b5a472062e1392a26cbcf8 | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/time.py#L26-L38 | train | 37,236 |
vxgmichel/aiostream | aiostream/stream/time.py | timeout | async def timeout(source, timeout):
"""Raise a time-out if an element of the asynchronous sequence
takes too long to arrive.
Note: the timeout is not global but specific to each step of
the iteration.
"""
async with streamcontext(source) as streamer:
while True:
try:
item = await wait_for(anext(streamer), timeout)
except StopAsyncIteration:
break
else:
yield item | python | async def timeout(source, timeout):
"""Raise a time-out if an element of the asynchronous sequence
takes too long to arrive.
Note: the timeout is not global but specific to each step of
the iteration.
"""
async with streamcontext(source) as streamer:
while True:
try:
item = await wait_for(anext(streamer), timeout)
except StopAsyncIteration:
break
else:
yield item | [
"async",
"def",
"timeout",
"(",
"source",
",",
"timeout",
")",
":",
"async",
"with",
"streamcontext",
"(",
"source",
")",
"as",
"streamer",
":",
"while",
"True",
":",
"try",
":",
"item",
"=",
"await",
"wait_for",
"(",
"anext",
"(",
"streamer",
")",
","... | Raise a time-out if an element of the asynchronous sequence
takes too long to arrive.
Note: the timeout is not global but specific to each step of
the iteration. | [
"Raise",
"a",
"time",
"-",
"out",
"if",
"an",
"element",
"of",
"the",
"asynchronous",
"sequence",
"takes",
"too",
"long",
"to",
"arrive",
"."
] | 43bdf04ab19108a3f1b5a472062e1392a26cbcf8 | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/time.py#L42-L56 | train | 37,237 |
vxgmichel/aiostream | aiostream/stream/time.py | delay | async def delay(source, delay):
"""Delay the iteration of an asynchronous sequence."""
await asyncio.sleep(delay)
async with streamcontext(source) as streamer:
async for item in streamer:
yield item | python | async def delay(source, delay):
"""Delay the iteration of an asynchronous sequence."""
await asyncio.sleep(delay)
async with streamcontext(source) as streamer:
async for item in streamer:
yield item | [
"async",
"def",
"delay",
"(",
"source",
",",
"delay",
")",
":",
"await",
"asyncio",
".",
"sleep",
"(",
"delay",
")",
"async",
"with",
"streamcontext",
"(",
"source",
")",
"as",
"streamer",
":",
"async",
"for",
"item",
"in",
"streamer",
":",
"yield",
"i... | Delay the iteration of an asynchronous sequence. | [
"Delay",
"the",
"iteration",
"of",
"an",
"asynchronous",
"sequence",
"."
] | 43bdf04ab19108a3f1b5a472062e1392a26cbcf8 | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/time.py#L60-L65 | train | 37,238 |
vxgmichel/aiostream | aiostream/stream/combine.py | chain | async def chain(*sources):
"""Chain asynchronous sequences together, in the order they are given.
Note: the sequences are not iterated until it is required,
so if the operation is interrupted, the remaining sequences
will be left untouched.
"""
for source in sources:
async with streamcontext(source) as streamer:
async for item in streamer:
yield item | python | async def chain(*sources):
"""Chain asynchronous sequences together, in the order they are given.
Note: the sequences are not iterated until it is required,
so if the operation is interrupted, the remaining sequences
will be left untouched.
"""
for source in sources:
async with streamcontext(source) as streamer:
async for item in streamer:
yield item | [
"async",
"def",
"chain",
"(",
"*",
"sources",
")",
":",
"for",
"source",
"in",
"sources",
":",
"async",
"with",
"streamcontext",
"(",
"source",
")",
"as",
"streamer",
":",
"async",
"for",
"item",
"in",
"streamer",
":",
"yield",
"item"
] | Chain asynchronous sequences together, in the order they are given.
Note: the sequences are not iterated until it is required,
so if the operation is interrupted, the remaining sequences
will be left untouched. | [
"Chain",
"asynchronous",
"sequences",
"together",
"in",
"the",
"order",
"they",
"are",
"given",
"."
] | 43bdf04ab19108a3f1b5a472062e1392a26cbcf8 | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/combine.py#L18-L28 | train | 37,239 |
vxgmichel/aiostream | aiostream/stream/combine.py | zip | async def zip(*sources):
"""Combine and forward the elements of several asynchronous sequences.
Each generated value is a tuple of elements, using the same order as
their respective sources. The generation continues until the shortest
sequence is exhausted.
Note: the different sequences are awaited in parrallel, so that their
waiting times don't add up.
"""
async with AsyncExitStack() as stack:
# Handle resources
streamers = [await stack.enter_async_context(streamcontext(source))
for source in sources]
# Loop over items
while True:
try:
coros = builtins.map(anext, streamers)
items = await asyncio.gather(*coros)
except StopAsyncIteration:
break
else:
yield tuple(items) | python | async def zip(*sources):
"""Combine and forward the elements of several asynchronous sequences.
Each generated value is a tuple of elements, using the same order as
their respective sources. The generation continues until the shortest
sequence is exhausted.
Note: the different sequences are awaited in parrallel, so that their
waiting times don't add up.
"""
async with AsyncExitStack() as stack:
# Handle resources
streamers = [await stack.enter_async_context(streamcontext(source))
for source in sources]
# Loop over items
while True:
try:
coros = builtins.map(anext, streamers)
items = await asyncio.gather(*coros)
except StopAsyncIteration:
break
else:
yield tuple(items) | [
"async",
"def",
"zip",
"(",
"*",
"sources",
")",
":",
"async",
"with",
"AsyncExitStack",
"(",
")",
"as",
"stack",
":",
"# Handle resources",
"streamers",
"=",
"[",
"await",
"stack",
".",
"enter_async_context",
"(",
"streamcontext",
"(",
"source",
")",
")",
... | Combine and forward the elements of several asynchronous sequences.
Each generated value is a tuple of elements, using the same order as
their respective sources. The generation continues until the shortest
sequence is exhausted.
Note: the different sequences are awaited in parrallel, so that their
waiting times don't add up. | [
"Combine",
"and",
"forward",
"the",
"elements",
"of",
"several",
"asynchronous",
"sequences",
"."
] | 43bdf04ab19108a3f1b5a472062e1392a26cbcf8 | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/combine.py#L32-L54 | train | 37,240 |
vxgmichel/aiostream | aiostream/stream/combine.py | amap | def amap(source, corofn, *more_sources, ordered=True, task_limit=None):
"""Apply a given coroutine function to the elements of one or several
asynchronous sequences.
Each element is used as a positional argument, using the same order as
their respective sources. The generation continues until the shortest
sequence is exhausted.
The results can either be returned in or out of order, depending on
the corresponding ``ordered`` argument.
The coroutines run concurrently but their amount can be limited using
the ``task_limit`` argument. A value of ``1`` will cause the coroutines
to run sequentially.
If more than one sequence is provided, they're also awaited concurrently,
so that their waiting times don't add up.
"""
def func(*args):
return create.just(corofn(*args))
if ordered:
return advanced.concatmap.raw(
source, func, *more_sources, task_limit=task_limit)
return advanced.flatmap.raw(
source, func, *more_sources, task_limit=task_limit) | python | def amap(source, corofn, *more_sources, ordered=True, task_limit=None):
"""Apply a given coroutine function to the elements of one or several
asynchronous sequences.
Each element is used as a positional argument, using the same order as
their respective sources. The generation continues until the shortest
sequence is exhausted.
The results can either be returned in or out of order, depending on
the corresponding ``ordered`` argument.
The coroutines run concurrently but their amount can be limited using
the ``task_limit`` argument. A value of ``1`` will cause the coroutines
to run sequentially.
If more than one sequence is provided, they're also awaited concurrently,
so that their waiting times don't add up.
"""
def func(*args):
return create.just(corofn(*args))
if ordered:
return advanced.concatmap.raw(
source, func, *more_sources, task_limit=task_limit)
return advanced.flatmap.raw(
source, func, *more_sources, task_limit=task_limit) | [
"def",
"amap",
"(",
"source",
",",
"corofn",
",",
"*",
"more_sources",
",",
"ordered",
"=",
"True",
",",
"task_limit",
"=",
"None",
")",
":",
"def",
"func",
"(",
"*",
"args",
")",
":",
"return",
"create",
".",
"just",
"(",
"corofn",
"(",
"*",
"args... | Apply a given coroutine function to the elements of one or several
asynchronous sequences.
Each element is used as a positional argument, using the same order as
their respective sources. The generation continues until the shortest
sequence is exhausted.
The results can either be returned in or out of order, depending on
the corresponding ``ordered`` argument.
The coroutines run concurrently but their amount can be limited using
the ``task_limit`` argument. A value of ``1`` will cause the coroutines
to run sequentially.
If more than one sequence is provided, they're also awaited concurrently,
so that their waiting times don't add up. | [
"Apply",
"a",
"given",
"coroutine",
"function",
"to",
"the",
"elements",
"of",
"one",
"or",
"several",
"asynchronous",
"sequences",
"."
] | 43bdf04ab19108a3f1b5a472062e1392a26cbcf8 | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/combine.py#L77-L103 | train | 37,241 |
vxgmichel/aiostream | aiostream/stream/create.py | iterate | def iterate(it):
"""Generate values from a sychronous or asynchronous iterable."""
if is_async_iterable(it):
return from_async_iterable.raw(it)
if isinstance(it, Iterable):
return from_iterable.raw(it)
raise TypeError(
f"{type(it).__name__!r} object is not (async) iterable") | python | def iterate(it):
"""Generate values from a sychronous or asynchronous iterable."""
if is_async_iterable(it):
return from_async_iterable.raw(it)
if isinstance(it, Iterable):
return from_iterable.raw(it)
raise TypeError(
f"{type(it).__name__!r} object is not (async) iterable") | [
"def",
"iterate",
"(",
"it",
")",
":",
"if",
"is_async_iterable",
"(",
"it",
")",
":",
"return",
"from_async_iterable",
".",
"raw",
"(",
"it",
")",
"if",
"isinstance",
"(",
"it",
",",
"Iterable",
")",
":",
"return",
"from_iterable",
".",
"raw",
"(",
"i... | Generate values from a sychronous or asynchronous iterable. | [
"Generate",
"values",
"from",
"a",
"sychronous",
"or",
"asynchronous",
"iterable",
"."
] | 43bdf04ab19108a3f1b5a472062e1392a26cbcf8 | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/create.py#L39-L46 | train | 37,242 |
vxgmichel/aiostream | aiostream/stream/create.py | repeat | def repeat(value, times=None, *, interval=0):
"""Generate the same value a given number of times.
If ``times`` is ``None``, the value is repeated indefinitely.
An optional interval can be given to space the values out.
"""
args = () if times is None else (times,)
it = itertools.repeat(value, *args)
agen = from_iterable.raw(it)
return time.spaceout.raw(agen, interval) if interval else agen | python | def repeat(value, times=None, *, interval=0):
"""Generate the same value a given number of times.
If ``times`` is ``None``, the value is repeated indefinitely.
An optional interval can be given to space the values out.
"""
args = () if times is None else (times,)
it = itertools.repeat(value, *args)
agen = from_iterable.raw(it)
return time.spaceout.raw(agen, interval) if interval else agen | [
"def",
"repeat",
"(",
"value",
",",
"times",
"=",
"None",
",",
"*",
",",
"interval",
"=",
"0",
")",
":",
"args",
"=",
"(",
")",
"if",
"times",
"is",
"None",
"else",
"(",
"times",
",",
")",
"it",
"=",
"itertools",
".",
"repeat",
"(",
"value",
",... | Generate the same value a given number of times.
If ``times`` is ``None``, the value is repeated indefinitely.
An optional interval can be given to space the values out. | [
"Generate",
"the",
"same",
"value",
"a",
"given",
"number",
"of",
"times",
"."
] | 43bdf04ab19108a3f1b5a472062e1392a26cbcf8 | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/create.py#L96-L105 | train | 37,243 |
vxgmichel/aiostream | aiostream/stream/create.py | range | def range(*args, interval=0):
"""Generate a given range of numbers.
It supports the same arguments as the builtin function.
An optional interval can be given to space the values out.
"""
agen = from_iterable.raw(builtins.range(*args))
return time.spaceout.raw(agen, interval) if interval else agen | python | def range(*args, interval=0):
"""Generate a given range of numbers.
It supports the same arguments as the builtin function.
An optional interval can be given to space the values out.
"""
agen = from_iterable.raw(builtins.range(*args))
return time.spaceout.raw(agen, interval) if interval else agen | [
"def",
"range",
"(",
"*",
"args",
",",
"interval",
"=",
"0",
")",
":",
"agen",
"=",
"from_iterable",
".",
"raw",
"(",
"builtins",
".",
"range",
"(",
"*",
"args",
")",
")",
"return",
"time",
".",
"spaceout",
".",
"raw",
"(",
"agen",
",",
"interval",... | Generate a given range of numbers.
It supports the same arguments as the builtin function.
An optional interval can be given to space the values out. | [
"Generate",
"a",
"given",
"range",
"of",
"numbers",
"."
] | 43bdf04ab19108a3f1b5a472062e1392a26cbcf8 | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/create.py#L111-L118 | train | 37,244 |
vxgmichel/aiostream | aiostream/stream/create.py | count | def count(start=0, step=1, *, interval=0):
"""Generate consecutive numbers indefinitely.
Optional starting point and increment can be defined,
respectively defaulting to ``0`` and ``1``.
An optional interval can be given to space the values out.
"""
agen = from_iterable.raw(itertools.count(start, step))
return time.spaceout.raw(agen, interval) if interval else agen | python | def count(start=0, step=1, *, interval=0):
"""Generate consecutive numbers indefinitely.
Optional starting point and increment can be defined,
respectively defaulting to ``0`` and ``1``.
An optional interval can be given to space the values out.
"""
agen = from_iterable.raw(itertools.count(start, step))
return time.spaceout.raw(agen, interval) if interval else agen | [
"def",
"count",
"(",
"start",
"=",
"0",
",",
"step",
"=",
"1",
",",
"*",
",",
"interval",
"=",
"0",
")",
":",
"agen",
"=",
"from_iterable",
".",
"raw",
"(",
"itertools",
".",
"count",
"(",
"start",
",",
"step",
")",
")",
"return",
"time",
".",
... | Generate consecutive numbers indefinitely.
Optional starting point and increment can be defined,
respectively defaulting to ``0`` and ``1``.
An optional interval can be given to space the values out. | [
"Generate",
"consecutive",
"numbers",
"indefinitely",
"."
] | 43bdf04ab19108a3f1b5a472062e1392a26cbcf8 | https://github.com/vxgmichel/aiostream/blob/43bdf04ab19108a3f1b5a472062e1392a26cbcf8/aiostream/stream/create.py#L122-L131 | train | 37,245 |
Dynatrace/OneAgent-SDK-for-Python | src/oneagent/sdk/tracers.py | Tracer.end | def end(self):
'''Ends the tracer.
May be called in any state. Transitions the state to ended and releases
any SDK resources owned by this tracer (this includes only internal
resources, things like passed-in
:class:`oneagent.common.DbInfoHandle` need to be released manually).
Prefer using the tracer as a context manager (i.e., with a
:code:`with`-block) instead of manually calling this method.
'''
if self.handle is not None:
self.nsdk.tracer_end(self.handle)
self.handle = None | python | def end(self):
'''Ends the tracer.
May be called in any state. Transitions the state to ended and releases
any SDK resources owned by this tracer (this includes only internal
resources, things like passed-in
:class:`oneagent.common.DbInfoHandle` need to be released manually).
Prefer using the tracer as a context manager (i.e., with a
:code:`with`-block) instead of manually calling this method.
'''
if self.handle is not None:
self.nsdk.tracer_end(self.handle)
self.handle = None | [
"def",
"end",
"(",
"self",
")",
":",
"if",
"self",
".",
"handle",
"is",
"not",
"None",
":",
"self",
".",
"nsdk",
".",
"tracer_end",
"(",
"self",
".",
"handle",
")",
"self",
".",
"handle",
"=",
"None"
] | Ends the tracer.
May be called in any state. Transitions the state to ended and releases
any SDK resources owned by this tracer (this includes only internal
resources, things like passed-in
:class:`oneagent.common.DbInfoHandle` need to be released manually).
Prefer using the tracer as a context manager (i.e., with a
:code:`with`-block) instead of manually calling this method. | [
"Ends",
"the",
"tracer",
"."
] | f7b121b492f25b1c5b27316798e1a70b6be2bd01 | https://github.com/Dynatrace/OneAgent-SDK-for-Python/blob/f7b121b492f25b1c5b27316798e1a70b6be2bd01/src/oneagent/sdk/tracers.py#L113-L126 | train | 37,246 |
Dynatrace/OneAgent-SDK-for-Python | src/oneagent/sdk/__init__.py | _get_kvc | def _get_kvc(kv_arg):
'''Returns a tuple keys, values, count for kv_arg (which can be a dict or a
tuple containing keys, values and optinally count.'''
if isinstance(kv_arg, Mapping):
return six.iterkeys(kv_arg), six.itervalues(kv_arg), len(kv_arg)
assert 2 <= len(kv_arg) <= 3, \
'Argument must be a mapping or a sequence (keys, values, [len])'
return (
kv_arg[0],
kv_arg[1],
kv_arg[2] if len(kv_arg) == 3 else len(kv_arg[0])) | python | def _get_kvc(kv_arg):
'''Returns a tuple keys, values, count for kv_arg (which can be a dict or a
tuple containing keys, values and optinally count.'''
if isinstance(kv_arg, Mapping):
return six.iterkeys(kv_arg), six.itervalues(kv_arg), len(kv_arg)
assert 2 <= len(kv_arg) <= 3, \
'Argument must be a mapping or a sequence (keys, values, [len])'
return (
kv_arg[0],
kv_arg[1],
kv_arg[2] if len(kv_arg) == 3 else len(kv_arg[0])) | [
"def",
"_get_kvc",
"(",
"kv_arg",
")",
":",
"if",
"isinstance",
"(",
"kv_arg",
",",
"Mapping",
")",
":",
"return",
"six",
".",
"iterkeys",
"(",
"kv_arg",
")",
",",
"six",
".",
"itervalues",
"(",
"kv_arg",
")",
",",
"len",
"(",
"kv_arg",
")",
"assert"... | Returns a tuple keys, values, count for kv_arg (which can be a dict or a
tuple containing keys, values and optinally count. | [
"Returns",
"a",
"tuple",
"keys",
"values",
"count",
"for",
"kv_arg",
"(",
"which",
"can",
"be",
"a",
"dict",
"or",
"a",
"tuple",
"containing",
"keys",
"values",
"and",
"optinally",
"count",
"."
] | f7b121b492f25b1c5b27316798e1a70b6be2bd01 | https://github.com/Dynatrace/OneAgent-SDK-for-Python/blob/f7b121b492f25b1c5b27316798e1a70b6be2bd01/src/oneagent/sdk/__init__.py#L57-L67 | train | 37,247 |
Dynatrace/OneAgent-SDK-for-Python | src/oneagent/sdk/__init__.py | SDK.trace_sql_database_request | def trace_sql_database_request(self, database, sql):
'''Create a tracer for the given database info and SQL statement.
:param DbInfoHandle database: Database information (see
:meth:`create_database_info`).
:param str sql: The SQL statement to trace.
:rtype: tracers.DatabaseRequestTracer
'''
assert isinstance(database, DbInfoHandle)
return tracers.DatabaseRequestTracer(
self._nsdk,
self._nsdk.databaserequesttracer_create_sql(database.handle, sql)) | python | def trace_sql_database_request(self, database, sql):
'''Create a tracer for the given database info and SQL statement.
:param DbInfoHandle database: Database information (see
:meth:`create_database_info`).
:param str sql: The SQL statement to trace.
:rtype: tracers.DatabaseRequestTracer
'''
assert isinstance(database, DbInfoHandle)
return tracers.DatabaseRequestTracer(
self._nsdk,
self._nsdk.databaserequesttracer_create_sql(database.handle, sql)) | [
"def",
"trace_sql_database_request",
"(",
"self",
",",
"database",
",",
"sql",
")",
":",
"assert",
"isinstance",
"(",
"database",
",",
"DbInfoHandle",
")",
"return",
"tracers",
".",
"DatabaseRequestTracer",
"(",
"self",
".",
"_nsdk",
",",
"self",
".",
"_nsdk",... | Create a tracer for the given database info and SQL statement.
:param DbInfoHandle database: Database information (see
:meth:`create_database_info`).
:param str sql: The SQL statement to trace.
:rtype: tracers.DatabaseRequestTracer | [
"Create",
"a",
"tracer",
"for",
"the",
"given",
"database",
"info",
"and",
"SQL",
"statement",
"."
] | f7b121b492f25b1c5b27316798e1a70b6be2bd01 | https://github.com/Dynatrace/OneAgent-SDK-for-Python/blob/f7b121b492f25b1c5b27316798e1a70b6be2bd01/src/oneagent/sdk/__init__.py#L136-L147 | train | 37,248 |
Dynatrace/OneAgent-SDK-for-Python | src/oneagent/sdk/__init__.py | SDK.trace_incoming_web_request | def trace_incoming_web_request(
self,
webapp_info,
url,
method,
headers=None,
remote_address=None,
str_tag=None,
byte_tag=None):
'''Create a tracer for an incoming webrequest.
:param WebapplicationInfoHandle webapp_info: Web application
information (see :meth:`create_web_application_info`).
:param str url: The requested URL (including scheme, hostname/port,
path and query).
:param str method: The HTTP method of the request (e.g., GET or
POST).
:param headers: The HTTP headers of the request. Can be either a
dictionary mapping header name to value (:class:`str` to
:class:`str`) or a tuple containing a sequence of string header
names as first element, an equally long sequence of
corresponding values as second element and optionally a count as
third element (this will default to the :func:`len` of the
header names).
Some headers can appear multiple times in an HTTP request. To
capture all the values, either use the tuple-form and provide
the name and corresponding values for each, or if possible for
that particular header, set the value to an appropriately
concatenated string.
.. warning:: If you use Python 2, be sure to use the UTF-8 encoding
or the :class:`unicode` type! See :ref:`here
<http-encoding-warning>` for more information.
:type headers: \
dict[str, str] or \
tuple[~typing.Collection[str], ~typing.Collection[str]] or \
tuple[~typing.Iterable[str], ~typing.Iterable[str], int]]
:param str remote_address: The remote (client) IP address (of the
peer of the socket connection via which the request was
received).
The remote address is useful to gain information about load
balancers, proxies and ultimately the end user that is sending
the request.
For the other parameters, see :ref:`tagging`.
:rtype: tracers.IncomingWebRequestTracer
'''
assert isinstance(webapp_info, WebapplicationInfoHandle)
result = tracers.IncomingWebRequestTracer(
self._nsdk,
self._nsdk.incomingwebrequesttracer_create(
webapp_info.handle, url, method))
if not result:
return result
try:
if headers:
self._nsdk.incomingwebrequesttracer_add_request_headers(
result.handle, *_get_kvc(headers))
if remote_address:
self._nsdk.incomingwebrequesttracer_set_remote_address(
result.handle, remote_address)
self._applytag(result, str_tag, byte_tag)
except:
result.end()
raise
return result | python | def trace_incoming_web_request(
self,
webapp_info,
url,
method,
headers=None,
remote_address=None,
str_tag=None,
byte_tag=None):
'''Create a tracer for an incoming webrequest.
:param WebapplicationInfoHandle webapp_info: Web application
information (see :meth:`create_web_application_info`).
:param str url: The requested URL (including scheme, hostname/port,
path and query).
:param str method: The HTTP method of the request (e.g., GET or
POST).
:param headers: The HTTP headers of the request. Can be either a
dictionary mapping header name to value (:class:`str` to
:class:`str`) or a tuple containing a sequence of string header
names as first element, an equally long sequence of
corresponding values as second element and optionally a count as
third element (this will default to the :func:`len` of the
header names).
Some headers can appear multiple times in an HTTP request. To
capture all the values, either use the tuple-form and provide
the name and corresponding values for each, or if possible for
that particular header, set the value to an appropriately
concatenated string.
.. warning:: If you use Python 2, be sure to use the UTF-8 encoding
or the :class:`unicode` type! See :ref:`here
<http-encoding-warning>` for more information.
:type headers: \
dict[str, str] or \
tuple[~typing.Collection[str], ~typing.Collection[str]] or \
tuple[~typing.Iterable[str], ~typing.Iterable[str], int]]
:param str remote_address: The remote (client) IP address (of the
peer of the socket connection via which the request was
received).
The remote address is useful to gain information about load
balancers, proxies and ultimately the end user that is sending
the request.
For the other parameters, see :ref:`tagging`.
:rtype: tracers.IncomingWebRequestTracer
'''
assert isinstance(webapp_info, WebapplicationInfoHandle)
result = tracers.IncomingWebRequestTracer(
self._nsdk,
self._nsdk.incomingwebrequesttracer_create(
webapp_info.handle, url, method))
if not result:
return result
try:
if headers:
self._nsdk.incomingwebrequesttracer_add_request_headers(
result.handle, *_get_kvc(headers))
if remote_address:
self._nsdk.incomingwebrequesttracer_set_remote_address(
result.handle, remote_address)
self._applytag(result, str_tag, byte_tag)
except:
result.end()
raise
return result | [
"def",
"trace_incoming_web_request",
"(",
"self",
",",
"webapp_info",
",",
"url",
",",
"method",
",",
"headers",
"=",
"None",
",",
"remote_address",
"=",
"None",
",",
"str_tag",
"=",
"None",
",",
"byte_tag",
"=",
"None",
")",
":",
"assert",
"isinstance",
"... | Create a tracer for an incoming webrequest.
:param WebapplicationInfoHandle webapp_info: Web application
information (see :meth:`create_web_application_info`).
:param str url: The requested URL (including scheme, hostname/port,
path and query).
:param str method: The HTTP method of the request (e.g., GET or
POST).
:param headers: The HTTP headers of the request. Can be either a
dictionary mapping header name to value (:class:`str` to
:class:`str`) or a tuple containing a sequence of string header
names as first element, an equally long sequence of
corresponding values as second element and optionally a count as
third element (this will default to the :func:`len` of the
header names).
Some headers can appear multiple times in an HTTP request. To
capture all the values, either use the tuple-form and provide
the name and corresponding values for each, or if possible for
that particular header, set the value to an appropriately
concatenated string.
.. warning:: If you use Python 2, be sure to use the UTF-8 encoding
or the :class:`unicode` type! See :ref:`here
<http-encoding-warning>` for more information.
:type headers: \
dict[str, str] or \
tuple[~typing.Collection[str], ~typing.Collection[str]] or \
tuple[~typing.Iterable[str], ~typing.Iterable[str], int]]
:param str remote_address: The remote (client) IP address (of the
peer of the socket connection via which the request was
received).
The remote address is useful to gain information about load
balancers, proxies and ultimately the end user that is sending
the request.
For the other parameters, see :ref:`tagging`.
:rtype: tracers.IncomingWebRequestTracer | [
"Create",
"a",
"tracer",
"for",
"an",
"incoming",
"webrequest",
"."
] | f7b121b492f25b1c5b27316798e1a70b6be2bd01 | https://github.com/Dynatrace/OneAgent-SDK-for-Python/blob/f7b121b492f25b1c5b27316798e1a70b6be2bd01/src/oneagent/sdk/__init__.py#L149-L217 | train | 37,249 |
Dynatrace/OneAgent-SDK-for-Python | src/oneagent/sdk/__init__.py | SDK.trace_outgoing_web_request | def trace_outgoing_web_request(self, url, method, headers=None):
'''Create a tracer for an outgoing webrequest.
:param str url: The request URL (including scheme, hostname/port, path and query).
:param str method: The HTTP method of the request (e.g., GET or POST).
:param headers: The HTTP headers of the request. Can be either a
dictionary mapping header name to value (:class:`str` to
:class:`str`) or a tuple containing a sequence of string header
names as first element, an equally long sequence of
corresponding values as second element and optionally a count as
third element (this will default to the :func:`len` of the
header names).
Some headers can appear multiple times in an HTTP request. To
capture all the values, either use the tuple-form and provide
the name and corresponding values for each, or if possible for
that particular header, set the value to an appropriately
concatenated string.
.. warning:: If you use Python 2, be sure to use the UTF-8 encoding
or the :class:`unicode` type! See :ref:`here
<http-encoding-warning>` for more information.
:type headers: \
dict[str, str] or \
tuple[~typing.Collection[str], ~typing.Collection[str]] or \
tuple[~typing.Iterable[str], ~typing.Iterable[str], int]]
:rtype: tracers.OutgoingWebRequestTracer
.. versionadded:: 1.1.0
'''
result = tracers.OutgoingWebRequestTracer(
self._nsdk, self._nsdk.outgoingwebrequesttracer_create(url, method))
if not result:
return result
try:
if headers:
self._nsdk.outgoingwebrequesttracer_add_request_headers(result.handle,
*_get_kvc(headers))
except:
result.end()
raise
return result | python | def trace_outgoing_web_request(self, url, method, headers=None):
'''Create a tracer for an outgoing webrequest.
:param str url: The request URL (including scheme, hostname/port, path and query).
:param str method: The HTTP method of the request (e.g., GET or POST).
:param headers: The HTTP headers of the request. Can be either a
dictionary mapping header name to value (:class:`str` to
:class:`str`) or a tuple containing a sequence of string header
names as first element, an equally long sequence of
corresponding values as second element and optionally a count as
third element (this will default to the :func:`len` of the
header names).
Some headers can appear multiple times in an HTTP request. To
capture all the values, either use the tuple-form and provide
the name and corresponding values for each, or if possible for
that particular header, set the value to an appropriately
concatenated string.
.. warning:: If you use Python 2, be sure to use the UTF-8 encoding
or the :class:`unicode` type! See :ref:`here
<http-encoding-warning>` for more information.
:type headers: \
dict[str, str] or \
tuple[~typing.Collection[str], ~typing.Collection[str]] or \
tuple[~typing.Iterable[str], ~typing.Iterable[str], int]]
:rtype: tracers.OutgoingWebRequestTracer
.. versionadded:: 1.1.0
'''
result = tracers.OutgoingWebRequestTracer(
self._nsdk, self._nsdk.outgoingwebrequesttracer_create(url, method))
if not result:
return result
try:
if headers:
self._nsdk.outgoingwebrequesttracer_add_request_headers(result.handle,
*_get_kvc(headers))
except:
result.end()
raise
return result | [
"def",
"trace_outgoing_web_request",
"(",
"self",
",",
"url",
",",
"method",
",",
"headers",
"=",
"None",
")",
":",
"result",
"=",
"tracers",
".",
"OutgoingWebRequestTracer",
"(",
"self",
".",
"_nsdk",
",",
"self",
".",
"_nsdk",
".",
"outgoingwebrequesttracer_... | Create a tracer for an outgoing webrequest.
:param str url: The request URL (including scheme, hostname/port, path and query).
:param str method: The HTTP method of the request (e.g., GET or POST).
:param headers: The HTTP headers of the request. Can be either a
dictionary mapping header name to value (:class:`str` to
:class:`str`) or a tuple containing a sequence of string header
names as first element, an equally long sequence of
corresponding values as second element and optionally a count as
third element (this will default to the :func:`len` of the
header names).
Some headers can appear multiple times in an HTTP request. To
capture all the values, either use the tuple-form and provide
the name and corresponding values for each, or if possible for
that particular header, set the value to an appropriately
concatenated string.
.. warning:: If you use Python 2, be sure to use the UTF-8 encoding
or the :class:`unicode` type! See :ref:`here
<http-encoding-warning>` for more information.
:type headers: \
dict[str, str] or \
tuple[~typing.Collection[str], ~typing.Collection[str]] or \
tuple[~typing.Iterable[str], ~typing.Iterable[str], int]]
:rtype: tracers.OutgoingWebRequestTracer
.. versionadded:: 1.1.0 | [
"Create",
"a",
"tracer",
"for",
"an",
"outgoing",
"webrequest",
"."
] | f7b121b492f25b1c5b27316798e1a70b6be2bd01 | https://github.com/Dynatrace/OneAgent-SDK-for-Python/blob/f7b121b492f25b1c5b27316798e1a70b6be2bd01/src/oneagent/sdk/__init__.py#L219-L264 | train | 37,250 |
Dynatrace/OneAgent-SDK-for-Python | src/oneagent/sdk/__init__.py | SDK.trace_outgoing_remote_call | def trace_outgoing_remote_call(
self,
method,
service,
endpoint,
channel,
protocol_name=None):
'''Creates a tracer for outgoing remote calls.
:param str method: The name of the service method/operation.
:param str service: The name of the service class/type.
:param str endpoint: A string identifying the "instance" of the the
service. See also `the general documentation on service
endpoints`__.
:param Channel channel: The channel used to communicate with the
service.
:param str protocol_name: The name of the remoting protocol (on top of
the communication protocol specified in :code:`channel.type_`.) that
is used to to communicate with the service (e.g., RMI, Protobuf,
...).
__ \
https://github.com/Dynatrace/OneAgent-SDK#common-concepts-service-endpoints-and-communication-endpoints
:rtype: tracers.OutgoingRemoteCallTracer
'''
result = tracers.OutgoingRemoteCallTracer(
self._nsdk,
self._nsdk.outgoingremotecalltracer_create(
method,
service,
endpoint,
channel.type_,
channel.endpoint))
if protocol_name is not None:
self._nsdk.outgoingremotecalltracer_set_protocol_name(
result.handle, protocol_name)
return result | python | def trace_outgoing_remote_call(
self,
method,
service,
endpoint,
channel,
protocol_name=None):
'''Creates a tracer for outgoing remote calls.
:param str method: The name of the service method/operation.
:param str service: The name of the service class/type.
:param str endpoint: A string identifying the "instance" of the the
service. See also `the general documentation on service
endpoints`__.
:param Channel channel: The channel used to communicate with the
service.
:param str protocol_name: The name of the remoting protocol (on top of
the communication protocol specified in :code:`channel.type_`.) that
is used to to communicate with the service (e.g., RMI, Protobuf,
...).
__ \
https://github.com/Dynatrace/OneAgent-SDK#common-concepts-service-endpoints-and-communication-endpoints
:rtype: tracers.OutgoingRemoteCallTracer
'''
result = tracers.OutgoingRemoteCallTracer(
self._nsdk,
self._nsdk.outgoingremotecalltracer_create(
method,
service,
endpoint,
channel.type_,
channel.endpoint))
if protocol_name is not None:
self._nsdk.outgoingremotecalltracer_set_protocol_name(
result.handle, protocol_name)
return result | [
"def",
"trace_outgoing_remote_call",
"(",
"self",
",",
"method",
",",
"service",
",",
"endpoint",
",",
"channel",
",",
"protocol_name",
"=",
"None",
")",
":",
"result",
"=",
"tracers",
".",
"OutgoingRemoteCallTracer",
"(",
"self",
".",
"_nsdk",
",",
"self",
... | Creates a tracer for outgoing remote calls.
:param str method: The name of the service method/operation.
:param str service: The name of the service class/type.
:param str endpoint: A string identifying the "instance" of the the
service. See also `the general documentation on service
endpoints`__.
:param Channel channel: The channel used to communicate with the
service.
:param str protocol_name: The name of the remoting protocol (on top of
the communication protocol specified in :code:`channel.type_`.) that
is used to to communicate with the service (e.g., RMI, Protobuf,
...).
__ \
https://github.com/Dynatrace/OneAgent-SDK#common-concepts-service-endpoints-and-communication-endpoints
:rtype: tracers.OutgoingRemoteCallTracer | [
"Creates",
"a",
"tracer",
"for",
"outgoing",
"remote",
"calls",
"."
] | f7b121b492f25b1c5b27316798e1a70b6be2bd01 | https://github.com/Dynatrace/OneAgent-SDK-for-Python/blob/f7b121b492f25b1c5b27316798e1a70b6be2bd01/src/oneagent/sdk/__init__.py#L266-L303 | train | 37,251 |
Dynatrace/OneAgent-SDK-for-Python | src/oneagent/sdk/__init__.py | SDK.trace_incoming_remote_call | def trace_incoming_remote_call(
self,
method,
name,
endpoint,
protocol_name=None,
str_tag=None,
byte_tag=None):
'''Creates a tracer for incoming remote calls.
For the parameters, see :ref:`tagging` (:code:`str_tag` and
:code:`byte_tag`) and :meth:`trace_outgoing_remote_call` (all others).
:rtype: tracers.IncomingRemoteCallTracer
'''
result = tracers.IncomingRemoteCallTracer(
self._nsdk,
self._nsdk.incomingremotecalltracer_create(method, name, endpoint))
if protocol_name is not None:
self._nsdk.incomingremotecalltracer_set_protocol_name(
result.handle, protocol_name)
self._applytag(result, str_tag, byte_tag)
return result | python | def trace_incoming_remote_call(
self,
method,
name,
endpoint,
protocol_name=None,
str_tag=None,
byte_tag=None):
'''Creates a tracer for incoming remote calls.
For the parameters, see :ref:`tagging` (:code:`str_tag` and
:code:`byte_tag`) and :meth:`trace_outgoing_remote_call` (all others).
:rtype: tracers.IncomingRemoteCallTracer
'''
result = tracers.IncomingRemoteCallTracer(
self._nsdk,
self._nsdk.incomingremotecalltracer_create(method, name, endpoint))
if protocol_name is not None:
self._nsdk.incomingremotecalltracer_set_protocol_name(
result.handle, protocol_name)
self._applytag(result, str_tag, byte_tag)
return result | [
"def",
"trace_incoming_remote_call",
"(",
"self",
",",
"method",
",",
"name",
",",
"endpoint",
",",
"protocol_name",
"=",
"None",
",",
"str_tag",
"=",
"None",
",",
"byte_tag",
"=",
"None",
")",
":",
"result",
"=",
"tracers",
".",
"IncomingRemoteCallTracer",
... | Creates a tracer for incoming remote calls.
For the parameters, see :ref:`tagging` (:code:`str_tag` and
:code:`byte_tag`) and :meth:`trace_outgoing_remote_call` (all others).
:rtype: tracers.IncomingRemoteCallTracer | [
"Creates",
"a",
"tracer",
"for",
"incoming",
"remote",
"calls",
"."
] | f7b121b492f25b1c5b27316798e1a70b6be2bd01 | https://github.com/Dynatrace/OneAgent-SDK-for-Python/blob/f7b121b492f25b1c5b27316798e1a70b6be2bd01/src/oneagent/sdk/__init__.py#L305-L327 | train | 37,252 |
Dynatrace/OneAgent-SDK-for-Python | src/oneagent/sdk/__init__.py | SDK.trace_in_process_link | def trace_in_process_link(self, link_bytes):
'''Creates a tracer for tracing asynchronous related processing in the same process.
For more information see :meth:`create_in_process_link`.
:param bytes link_bytes: An in-process link created using :meth:`create_in_process_link`.
:rtype: tracers.InProcessLinkTracer
.. versionadded:: 1.1.0
'''
return tracers.InProcessLinkTracer(self._nsdk,
self._nsdk.trace_in_process_link(link_bytes)) | python | def trace_in_process_link(self, link_bytes):
'''Creates a tracer for tracing asynchronous related processing in the same process.
For more information see :meth:`create_in_process_link`.
:param bytes link_bytes: An in-process link created using :meth:`create_in_process_link`.
:rtype: tracers.InProcessLinkTracer
.. versionadded:: 1.1.0
'''
return tracers.InProcessLinkTracer(self._nsdk,
self._nsdk.trace_in_process_link(link_bytes)) | [
"def",
"trace_in_process_link",
"(",
"self",
",",
"link_bytes",
")",
":",
"return",
"tracers",
".",
"InProcessLinkTracer",
"(",
"self",
".",
"_nsdk",
",",
"self",
".",
"_nsdk",
".",
"trace_in_process_link",
"(",
"link_bytes",
")",
")"
] | Creates a tracer for tracing asynchronous related processing in the same process.
For more information see :meth:`create_in_process_link`.
:param bytes link_bytes: An in-process link created using :meth:`create_in_process_link`.
:rtype: tracers.InProcessLinkTracer
.. versionadded:: 1.1.0 | [
"Creates",
"a",
"tracer",
"for",
"tracing",
"asynchronous",
"related",
"processing",
"in",
"the",
"same",
"process",
"."
] | f7b121b492f25b1c5b27316798e1a70b6be2bd01 | https://github.com/Dynatrace/OneAgent-SDK-for-Python/blob/f7b121b492f25b1c5b27316798e1a70b6be2bd01/src/oneagent/sdk/__init__.py#L357-L369 | train | 37,253 |
Dynatrace/OneAgent-SDK-for-Python | src/oneagent/sdk/__init__.py | SDK.add_custom_request_attribute | def add_custom_request_attribute(self, key, value):
'''Adds a custom request attribute to the current active tracer.
:param str key: The name of the custom request attribute, the name is mandatory and
may not be None.
:param value: The value of the custom request attribute. Currently supported types
are integer, float and string values. The value is mandatory and may
not be None.
:type value: str or int or float
.. versionadded:: 1.1.0
'''
if isinstance(value, int):
self._nsdk.customrequestattribute_add_integer(key, value)
elif isinstance(value, float):
self._nsdk.customrequestattribute_add_float(key, value)
elif isinstance(value, six.string_types):
self._nsdk.customrequestattribute_add_string(key, value)
else:
warn = self._nsdk.agent_get_logging_callback()
if warn:
warn('Can\'t add custom request attribute \'{0}\' '
'because the value type \'{1}\' is not supported!'.format(key, type(value))) | python | def add_custom_request_attribute(self, key, value):
'''Adds a custom request attribute to the current active tracer.
:param str key: The name of the custom request attribute, the name is mandatory and
may not be None.
:param value: The value of the custom request attribute. Currently supported types
are integer, float and string values. The value is mandatory and may
not be None.
:type value: str or int or float
.. versionadded:: 1.1.0
'''
if isinstance(value, int):
self._nsdk.customrequestattribute_add_integer(key, value)
elif isinstance(value, float):
self._nsdk.customrequestattribute_add_float(key, value)
elif isinstance(value, six.string_types):
self._nsdk.customrequestattribute_add_string(key, value)
else:
warn = self._nsdk.agent_get_logging_callback()
if warn:
warn('Can\'t add custom request attribute \'{0}\' '
'because the value type \'{1}\' is not supported!'.format(key, type(value))) | [
"def",
"add_custom_request_attribute",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"int",
")",
":",
"self",
".",
"_nsdk",
".",
"customrequestattribute_add_integer",
"(",
"key",
",",
"value",
")",
"elif",
"isinstanc... | Adds a custom request attribute to the current active tracer.
:param str key: The name of the custom request attribute, the name is mandatory and
may not be None.
:param value: The value of the custom request attribute. Currently supported types
are integer, float and string values. The value is mandatory and may
not be None.
:type value: str or int or float
.. versionadded:: 1.1.0 | [
"Adds",
"a",
"custom",
"request",
"attribute",
"to",
"the",
"current",
"active",
"tracer",
"."
] | f7b121b492f25b1c5b27316798e1a70b6be2bd01 | https://github.com/Dynatrace/OneAgent-SDK-for-Python/blob/f7b121b492f25b1c5b27316798e1a70b6be2bd01/src/oneagent/sdk/__init__.py#L430-L453 | train | 37,254 |
Dynatrace/OneAgent-SDK-for-Python | src/oneagent/common.py | SDKHandleBase.close | def close(self):
'''Closes the handle, if it is still open.
Usually, you should prefer using the handle as a context manager to
calling :meth:`close` manually.'''
if self.handle is not None:
self.close_handle(self.nsdk, self.handle)
self.handle = None | python | def close(self):
'''Closes the handle, if it is still open.
Usually, you should prefer using the handle as a context manager to
calling :meth:`close` manually.'''
if self.handle is not None:
self.close_handle(self.nsdk, self.handle)
self.handle = None | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"handle",
"is",
"not",
"None",
":",
"self",
".",
"close_handle",
"(",
"self",
".",
"nsdk",
",",
"self",
".",
"handle",
")",
"self",
".",
"handle",
"=",
"None"
] | Closes the handle, if it is still open.
Usually, you should prefer using the handle as a context manager to
calling :meth:`close` manually. | [
"Closes",
"the",
"handle",
"if",
"it",
"is",
"still",
"open",
"."
] | f7b121b492f25b1c5b27316798e1a70b6be2bd01 | https://github.com/Dynatrace/OneAgent-SDK-for-Python/blob/f7b121b492f25b1c5b27316798e1a70b6be2bd01/src/oneagent/common.py#L285-L292 | train | 37,255 |
Dynatrace/OneAgent-SDK-for-Python | src/oneagent/__init__.py | initialize | def initialize(sdkopts=(), sdklibname=None):
'''Attempts to initialize the SDK with the specified options.
Even if initialization fails, a dummy SDK will be available so that SDK
functions can be called but will do nothing.
If you call this function multiple times, you must call :func:`shutdown`
just as many times. The options from all but the first :code:`initialize` call
will be ignored (the return value will have the
:data:`InitResult.STATUS_ALREADY_INITIALIZED` status code in that case).
:param sdkopts: A sequence of strings of the form
:samp:`{NAME}={VALUE}` that set the given SDK options. Igored in all but
the first :code:`initialize` call.
:type sdkopts: ~typing.Iterable[str]
:param str sdklibname: The file or directory name of the native C SDK
DLL. If None, the shared library packaged directly with the agent is
used. Using a value other than None is only acceptable for debugging.
You are responsible for providing a native SDK version that matches the
Python SDK version.
:rtype: .InitResult
'''
global _sdk_ref_count #pylint:disable=global-statement
global _sdk_instance #pylint:disable=global-statement
with _sdk_ref_lk:
logger.debug("initialize: ref count = %d", _sdk_ref_count)
result = _try_init_noref(sdkopts, sdklibname)
if _sdk_instance is None:
_sdk_instance = SDK(try_get_sdk())
_sdk_ref_count += 1
return result | python | def initialize(sdkopts=(), sdklibname=None):
'''Attempts to initialize the SDK with the specified options.
Even if initialization fails, a dummy SDK will be available so that SDK
functions can be called but will do nothing.
If you call this function multiple times, you must call :func:`shutdown`
just as many times. The options from all but the first :code:`initialize` call
will be ignored (the return value will have the
:data:`InitResult.STATUS_ALREADY_INITIALIZED` status code in that case).
:param sdkopts: A sequence of strings of the form
:samp:`{NAME}={VALUE}` that set the given SDK options. Igored in all but
the first :code:`initialize` call.
:type sdkopts: ~typing.Iterable[str]
:param str sdklibname: The file or directory name of the native C SDK
DLL. If None, the shared library packaged directly with the agent is
used. Using a value other than None is only acceptable for debugging.
You are responsible for providing a native SDK version that matches the
Python SDK version.
:rtype: .InitResult
'''
global _sdk_ref_count #pylint:disable=global-statement
global _sdk_instance #pylint:disable=global-statement
with _sdk_ref_lk:
logger.debug("initialize: ref count = %d", _sdk_ref_count)
result = _try_init_noref(sdkopts, sdklibname)
if _sdk_instance is None:
_sdk_instance = SDK(try_get_sdk())
_sdk_ref_count += 1
return result | [
"def",
"initialize",
"(",
"sdkopts",
"=",
"(",
")",
",",
"sdklibname",
"=",
"None",
")",
":",
"global",
"_sdk_ref_count",
"#pylint:disable=global-statement",
"global",
"_sdk_instance",
"#pylint:disable=global-statement",
"with",
"_sdk_ref_lk",
":",
"logger",
".",
"deb... | Attempts to initialize the SDK with the specified options.
Even if initialization fails, a dummy SDK will be available so that SDK
functions can be called but will do nothing.
If you call this function multiple times, you must call :func:`shutdown`
just as many times. The options from all but the first :code:`initialize` call
will be ignored (the return value will have the
:data:`InitResult.STATUS_ALREADY_INITIALIZED` status code in that case).
:param sdkopts: A sequence of strings of the form
:samp:`{NAME}={VALUE}` that set the given SDK options. Igored in all but
the first :code:`initialize` call.
:type sdkopts: ~typing.Iterable[str]
:param str sdklibname: The file or directory name of the native C SDK
DLL. If None, the shared library packaged directly with the agent is
used. Using a value other than None is only acceptable for debugging.
You are responsible for providing a native SDK version that matches the
Python SDK version.
:rtype: .InitResult | [
"Attempts",
"to",
"initialize",
"the",
"SDK",
"with",
"the",
"specified",
"options",
"."
] | f7b121b492f25b1c5b27316798e1a70b6be2bd01 | https://github.com/Dynatrace/OneAgent-SDK-for-Python/blob/f7b121b492f25b1c5b27316798e1a70b6be2bd01/src/oneagent/__init__.py#L172-L205 | train | 37,256 |
Dynatrace/OneAgent-SDK-for-Python | src/oneagent/__init__.py | shutdown | def shutdown():
'''Shut down the SDK.
:returns: An exception object if an error occurred, a falsy value otherwise.
:rtype: Exception
'''
global _sdk_ref_count #pylint:disable=global-statement
global _sdk_instance #pylint:disable=global-statement
global _should_shutdown #pylint:disable=global-statement
with _sdk_ref_lk:
logger.debug("shutdown: ref count = %d, should_shutdown = %s", \
_sdk_ref_count, _should_shutdown)
nsdk = nativeagent.try_get_sdk()
if not nsdk:
logger.warning('shutdown: SDK not initialized or already shut down')
_sdk_ref_count = 0
return None
if _sdk_ref_count > 1:
logger.debug('shutdown: reference count is now %d', _sdk_ref_count)
_sdk_ref_count -= 1
return None
logger.info('shutdown: Shutting down SDK.')
try:
if _should_shutdown:
_rc = nsdk.shutdown()
if _rc == ErrorCode.NOT_INITIALIZED:
logger.warning('shutdown: native SDK was not initialized')
else:
nativeagent.checkresult(nsdk, _rc, 'shutdown')
_should_shutdown = False
except SDKError as e:
logger.warning('shutdown failed', exc_info=sys.exc_info())
return e
_sdk_ref_count = 0
_sdk_instance = None
nativeagent._force_initialize(None) #pylint:disable=protected-access
logger.debug('shutdown: completed')
return None | python | def shutdown():
'''Shut down the SDK.
:returns: An exception object if an error occurred, a falsy value otherwise.
:rtype: Exception
'''
global _sdk_ref_count #pylint:disable=global-statement
global _sdk_instance #pylint:disable=global-statement
global _should_shutdown #pylint:disable=global-statement
with _sdk_ref_lk:
logger.debug("shutdown: ref count = %d, should_shutdown = %s", \
_sdk_ref_count, _should_shutdown)
nsdk = nativeagent.try_get_sdk()
if not nsdk:
logger.warning('shutdown: SDK not initialized or already shut down')
_sdk_ref_count = 0
return None
if _sdk_ref_count > 1:
logger.debug('shutdown: reference count is now %d', _sdk_ref_count)
_sdk_ref_count -= 1
return None
logger.info('shutdown: Shutting down SDK.')
try:
if _should_shutdown:
_rc = nsdk.shutdown()
if _rc == ErrorCode.NOT_INITIALIZED:
logger.warning('shutdown: native SDK was not initialized')
else:
nativeagent.checkresult(nsdk, _rc, 'shutdown')
_should_shutdown = False
except SDKError as e:
logger.warning('shutdown failed', exc_info=sys.exc_info())
return e
_sdk_ref_count = 0
_sdk_instance = None
nativeagent._force_initialize(None) #pylint:disable=protected-access
logger.debug('shutdown: completed')
return None | [
"def",
"shutdown",
"(",
")",
":",
"global",
"_sdk_ref_count",
"#pylint:disable=global-statement",
"global",
"_sdk_instance",
"#pylint:disable=global-statement",
"global",
"_should_shutdown",
"#pylint:disable=global-statement",
"with",
"_sdk_ref_lk",
":",
"logger",
".",
"debug",... | Shut down the SDK.
:returns: An exception object if an error occurred, a falsy value otherwise.
:rtype: Exception | [
"Shut",
"down",
"the",
"SDK",
"."
] | f7b121b492f25b1c5b27316798e1a70b6be2bd01 | https://github.com/Dynatrace/OneAgent-SDK-for-Python/blob/f7b121b492f25b1c5b27316798e1a70b6be2bd01/src/oneagent/__init__.py#L266-L305 | train | 37,257 |
Dynatrace/OneAgent-SDK-for-Python | src/oneagent/_impl/util.py | error_from_exc | def error_from_exc(nsdk, tracer_h, e_val=None, e_ty=None):
"""Attach appropriate error information to tracer_h.
If e_val and e_ty are None, the current exception is used."""
if not tracer_h:
return
if e_ty is None and e_val is None:
e_ty, e_val = sys.exc_info()[:2]
if e_ty is None and e_val is not None:
e_ty = type(e_val)
nsdk.tracer_error(tracer_h, getfullname(e_ty), str(e_val)) | python | def error_from_exc(nsdk, tracer_h, e_val=None, e_ty=None):
"""Attach appropriate error information to tracer_h.
If e_val and e_ty are None, the current exception is used."""
if not tracer_h:
return
if e_ty is None and e_val is None:
e_ty, e_val = sys.exc_info()[:2]
if e_ty is None and e_val is not None:
e_ty = type(e_val)
nsdk.tracer_error(tracer_h, getfullname(e_ty), str(e_val)) | [
"def",
"error_from_exc",
"(",
"nsdk",
",",
"tracer_h",
",",
"e_val",
"=",
"None",
",",
"e_ty",
"=",
"None",
")",
":",
"if",
"not",
"tracer_h",
":",
"return",
"if",
"e_ty",
"is",
"None",
"and",
"e_val",
"is",
"None",
":",
"e_ty",
",",
"e_val",
"=",
... | Attach appropriate error information to tracer_h.
If e_val and e_ty are None, the current exception is used. | [
"Attach",
"appropriate",
"error",
"information",
"to",
"tracer_h",
"."
] | f7b121b492f25b1c5b27316798e1a70b6be2bd01 | https://github.com/Dynatrace/OneAgent-SDK-for-Python/blob/f7b121b492f25b1c5b27316798e1a70b6be2bd01/src/oneagent/_impl/util.py#L28-L40 | train | 37,258 |
10gen/mongo-orchestration | mongo_orchestration/process.py | _host | def _host():
"""Get the Host from the most recent HTTP request."""
host_and_port = request.urlparts[1]
try:
host, _ = host_and_port.split(':')
except ValueError:
# No port yet. Host defaults to '127.0.0.1' in bottle.request.
return DEFAULT_BIND
return host or DEFAULT_BIND | python | def _host():
"""Get the Host from the most recent HTTP request."""
host_and_port = request.urlparts[1]
try:
host, _ = host_and_port.split(':')
except ValueError:
# No port yet. Host defaults to '127.0.0.1' in bottle.request.
return DEFAULT_BIND
return host or DEFAULT_BIND | [
"def",
"_host",
"(",
")",
":",
"host_and_port",
"=",
"request",
".",
"urlparts",
"[",
"1",
"]",
"try",
":",
"host",
",",
"_",
"=",
"host_and_port",
".",
"split",
"(",
"':'",
")",
"except",
"ValueError",
":",
"# No port yet. Host defaults to '127.0.0.1' in bott... | Get the Host from the most recent HTTP request. | [
"Get",
"the",
"Host",
"from",
"the",
"most",
"recent",
"HTTP",
"request",
"."
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/process.py#L45-L53 | train | 37,259 |
10gen/mongo-orchestration | mongo_orchestration/process.py | repair_mongo | def repair_mongo(name, dbpath):
"""repair mongodb after usafe shutdown"""
log_file = os.path.join(dbpath, 'mongod.log')
cmd = [name, "--dbpath", dbpath, "--logpath", log_file, "--logappend",
"--repair"]
proc = subprocess.Popen(
cmd, universal_newlines=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
timeout = 45
t_start = time.time()
while time.time() - t_start < timeout:
line = str(proc.stdout.readline())
logger.info("repair output: %s" % (line,))
return_code = proc.poll()
if return_code is not None:
if return_code:
raise Exception("mongod --repair failed with exit code %s, "
"check log file: %s" % (return_code, log_file))
# Success when poll() returns 0
return
time.sleep(1)
proc.terminate()
raise Exception("mongod --repair failed to exit after %s seconds, "
"check log file: %s" % (timeout, log_file)) | python | def repair_mongo(name, dbpath):
"""repair mongodb after usafe shutdown"""
log_file = os.path.join(dbpath, 'mongod.log')
cmd = [name, "--dbpath", dbpath, "--logpath", log_file, "--logappend",
"--repair"]
proc = subprocess.Popen(
cmd, universal_newlines=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
timeout = 45
t_start = time.time()
while time.time() - t_start < timeout:
line = str(proc.stdout.readline())
logger.info("repair output: %s" % (line,))
return_code = proc.poll()
if return_code is not None:
if return_code:
raise Exception("mongod --repair failed with exit code %s, "
"check log file: %s" % (return_code, log_file))
# Success when poll() returns 0
return
time.sleep(1)
proc.terminate()
raise Exception("mongod --repair failed to exit after %s seconds, "
"check log file: %s" % (timeout, log_file)) | [
"def",
"repair_mongo",
"(",
"name",
",",
"dbpath",
")",
":",
"log_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dbpath",
",",
"'mongod.log'",
")",
"cmd",
"=",
"[",
"name",
",",
"\"--dbpath\"",
",",
"dbpath",
",",
"\"--logpath\"",
",",
"log_file",
"... | repair mongodb after usafe shutdown | [
"repair",
"mongodb",
"after",
"usafe",
"shutdown"
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/process.py#L161-L184 | train | 37,260 |
10gen/mongo-orchestration | mongo_orchestration/process.py | wait_mprocess | def wait_mprocess(process, timeout):
"""Compatibility function for waiting on a process with a timeout.
Raises TimeoutError when the timeout is reached.
"""
if PY3:
try:
return process.wait(timeout=timeout)
except subprocess.TimeoutExpired as exc:
raise TimeoutError(str(exc))
# On Python 2, simulate the timeout parameter and raise TimeoutError.
start = time.time()
while True:
exit_code = process.poll()
if exit_code is not None:
return exit_code
if time.time() - start > timeout:
raise TimeoutError("Process %s timed out after %s seconds" %
(process.pid, timeout))
time.sleep(0.05) | python | def wait_mprocess(process, timeout):
"""Compatibility function for waiting on a process with a timeout.
Raises TimeoutError when the timeout is reached.
"""
if PY3:
try:
return process.wait(timeout=timeout)
except subprocess.TimeoutExpired as exc:
raise TimeoutError(str(exc))
# On Python 2, simulate the timeout parameter and raise TimeoutError.
start = time.time()
while True:
exit_code = process.poll()
if exit_code is not None:
return exit_code
if time.time() - start > timeout:
raise TimeoutError("Process %s timed out after %s seconds" %
(process.pid, timeout))
time.sleep(0.05) | [
"def",
"wait_mprocess",
"(",
"process",
",",
"timeout",
")",
":",
"if",
"PY3",
":",
"try",
":",
"return",
"process",
".",
"wait",
"(",
"timeout",
"=",
"timeout",
")",
"except",
"subprocess",
".",
"TimeoutExpired",
"as",
"exc",
":",
"raise",
"TimeoutError",... | Compatibility function for waiting on a process with a timeout.
Raises TimeoutError when the timeout is reached. | [
"Compatibility",
"function",
"for",
"waiting",
"on",
"a",
"process",
"with",
"a",
"timeout",
"."
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/process.py#L240-L260 | train | 37,261 |
10gen/mongo-orchestration | mongo_orchestration/process.py | remove_path | def remove_path(path):
"""remove path from file system
If path is None - do nothing"""
if path is None or not os.path.exists(path):
return
if platform.system() == 'Windows':
# Need to have write permission before deleting the file.
os.chmod(path, stat.S_IWRITE)
try:
if os.path.isdir(path):
shutil.rmtree(path)
elif os.path.isfile(path):
shutil.os.remove(path)
except OSError:
logger.exception("Could not remove path: %s" % path) | python | def remove_path(path):
"""remove path from file system
If path is None - do nothing"""
if path is None or not os.path.exists(path):
return
if platform.system() == 'Windows':
# Need to have write permission before deleting the file.
os.chmod(path, stat.S_IWRITE)
try:
if os.path.isdir(path):
shutil.rmtree(path)
elif os.path.isfile(path):
shutil.os.remove(path)
except OSError:
logger.exception("Could not remove path: %s" % path) | [
"def",
"remove_path",
"(",
"path",
")",
":",
"if",
"path",
"is",
"None",
"or",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"return",
"if",
"platform",
".",
"system",
"(",
")",
"==",
"'Windows'",
":",
"# Need to have write permission b... | remove path from file system
If path is None - do nothing | [
"remove",
"path",
"from",
"file",
"system",
"If",
"path",
"is",
"None",
"-",
"do",
"nothing"
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/process.py#L285-L299 | train | 37,262 |
10gen/mongo-orchestration | mongo_orchestration/process.py | read_config | def read_config(config_path):
"""read config_path and return options as dictionary"""
result = {}
with open(config_path, 'r') as fd:
for line in fd.readlines():
if '=' in line:
key, value = line.split('=', 1)
try:
result[key] = json.loads(value)
except ValueError:
result[key] = value.rstrip('\n')
return result | python | def read_config(config_path):
"""read config_path and return options as dictionary"""
result = {}
with open(config_path, 'r') as fd:
for line in fd.readlines():
if '=' in line:
key, value = line.split('=', 1)
try:
result[key] = json.loads(value)
except ValueError:
result[key] = value.rstrip('\n')
return result | [
"def",
"read_config",
"(",
"config_path",
")",
":",
"result",
"=",
"{",
"}",
"with",
"open",
"(",
"config_path",
",",
"'r'",
")",
"as",
"fd",
":",
"for",
"line",
"in",
"fd",
".",
"readlines",
"(",
")",
":",
"if",
"'='",
"in",
"line",
":",
"key",
... | read config_path and return options as dictionary | [
"read",
"config_path",
"and",
"return",
"options",
"as",
"dictionary"
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/process.py#L336-L347 | train | 37,263 |
10gen/mongo-orchestration | mongo_orchestration/process.py | PortPool.__check_port | def __check_port(self, port):
"""check port status
return True if port is free, False else
"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind((_host(), port))
return True
except socket.error:
return False
finally:
s.close() | python | def __check_port(self, port):
"""check port status
return True if port is free, False else
"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind((_host(), port))
return True
except socket.error:
return False
finally:
s.close() | [
"def",
"__check_port",
"(",
"self",
",",
"port",
")",
":",
"s",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"try",
":",
"s",
".",
"bind",
"(",
"(",
"_host",
"(",
")",
",",
"port",
")",
")",... | check port status
return True if port is free, False else | [
"check",
"port",
"status",
"return",
"True",
"if",
"port",
"is",
"free",
"False",
"else"
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/process.py#L81-L92 | train | 37,264 |
10gen/mongo-orchestration | mongo_orchestration/process.py | PortPool.change_range | def change_range(self, min_port=1025, max_port=2000, port_sequence=None):
"""change Pool port range"""
self.__init_range(min_port, max_port, port_sequence) | python | def change_range(self, min_port=1025, max_port=2000, port_sequence=None):
"""change Pool port range"""
self.__init_range(min_port, max_port, port_sequence) | [
"def",
"change_range",
"(",
"self",
",",
"min_port",
"=",
"1025",
",",
"max_port",
"=",
"2000",
",",
"port_sequence",
"=",
"None",
")",
":",
"self",
".",
"__init_range",
"(",
"min_port",
",",
"max_port",
",",
"port_sequence",
")"
] | change Pool port range | [
"change",
"Pool",
"port",
"range"
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/process.py#L133-L135 | train | 37,265 |
10gen/mongo-orchestration | mongo_orchestration/apps/__init__.py | setup_versioned_routes | def setup_versioned_routes(routes, version=None):
"""Set up routes with a version prefix."""
prefix = '/' + version if version else ""
for r in routes:
path, method = r
route(prefix + path, method, routes[r]) | python | def setup_versioned_routes(routes, version=None):
"""Set up routes with a version prefix."""
prefix = '/' + version if version else ""
for r in routes:
path, method = r
route(prefix + path, method, routes[r]) | [
"def",
"setup_versioned_routes",
"(",
"routes",
",",
"version",
"=",
"None",
")",
":",
"prefix",
"=",
"'/'",
"+",
"version",
"if",
"version",
"else",
"\"\"",
"for",
"r",
"in",
"routes",
":",
"path",
",",
"method",
"=",
"r",
"route",
"(",
"prefix",
"+",... | Set up routes with a version prefix. | [
"Set",
"up",
"routes",
"with",
"a",
"version",
"prefix",
"."
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/apps/__init__.py#L39-L44 | train | 37,266 |
10gen/mongo-orchestration | mongo_orchestration/replica_sets.py | ReplicaSet.cleanup | def cleanup(self):
"""remove all members without reconfig"""
for item in self.server_map:
self.member_del(item, reconfig=False)
self.server_map.clear() | python | def cleanup(self):
"""remove all members without reconfig"""
for item in self.server_map:
self.member_del(item, reconfig=False)
self.server_map.clear() | [
"def",
"cleanup",
"(",
"self",
")",
":",
"for",
"item",
"in",
"self",
".",
"server_map",
":",
"self",
".",
"member_del",
"(",
"item",
",",
"reconfig",
"=",
"False",
")",
"self",
".",
"server_map",
".",
"clear",
"(",
")"
] | remove all members without reconfig | [
"remove",
"all",
"members",
"without",
"reconfig"
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/replica_sets.py#L154-L158 | train | 37,267 |
10gen/mongo-orchestration | mongo_orchestration/replica_sets.py | ReplicaSet.host2id | def host2id(self, hostname):
"""return member id by hostname"""
for key, value in self.server_map.items():
if value == hostname:
return key | python | def host2id(self, hostname):
"""return member id by hostname"""
for key, value in self.server_map.items():
if value == hostname:
return key | [
"def",
"host2id",
"(",
"self",
",",
"hostname",
")",
":",
"for",
"key",
",",
"value",
"in",
"self",
".",
"server_map",
".",
"items",
"(",
")",
":",
"if",
"value",
"==",
"hostname",
":",
"return",
"key"
] | return member id by hostname | [
"return",
"member",
"id",
"by",
"hostname"
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/replica_sets.py#L164-L168 | train | 37,268 |
10gen/mongo-orchestration | mongo_orchestration/replica_sets.py | ReplicaSet.repl_init | def repl_init(self, config):
"""create replica set by config
return True if replica set created successfuly, else False"""
self.update_server_map(config)
# init_server - server which can init replica set
init_server = [member['host'] for member in config['members']
if not (member.get('arbiterOnly', False)
or member.get('priority', 1) == 0)][0]
servers = [member['host'] for member in config['members']]
if not self.wait_while_reachable(servers):
logger.error("all servers must be reachable")
self.cleanup()
return False
try:
result = self.connection(init_server).admin.command("replSetInitiate", config)
logger.debug("replica init result: {result}".format(**locals()))
except pymongo.errors.PyMongoError:
raise
if int(result.get('ok', 0)) == 1:
# Wait while members come up
return self.waiting_member_state()
else:
self.cleanup()
return False | python | def repl_init(self, config):
"""create replica set by config
return True if replica set created successfuly, else False"""
self.update_server_map(config)
# init_server - server which can init replica set
init_server = [member['host'] for member in config['members']
if not (member.get('arbiterOnly', False)
or member.get('priority', 1) == 0)][0]
servers = [member['host'] for member in config['members']]
if not self.wait_while_reachable(servers):
logger.error("all servers must be reachable")
self.cleanup()
return False
try:
result = self.connection(init_server).admin.command("replSetInitiate", config)
logger.debug("replica init result: {result}".format(**locals()))
except pymongo.errors.PyMongoError:
raise
if int(result.get('ok', 0)) == 1:
# Wait while members come up
return self.waiting_member_state()
else:
self.cleanup()
return False | [
"def",
"repl_init",
"(",
"self",
",",
"config",
")",
":",
"self",
".",
"update_server_map",
"(",
"config",
")",
"# init_server - server which can init replica set",
"init_server",
"=",
"[",
"member",
"[",
"'host'",
"]",
"for",
"member",
"in",
"config",
"[",
"'me... | create replica set by config
return True if replica set created successfuly, else False | [
"create",
"replica",
"set",
"by",
"config",
"return",
"True",
"if",
"replica",
"set",
"created",
"successfuly",
"else",
"False"
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/replica_sets.py#L174-L198 | train | 37,269 |
10gen/mongo-orchestration | mongo_orchestration/replica_sets.py | ReplicaSet.reset | def reset(self):
"""Ensure all members are running and available."""
# Need to use self.server_map, in case no Servers are left running.
for member_id in self.server_map:
host = self.member_id_to_host(member_id)
server_id = self._servers.host_to_server_id(host)
# Reset each member.
self._servers.command(server_id, 'reset')
# Wait for all members to have a state of 1, 2, or 7.
# Note that this also waits for a primary to become available.
self.waiting_member_state()
# Wait for Server states to match the config from the primary.
self.waiting_config_state()
return self.info() | python | def reset(self):
"""Ensure all members are running and available."""
# Need to use self.server_map, in case no Servers are left running.
for member_id in self.server_map:
host = self.member_id_to_host(member_id)
server_id = self._servers.host_to_server_id(host)
# Reset each member.
self._servers.command(server_id, 'reset')
# Wait for all members to have a state of 1, 2, or 7.
# Note that this also waits for a primary to become available.
self.waiting_member_state()
# Wait for Server states to match the config from the primary.
self.waiting_config_state()
return self.info() | [
"def",
"reset",
"(",
"self",
")",
":",
"# Need to use self.server_map, in case no Servers are left running.",
"for",
"member_id",
"in",
"self",
".",
"server_map",
":",
"host",
"=",
"self",
".",
"member_id_to_host",
"(",
"member_id",
")",
"server_id",
"=",
"self",
".... | Ensure all members are running and available. | [
"Ensure",
"all",
"members",
"are",
"running",
"and",
"available",
"."
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/replica_sets.py#L200-L213 | train | 37,270 |
10gen/mongo-orchestration | mongo_orchestration/replica_sets.py | ReplicaSet.repl_update | def repl_update(self, config):
"""Reconfig Replicaset with new config"""
cfg = config.copy()
cfg['version'] += 1
try:
result = self.run_command("replSetReconfig", cfg)
if int(result.get('ok', 0)) != 1:
return False
except pymongo.errors.AutoReconnect:
self.update_server_map(cfg) # use new server_map
self.waiting_member_state()
self.waiting_config_state()
return self.connection() and True | python | def repl_update(self, config):
"""Reconfig Replicaset with new config"""
cfg = config.copy()
cfg['version'] += 1
try:
result = self.run_command("replSetReconfig", cfg)
if int(result.get('ok', 0)) != 1:
return False
except pymongo.errors.AutoReconnect:
self.update_server_map(cfg) # use new server_map
self.waiting_member_state()
self.waiting_config_state()
return self.connection() and True | [
"def",
"repl_update",
"(",
"self",
",",
"config",
")",
":",
"cfg",
"=",
"config",
".",
"copy",
"(",
")",
"cfg",
"[",
"'version'",
"]",
"+=",
"1",
"try",
":",
"result",
"=",
"self",
".",
"run_command",
"(",
"\"replSetReconfig\"",
",",
"cfg",
")",
"if"... | Reconfig Replicaset with new config | [
"Reconfig",
"Replicaset",
"with",
"new",
"config"
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/replica_sets.py#L215-L227 | train | 37,271 |
10gen/mongo-orchestration | mongo_orchestration/replica_sets.py | ReplicaSet.info | def info(self):
"""return information about replica set"""
hosts = ','.join(x['host'] for x in self.members())
mongodb_uri = 'mongodb://' + hosts + '/?replicaSet=' + self.repl_id
result = {"id": self.repl_id,
"auth_key": self.auth_key,
"members": self.members(),
"mongodb_uri": mongodb_uri,
"orchestration": 'replica_sets'}
if self.login:
# Add replicaSet URI parameter.
uri = ('%s&replicaSet=%s'
% (self.mongodb_auth_uri(hosts), self.repl_id))
result['mongodb_auth_uri'] = uri
return result | python | def info(self):
"""return information about replica set"""
hosts = ','.join(x['host'] for x in self.members())
mongodb_uri = 'mongodb://' + hosts + '/?replicaSet=' + self.repl_id
result = {"id": self.repl_id,
"auth_key": self.auth_key,
"members": self.members(),
"mongodb_uri": mongodb_uri,
"orchestration": 'replica_sets'}
if self.login:
# Add replicaSet URI parameter.
uri = ('%s&replicaSet=%s'
% (self.mongodb_auth_uri(hosts), self.repl_id))
result['mongodb_auth_uri'] = uri
return result | [
"def",
"info",
"(",
"self",
")",
":",
"hosts",
"=",
"','",
".",
"join",
"(",
"x",
"[",
"'host'",
"]",
"for",
"x",
"in",
"self",
".",
"members",
"(",
")",
")",
"mongodb_uri",
"=",
"'mongodb://'",
"+",
"hosts",
"+",
"'/?replicaSet='",
"+",
"self",
".... | return information about replica set | [
"return",
"information",
"about",
"replica",
"set"
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/replica_sets.py#L229-L243 | train | 37,272 |
10gen/mongo-orchestration | mongo_orchestration/replica_sets.py | ReplicaSet.run_command | def run_command(self, command, arg=None, is_eval=False, member_id=None):
"""run command on replica set
if member_id is specified command will be execute on this server
if member_id is not specified command will be execute on the primary
Args:
command - command string
arg - command argument
is_eval - if True execute command as eval
member_id - member id
return command's result
"""
logger.debug("run_command({command}, {arg}, {is_eval}, {member_id})".format(**locals()))
mode = is_eval and 'eval' or 'command'
hostname = None
if isinstance(member_id, int):
hostname = self.member_id_to_host(member_id)
result = getattr(self.connection(hostname=hostname).admin, mode)(command, arg)
logger.debug("command result: {result}".format(result=result))
return result | python | def run_command(self, command, arg=None, is_eval=False, member_id=None):
"""run command on replica set
if member_id is specified command will be execute on this server
if member_id is not specified command will be execute on the primary
Args:
command - command string
arg - command argument
is_eval - if True execute command as eval
member_id - member id
return command's result
"""
logger.debug("run_command({command}, {arg}, {is_eval}, {member_id})".format(**locals()))
mode = is_eval and 'eval' or 'command'
hostname = None
if isinstance(member_id, int):
hostname = self.member_id_to_host(member_id)
result = getattr(self.connection(hostname=hostname).admin, mode)(command, arg)
logger.debug("command result: {result}".format(result=result))
return result | [
"def",
"run_command",
"(",
"self",
",",
"command",
",",
"arg",
"=",
"None",
",",
"is_eval",
"=",
"False",
",",
"member_id",
"=",
"None",
")",
":",
"logger",
".",
"debug",
"(",
"\"run_command({command}, {arg}, {is_eval}, {member_id})\"",
".",
"format",
"(",
"*"... | run command on replica set
if member_id is specified command will be execute on this server
if member_id is not specified command will be execute on the primary
Args:
command - command string
arg - command argument
is_eval - if True execute command as eval
member_id - member id
return command's result | [
"run",
"command",
"on",
"replica",
"set",
"if",
"member_id",
"is",
"specified",
"command",
"will",
"be",
"execute",
"on",
"this",
"server",
"if",
"member_id",
"is",
"not",
"specified",
"command",
"will",
"be",
"execute",
"on",
"the",
"primary"
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/replica_sets.py#L260-L280 | train | 37,273 |
10gen/mongo-orchestration | mongo_orchestration/replica_sets.py | ReplicaSet.member_info | def member_info(self, member_id):
"""return information about member"""
server_id = self._servers.host_to_server_id(
self.member_id_to_host(member_id))
server_info = self._servers.info(server_id)
result = {'_id': member_id, 'server_id': server_id,
'mongodb_uri': server_info['mongodb_uri'],
'procInfo': server_info['procInfo'],
'statuses': server_info['statuses']}
if self.login:
result['mongodb_auth_uri'] = self.mongodb_auth_uri(
self._servers.hostname(server_id))
result['rsInfo'] = {}
if server_info['procInfo']['alive']:
# Can't call serverStatus on arbiter when running with auth enabled.
# (SERVER-5479)
if self.login or self.auth_key:
arbiter_ids = [member['_id'] for member in self.arbiters()]
if member_id in arbiter_ids:
result['rsInfo'] = {
'arbiterOnly': True, 'secondary': False, 'primary': False}
return result
repl = self.run_command('serverStatus', arg=None, is_eval=False, member_id=member_id)['repl']
logger.debug("member {member_id} repl info: {repl}".format(**locals()))
for key in ('votes', 'tags', 'arbiterOnly', 'buildIndexes', 'hidden', 'priority', 'slaveDelay', 'votes', 'secondary'):
if key in repl:
result['rsInfo'][key] = repl[key]
result['rsInfo']['primary'] = repl.get('ismaster', False)
return result | python | def member_info(self, member_id):
"""return information about member"""
server_id = self._servers.host_to_server_id(
self.member_id_to_host(member_id))
server_info = self._servers.info(server_id)
result = {'_id': member_id, 'server_id': server_id,
'mongodb_uri': server_info['mongodb_uri'],
'procInfo': server_info['procInfo'],
'statuses': server_info['statuses']}
if self.login:
result['mongodb_auth_uri'] = self.mongodb_auth_uri(
self._servers.hostname(server_id))
result['rsInfo'] = {}
if server_info['procInfo']['alive']:
# Can't call serverStatus on arbiter when running with auth enabled.
# (SERVER-5479)
if self.login or self.auth_key:
arbiter_ids = [member['_id'] for member in self.arbiters()]
if member_id in arbiter_ids:
result['rsInfo'] = {
'arbiterOnly': True, 'secondary': False, 'primary': False}
return result
repl = self.run_command('serverStatus', arg=None, is_eval=False, member_id=member_id)['repl']
logger.debug("member {member_id} repl info: {repl}".format(**locals()))
for key in ('votes', 'tags', 'arbiterOnly', 'buildIndexes', 'hidden', 'priority', 'slaveDelay', 'votes', 'secondary'):
if key in repl:
result['rsInfo'][key] = repl[key]
result['rsInfo']['primary'] = repl.get('ismaster', False)
return result | [
"def",
"member_info",
"(",
"self",
",",
"member_id",
")",
":",
"server_id",
"=",
"self",
".",
"_servers",
".",
"host_to_server_id",
"(",
"self",
".",
"member_id_to_host",
"(",
"member_id",
")",
")",
"server_info",
"=",
"self",
".",
"_servers",
".",
"info",
... | return information about member | [
"return",
"information",
"about",
"member"
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/replica_sets.py#L352-L381 | train | 37,274 |
10gen/mongo-orchestration | mongo_orchestration/replica_sets.py | ReplicaSet.members | def members(self):
"""return list of members information"""
result = list()
for member in self.run_command(command="replSetGetStatus", is_eval=False)['members']:
result.append({
"_id": member['_id'],
"host": member["name"],
"server_id": self._servers.host_to_server_id(member["name"]),
"state": member['state']
})
return result | python | def members(self):
"""return list of members information"""
result = list()
for member in self.run_command(command="replSetGetStatus", is_eval=False)['members']:
result.append({
"_id": member['_id'],
"host": member["name"],
"server_id": self._servers.host_to_server_id(member["name"]),
"state": member['state']
})
return result | [
"def",
"members",
"(",
"self",
")",
":",
"result",
"=",
"list",
"(",
")",
"for",
"member",
"in",
"self",
".",
"run_command",
"(",
"command",
"=",
"\"replSetGetStatus\"",
",",
"is_eval",
"=",
"False",
")",
"[",
"'members'",
"]",
":",
"result",
".",
"app... | return list of members information | [
"return",
"list",
"of",
"members",
"information"
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/replica_sets.py#L395-L405 | train | 37,275 |
10gen/mongo-orchestration | mongo_orchestration/replica_sets.py | ReplicaSet.get_members_in_state | def get_members_in_state(self, state):
"""return all members of replica set in specific state"""
members = self.run_command(command='replSetGetStatus', is_eval=False)['members']
return [member['name'] for member in members if member['state'] == state] | python | def get_members_in_state(self, state):
"""return all members of replica set in specific state"""
members = self.run_command(command='replSetGetStatus', is_eval=False)['members']
return [member['name'] for member in members if member['state'] == state] | [
"def",
"get_members_in_state",
"(",
"self",
",",
"state",
")",
":",
"members",
"=",
"self",
".",
"run_command",
"(",
"command",
"=",
"'replSetGetStatus'",
",",
"is_eval",
"=",
"False",
")",
"[",
"'members'",
"]",
"return",
"[",
"member",
"[",
"'name'",
"]"... | return all members of replica set in specific state | [
"return",
"all",
"members",
"of",
"replica",
"set",
"in",
"specific",
"state"
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/replica_sets.py#L412-L415 | train | 37,276 |
10gen/mongo-orchestration | mongo_orchestration/replica_sets.py | ReplicaSet._authenticate_client | def _authenticate_client(self, client):
"""Authenticate the client if necessary."""
if self.login and not self.restart_required:
try:
db = client[self.auth_source]
if self.x509_extra_user:
db.authenticate(
DEFAULT_SUBJECT,
mechanism='MONGODB-X509'
)
else:
db.authenticate(
self.login, self.password)
except Exception:
logger.exception(
"Could not authenticate to %r as %s/%s"
% (client, self.login, self.password))
raise | python | def _authenticate_client(self, client):
"""Authenticate the client if necessary."""
if self.login and not self.restart_required:
try:
db = client[self.auth_source]
if self.x509_extra_user:
db.authenticate(
DEFAULT_SUBJECT,
mechanism='MONGODB-X509'
)
else:
db.authenticate(
self.login, self.password)
except Exception:
logger.exception(
"Could not authenticate to %r as %s/%s"
% (client, self.login, self.password))
raise | [
"def",
"_authenticate_client",
"(",
"self",
",",
"client",
")",
":",
"if",
"self",
".",
"login",
"and",
"not",
"self",
".",
"restart_required",
":",
"try",
":",
"db",
"=",
"client",
"[",
"self",
".",
"auth_source",
"]",
"if",
"self",
".",
"x509_extra_use... | Authenticate the client if necessary. | [
"Authenticate",
"the",
"client",
"if",
"necessary",
"."
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/replica_sets.py#L417-L434 | train | 37,277 |
10gen/mongo-orchestration | mongo_orchestration/replica_sets.py | ReplicaSet.secondaries | def secondaries(self):
"""return list of secondaries members"""
return [
{
"_id": self.host2id(member),
"host": member,
"server_id": self._servers.host_to_server_id(member)
}
for member in self.get_members_in_state(2)
] | python | def secondaries(self):
"""return list of secondaries members"""
return [
{
"_id": self.host2id(member),
"host": member,
"server_id": self._servers.host_to_server_id(member)
}
for member in self.get_members_in_state(2)
] | [
"def",
"secondaries",
"(",
"self",
")",
":",
"return",
"[",
"{",
"\"_id\"",
":",
"self",
".",
"host2id",
"(",
"member",
")",
",",
"\"host\"",
":",
"member",
",",
"\"server_id\"",
":",
"self",
".",
"_servers",
".",
"host_to_server_id",
"(",
"member",
")",... | return list of secondaries members | [
"return",
"list",
"of",
"secondaries",
"members"
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/replica_sets.py#L477-L486 | train | 37,278 |
10gen/mongo-orchestration | mongo_orchestration/replica_sets.py | ReplicaSet.arbiters | def arbiters(self):
"""return list of arbiters"""
return [
{
"_id": self.host2id(member),
"host": member,
"server_id": self._servers.host_to_server_id(member)
}
for member in self.get_members_in_state(7)
] | python | def arbiters(self):
"""return list of arbiters"""
return [
{
"_id": self.host2id(member),
"host": member,
"server_id": self._servers.host_to_server_id(member)
}
for member in self.get_members_in_state(7)
] | [
"def",
"arbiters",
"(",
"self",
")",
":",
"return",
"[",
"{",
"\"_id\"",
":",
"self",
".",
"host2id",
"(",
"member",
")",
",",
"\"host\"",
":",
"member",
",",
"\"server_id\"",
":",
"self",
".",
"_servers",
".",
"host_to_server_id",
"(",
"member",
")",
... | return list of arbiters | [
"return",
"list",
"of",
"arbiters"
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/replica_sets.py#L488-L497 | train | 37,279 |
10gen/mongo-orchestration | mongo_orchestration/replica_sets.py | ReplicaSet.hidden | def hidden(self):
"""return list of hidden members"""
members = [self.member_info(item["_id"]) for item in self.members()]
result = []
for member in members:
if member['rsInfo'].get('hidden'):
server_id = member['server_id']
result.append({
'_id': member['_id'],
'host': self._servers.hostname(server_id),
'server_id': server_id})
return result | python | def hidden(self):
"""return list of hidden members"""
members = [self.member_info(item["_id"]) for item in self.members()]
result = []
for member in members:
if member['rsInfo'].get('hidden'):
server_id = member['server_id']
result.append({
'_id': member['_id'],
'host': self._servers.hostname(server_id),
'server_id': server_id})
return result | [
"def",
"hidden",
"(",
"self",
")",
":",
"members",
"=",
"[",
"self",
".",
"member_info",
"(",
"item",
"[",
"\"_id\"",
"]",
")",
"for",
"item",
"in",
"self",
".",
"members",
"(",
")",
"]",
"result",
"=",
"[",
"]",
"for",
"member",
"in",
"members",
... | return list of hidden members | [
"return",
"list",
"of",
"hidden",
"members"
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/replica_sets.py#L499-L510 | train | 37,280 |
10gen/mongo-orchestration | mongo_orchestration/replica_sets.py | ReplicaSet.passives | def passives(self):
"""return list of passive servers"""
servers = self.run_command('ismaster').get('passives', [])
return [member for member in self.members() if member['host'] in servers] | python | def passives(self):
"""return list of passive servers"""
servers = self.run_command('ismaster').get('passives', [])
return [member for member in self.members() if member['host'] in servers] | [
"def",
"passives",
"(",
"self",
")",
":",
"servers",
"=",
"self",
".",
"run_command",
"(",
"'ismaster'",
")",
".",
"get",
"(",
"'passives'",
",",
"[",
"]",
")",
"return",
"[",
"member",
"for",
"member",
"in",
"self",
".",
"members",
"(",
")",
"if",
... | return list of passive servers | [
"return",
"list",
"of",
"passive",
"servers"
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/replica_sets.py#L512-L515 | train | 37,281 |
10gen/mongo-orchestration | mongo_orchestration/replica_sets.py | ReplicaSet.waiting_member_state | def waiting_member_state(self, timeout=300):
"""Wait for all RS members to be in an acceptable state."""
t_start = time.time()
while not self.check_member_state():
if time.time() - t_start > timeout:
return False
time.sleep(0.1)
return True | python | def waiting_member_state(self, timeout=300):
"""Wait for all RS members to be in an acceptable state."""
t_start = time.time()
while not self.check_member_state():
if time.time() - t_start > timeout:
return False
time.sleep(0.1)
return True | [
"def",
"waiting_member_state",
"(",
"self",
",",
"timeout",
"=",
"300",
")",
":",
"t_start",
"=",
"time",
".",
"time",
"(",
")",
"while",
"not",
"self",
".",
"check_member_state",
"(",
")",
":",
"if",
"time",
".",
"time",
"(",
")",
"-",
"t_start",
">... | Wait for all RS members to be in an acceptable state. | [
"Wait",
"for",
"all",
"RS",
"members",
"to",
"be",
"in",
"an",
"acceptable",
"state",
"."
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/replica_sets.py#L543-L550 | train | 37,282 |
10gen/mongo-orchestration | mongo_orchestration/replica_sets.py | ReplicaSet.check_member_state | def check_member_state(self):
"""Verify that all RS members have an acceptable state."""
bad_states = (0, 3, 4, 5, 6, 9)
try:
rs_status = self.run_command('replSetGetStatus')
bad_members = [member for member in rs_status['members']
if member['state'] in bad_states]
if bad_members:
return False
except pymongo.errors.AutoReconnect:
# catch 'No replica set primary available' Exception
return False
logger.debug("all members in correct state")
return True | python | def check_member_state(self):
"""Verify that all RS members have an acceptable state."""
bad_states = (0, 3, 4, 5, 6, 9)
try:
rs_status = self.run_command('replSetGetStatus')
bad_members = [member for member in rs_status['members']
if member['state'] in bad_states]
if bad_members:
return False
except pymongo.errors.AutoReconnect:
# catch 'No replica set primary available' Exception
return False
logger.debug("all members in correct state")
return True | [
"def",
"check_member_state",
"(",
"self",
")",
":",
"bad_states",
"=",
"(",
"0",
",",
"3",
",",
"4",
",",
"5",
",",
"6",
",",
"9",
")",
"try",
":",
"rs_status",
"=",
"self",
".",
"run_command",
"(",
"'replSetGetStatus'",
")",
"bad_members",
"=",
"[",... | Verify that all RS members have an acceptable state. | [
"Verify",
"that",
"all",
"RS",
"members",
"have",
"an",
"acceptable",
"state",
"."
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/replica_sets.py#L566-L579 | train | 37,283 |
10gen/mongo-orchestration | mongo_orchestration/replica_sets.py | ReplicaSet.check_config_state | def check_config_state(self):
"""Return True if real state equal config state otherwise False."""
config = self.config
self.update_server_map(config)
for member in config['members']:
cfg_member_info = self.default_params.copy()
cfg_member_info.update(member)
# Remove attributes we can't check.
for attr in ('priority', 'votes', 'tags', 'buildIndexes'):
cfg_member_info.pop(attr, None)
cfg_member_info['host'] = cfg_member_info['host'].lower()
real_member_info = self.default_params.copy()
info = self.member_info(member["_id"])
real_member_info["_id"] = info['_id']
member_hostname = self._servers.hostname(info['server_id'])
real_member_info["host"] = member_hostname.lower()
real_member_info.update(info['rsInfo'])
logger.debug("real_member_info({member_id}): {info}".format(member_id=member['_id'], info=info))
for key in cfg_member_info:
if cfg_member_info[key] != real_member_info.get(key, None):
logger.debug("{key}: {value1} ! = {value2}".format(key=key, value1=cfg_member_info[key], value2=real_member_info.get(key, None)))
return False
return True | python | def check_config_state(self):
"""Return True if real state equal config state otherwise False."""
config = self.config
self.update_server_map(config)
for member in config['members']:
cfg_member_info = self.default_params.copy()
cfg_member_info.update(member)
# Remove attributes we can't check.
for attr in ('priority', 'votes', 'tags', 'buildIndexes'):
cfg_member_info.pop(attr, None)
cfg_member_info['host'] = cfg_member_info['host'].lower()
real_member_info = self.default_params.copy()
info = self.member_info(member["_id"])
real_member_info["_id"] = info['_id']
member_hostname = self._servers.hostname(info['server_id'])
real_member_info["host"] = member_hostname.lower()
real_member_info.update(info['rsInfo'])
logger.debug("real_member_info({member_id}): {info}".format(member_id=member['_id'], info=info))
for key in cfg_member_info:
if cfg_member_info[key] != real_member_info.get(key, None):
logger.debug("{key}: {value1} ! = {value2}".format(key=key, value1=cfg_member_info[key], value2=real_member_info.get(key, None)))
return False
return True | [
"def",
"check_config_state",
"(",
"self",
")",
":",
"config",
"=",
"self",
".",
"config",
"self",
".",
"update_server_map",
"(",
"config",
")",
"for",
"member",
"in",
"config",
"[",
"'members'",
"]",
":",
"cfg_member_info",
"=",
"self",
".",
"default_params"... | Return True if real state equal config state otherwise False. | [
"Return",
"True",
"if",
"real",
"state",
"equal",
"config",
"state",
"otherwise",
"False",
"."
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/replica_sets.py#L581-L604 | train | 37,284 |
10gen/mongo-orchestration | mongo_orchestration/replica_sets.py | ReplicaSet.restart | def restart(self, timeout=300, config_callback=None):
"""Restart each member of the replica set."""
for member_id in self.server_map:
host = self.server_map[member_id]
server_id = self._servers.host_to_server_id(host)
server = self._servers._storage[server_id]
server.restart(timeout, config_callback)
self.waiting_member_state() | python | def restart(self, timeout=300, config_callback=None):
"""Restart each member of the replica set."""
for member_id in self.server_map:
host = self.server_map[member_id]
server_id = self._servers.host_to_server_id(host)
server = self._servers._storage[server_id]
server.restart(timeout, config_callback)
self.waiting_member_state() | [
"def",
"restart",
"(",
"self",
",",
"timeout",
"=",
"300",
",",
"config_callback",
"=",
"None",
")",
":",
"for",
"member_id",
"in",
"self",
".",
"server_map",
":",
"host",
"=",
"self",
".",
"server_map",
"[",
"member_id",
"]",
"server_id",
"=",
"self",
... | Restart each member of the replica set. | [
"Restart",
"each",
"member",
"of",
"the",
"replica",
"set",
"."
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/replica_sets.py#L606-L613 | train | 37,285 |
10gen/mongo-orchestration | mongo_orchestration/replica_sets.py | ReplicaSets.command | def command(self, rs_id, command, *args):
"""Call a ReplicaSet method."""
rs = self._storage[rs_id]
try:
return getattr(rs, command)(*args)
except AttributeError:
raise ValueError("Cannot issue the command %r to ReplicaSet %s"
% (command, rs_id)) | python | def command(self, rs_id, command, *args):
"""Call a ReplicaSet method."""
rs = self._storage[rs_id]
try:
return getattr(rs, command)(*args)
except AttributeError:
raise ValueError("Cannot issue the command %r to ReplicaSet %s"
% (command, rs_id)) | [
"def",
"command",
"(",
"self",
",",
"rs_id",
",",
"command",
",",
"*",
"args",
")",
":",
"rs",
"=",
"self",
".",
"_storage",
"[",
"rs_id",
"]",
"try",
":",
"return",
"getattr",
"(",
"rs",
",",
"command",
")",
"(",
"*",
"args",
")",
"except",
"Att... | Call a ReplicaSet method. | [
"Call",
"a",
"ReplicaSet",
"method",
"."
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/replica_sets.py#L708-L715 | train | 37,286 |
10gen/mongo-orchestration | mongo_orchestration/common.py | BaseModel.key_file | def key_file(self):
"""Get the path to the key file containig our auth key, or None."""
if self.auth_key:
key_file_path = os.path.join(orchestration_mkdtemp(), 'key')
with open(key_file_path, 'w') as fd:
fd.write(self.auth_key)
os.chmod(key_file_path, stat.S_IRUSR)
return key_file_path | python | def key_file(self):
"""Get the path to the key file containig our auth key, or None."""
if self.auth_key:
key_file_path = os.path.join(orchestration_mkdtemp(), 'key')
with open(key_file_path, 'w') as fd:
fd.write(self.auth_key)
os.chmod(key_file_path, stat.S_IRUSR)
return key_file_path | [
"def",
"key_file",
"(",
"self",
")",
":",
"if",
"self",
".",
"auth_key",
":",
"key_file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"orchestration_mkdtemp",
"(",
")",
",",
"'key'",
")",
"with",
"open",
"(",
"key_file_path",
",",
"'w'",
")",
"as",
... | Get the path to the key file containig our auth key, or None. | [
"Get",
"the",
"path",
"to",
"the",
"key",
"file",
"containig",
"our",
"auth",
"key",
"or",
"None",
"."
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/common.py#L67-L74 | train | 37,287 |
10gen/mongo-orchestration | mongo_orchestration/common.py | BaseModel._strip_auth | def _strip_auth(self, proc_params):
"""Remove options from parameters that cause auth to be enabled."""
params = proc_params.copy()
params.pop("auth", None)
params.pop("clusterAuthMode", None)
return params | python | def _strip_auth(self, proc_params):
"""Remove options from parameters that cause auth to be enabled."""
params = proc_params.copy()
params.pop("auth", None)
params.pop("clusterAuthMode", None)
return params | [
"def",
"_strip_auth",
"(",
"self",
",",
"proc_params",
")",
":",
"params",
"=",
"proc_params",
".",
"copy",
"(",
")",
"params",
".",
"pop",
"(",
"\"auth\"",
",",
"None",
")",
"params",
".",
"pop",
"(",
"\"clusterAuthMode\"",
",",
"None",
")",
"return",
... | Remove options from parameters that cause auth to be enabled. | [
"Remove",
"options",
"from",
"parameters",
"that",
"cause",
"auth",
"to",
"be",
"enabled",
"."
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/common.py#L76-L81 | train | 37,288 |
10gen/mongo-orchestration | mongo_orchestration/common.py | BaseModel.mongodb_auth_uri | def mongodb_auth_uri(self, hosts):
"""Get a connection string with all info necessary to authenticate."""
parts = ['mongodb://']
if self.login:
parts.append(self.login)
if self.password:
parts.append(':' + self.password)
parts.append('@')
parts.append(hosts + '/')
if self.login:
parts.append('?authSource=' + self.auth_source)
if self.x509_extra_user:
parts.append('&authMechanism=MONGODB-X509')
return ''.join(parts) | python | def mongodb_auth_uri(self, hosts):
"""Get a connection string with all info necessary to authenticate."""
parts = ['mongodb://']
if self.login:
parts.append(self.login)
if self.password:
parts.append(':' + self.password)
parts.append('@')
parts.append(hosts + '/')
if self.login:
parts.append('?authSource=' + self.auth_source)
if self.x509_extra_user:
parts.append('&authMechanism=MONGODB-X509')
return ''.join(parts) | [
"def",
"mongodb_auth_uri",
"(",
"self",
",",
"hosts",
")",
":",
"parts",
"=",
"[",
"'mongodb://'",
"]",
"if",
"self",
".",
"login",
":",
"parts",
".",
"append",
"(",
"self",
".",
"login",
")",
"if",
"self",
".",
"password",
":",
"parts",
".",
"append... | Get a connection string with all info necessary to authenticate. | [
"Get",
"a",
"connection",
"string",
"with",
"all",
"info",
"necessary",
"to",
"authenticate",
"."
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/common.py#L83-L96 | train | 37,289 |
10gen/mongo-orchestration | mongo_orchestration/common.py | BaseModel._add_users | def _add_users(self, db, mongo_version):
"""Add given user, and extra x509 user if necessary."""
if self.x509_extra_user:
# Build dict of kwargs to pass to add_user.
auth_dict = {
'name': DEFAULT_SUBJECT,
'roles': self._user_roles(db.client)
}
db.add_user(**auth_dict)
# Fix kwargs to MongoClient.
self.kwargs['ssl_certfile'] = DEFAULT_CLIENT_CERT
# Add secondary user given from request.
secondary_login = {
'name': self.login,
'roles': self._user_roles(db.client)
}
if self.password:
secondary_login['password'] = self.password
if mongo_version >= (3, 7, 2):
# Use SCRAM_SHA-1 so that pymongo < 3.7 can authenticate.
secondary_login['mechanisms'] = ['SCRAM-SHA-1']
db.add_user(**secondary_login) | python | def _add_users(self, db, mongo_version):
"""Add given user, and extra x509 user if necessary."""
if self.x509_extra_user:
# Build dict of kwargs to pass to add_user.
auth_dict = {
'name': DEFAULT_SUBJECT,
'roles': self._user_roles(db.client)
}
db.add_user(**auth_dict)
# Fix kwargs to MongoClient.
self.kwargs['ssl_certfile'] = DEFAULT_CLIENT_CERT
# Add secondary user given from request.
secondary_login = {
'name': self.login,
'roles': self._user_roles(db.client)
}
if self.password:
secondary_login['password'] = self.password
if mongo_version >= (3, 7, 2):
# Use SCRAM_SHA-1 so that pymongo < 3.7 can authenticate.
secondary_login['mechanisms'] = ['SCRAM-SHA-1']
db.add_user(**secondary_login) | [
"def",
"_add_users",
"(",
"self",
",",
"db",
",",
"mongo_version",
")",
":",
"if",
"self",
".",
"x509_extra_user",
":",
"# Build dict of kwargs to pass to add_user.",
"auth_dict",
"=",
"{",
"'name'",
":",
"DEFAULT_SUBJECT",
",",
"'roles'",
":",
"self",
".",
"_us... | Add given user, and extra x509 user if necessary. | [
"Add",
"given",
"user",
"and",
"extra",
"x509",
"user",
"if",
"necessary",
"."
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/common.py#L108-L131 | train | 37,290 |
10gen/mongo-orchestration | mongo_orchestration/apps/links.py | base_link | def base_link(rel, self_rel=False):
"""Helper for getting a link document under the API root, given a rel."""
link = _BASE_LINKS[rel].copy()
link['rel'] = 'self' if self_rel else rel
return link | python | def base_link(rel, self_rel=False):
"""Helper for getting a link document under the API root, given a rel."""
link = _BASE_LINKS[rel].copy()
link['rel'] = 'self' if self_rel else rel
return link | [
"def",
"base_link",
"(",
"rel",
",",
"self_rel",
"=",
"False",
")",
":",
"link",
"=",
"_BASE_LINKS",
"[",
"rel",
"]",
".",
"copy",
"(",
")",
"link",
"[",
"'rel'",
"]",
"=",
"'self'",
"if",
"self_rel",
"else",
"rel",
"return",
"link"
] | Helper for getting a link document under the API root, given a rel. | [
"Helper",
"for",
"getting",
"a",
"link",
"document",
"under",
"the",
"API",
"root",
"given",
"a",
"rel",
"."
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/apps/links.py#L105-L109 | train | 37,291 |
10gen/mongo-orchestration | mongo_orchestration/apps/links.py | server_link | def server_link(rel, server_id=None, self_rel=False):
"""Helper for getting a Server link document, given a rel."""
servers_href = '/v1/servers'
link = _SERVER_LINKS[rel].copy()
link['href'] = link['href'].format(**locals())
link['rel'] = 'self' if self_rel else rel
return link | python | def server_link(rel, server_id=None, self_rel=False):
"""Helper for getting a Server link document, given a rel."""
servers_href = '/v1/servers'
link = _SERVER_LINKS[rel].copy()
link['href'] = link['href'].format(**locals())
link['rel'] = 'self' if self_rel else rel
return link | [
"def",
"server_link",
"(",
"rel",
",",
"server_id",
"=",
"None",
",",
"self_rel",
"=",
"False",
")",
":",
"servers_href",
"=",
"'/v1/servers'",
"link",
"=",
"_SERVER_LINKS",
"[",
"rel",
"]",
".",
"copy",
"(",
")",
"link",
"[",
"'href'",
"]",
"=",
"link... | Helper for getting a Server link document, given a rel. | [
"Helper",
"for",
"getting",
"a",
"Server",
"link",
"document",
"given",
"a",
"rel",
"."
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/apps/links.py#L130-L136 | train | 37,292 |
10gen/mongo-orchestration | mongo_orchestration/apps/links.py | all_server_links | def all_server_links(server_id, rel_to=None):
"""Get a list of all links to be included with Servers."""
return [
server_link(rel, server_id, self_rel=(rel == rel_to))
for rel in ('delete-server', 'get-server-info', 'server-command')
] | python | def all_server_links(server_id, rel_to=None):
"""Get a list of all links to be included with Servers."""
return [
server_link(rel, server_id, self_rel=(rel == rel_to))
for rel in ('delete-server', 'get-server-info', 'server-command')
] | [
"def",
"all_server_links",
"(",
"server_id",
",",
"rel_to",
"=",
"None",
")",
":",
"return",
"[",
"server_link",
"(",
"rel",
",",
"server_id",
",",
"self_rel",
"=",
"(",
"rel",
"==",
"rel_to",
")",
")",
"for",
"rel",
"in",
"(",
"'delete-server'",
",",
... | Get a list of all links to be included with Servers. | [
"Get",
"a",
"list",
"of",
"all",
"links",
"to",
"be",
"included",
"with",
"Servers",
"."
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/apps/links.py#L139-L144 | train | 37,293 |
10gen/mongo-orchestration | mongo_orchestration/apps/links.py | replica_set_link | def replica_set_link(rel, repl_id=None, member_id=None, self_rel=False):
"""Helper for getting a ReplicaSet link document, given a rel."""
repls_href = '/v1/replica_sets'
link = _REPLICA_SET_LINKS[rel].copy()
link['href'] = link['href'].format(**locals())
link['rel'] = 'self' if self_rel else rel
return link | python | def replica_set_link(rel, repl_id=None, member_id=None, self_rel=False):
"""Helper for getting a ReplicaSet link document, given a rel."""
repls_href = '/v1/replica_sets'
link = _REPLICA_SET_LINKS[rel].copy()
link['href'] = link['href'].format(**locals())
link['rel'] = 'self' if self_rel else rel
return link | [
"def",
"replica_set_link",
"(",
"rel",
",",
"repl_id",
"=",
"None",
",",
"member_id",
"=",
"None",
",",
"self_rel",
"=",
"False",
")",
":",
"repls_href",
"=",
"'/v1/replica_sets'",
"link",
"=",
"_REPLICA_SET_LINKS",
"[",
"rel",
"]",
".",
"copy",
"(",
")",
... | Helper for getting a ReplicaSet link document, given a rel. | [
"Helper",
"for",
"getting",
"a",
"ReplicaSet",
"link",
"document",
"given",
"a",
"rel",
"."
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/apps/links.py#L147-L153 | train | 37,294 |
10gen/mongo-orchestration | mongo_orchestration/apps/links.py | all_replica_set_links | def all_replica_set_links(rs_id, rel_to=None):
"""Get a list of all links to be included with replica sets."""
return [
replica_set_link(rel, rs_id, self_rel=(rel == rel_to))
for rel in (
'get-replica-set-info',
'delete-replica-set', 'replica-set-command',
'get-replica-set-members', 'add-replica-set-member',
'get-replica-set-secondaries', 'get-replica-set-primary',
'get-replica-set-arbiters', 'get-replica-set-hidden-members',
'get-replica-set-passive-members', 'get-replica-set-servers'
)
] | python | def all_replica_set_links(rs_id, rel_to=None):
"""Get a list of all links to be included with replica sets."""
return [
replica_set_link(rel, rs_id, self_rel=(rel == rel_to))
for rel in (
'get-replica-set-info',
'delete-replica-set', 'replica-set-command',
'get-replica-set-members', 'add-replica-set-member',
'get-replica-set-secondaries', 'get-replica-set-primary',
'get-replica-set-arbiters', 'get-replica-set-hidden-members',
'get-replica-set-passive-members', 'get-replica-set-servers'
)
] | [
"def",
"all_replica_set_links",
"(",
"rs_id",
",",
"rel_to",
"=",
"None",
")",
":",
"return",
"[",
"replica_set_link",
"(",
"rel",
",",
"rs_id",
",",
"self_rel",
"=",
"(",
"rel",
"==",
"rel_to",
")",
")",
"for",
"rel",
"in",
"(",
"'get-replica-set-info'",
... | Get a list of all links to be included with replica sets. | [
"Get",
"a",
"list",
"of",
"all",
"links",
"to",
"be",
"included",
"with",
"replica",
"sets",
"."
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/apps/links.py#L156-L168 | train | 37,295 |
10gen/mongo-orchestration | mongo_orchestration/apps/links.py | sharded_cluster_link | def sharded_cluster_link(rel, cluster_id=None,
shard_id=None, router_id=None, self_rel=False):
"""Helper for getting a ShardedCluster link document, given a rel."""
clusters_href = '/v1/sharded_clusters'
link = _SHARDED_CLUSTER_LINKS[rel].copy()
link['href'] = link['href'].format(**locals())
link['rel'] = 'self' if self_rel else rel
return link | python | def sharded_cluster_link(rel, cluster_id=None,
shard_id=None, router_id=None, self_rel=False):
"""Helper for getting a ShardedCluster link document, given a rel."""
clusters_href = '/v1/sharded_clusters'
link = _SHARDED_CLUSTER_LINKS[rel].copy()
link['href'] = link['href'].format(**locals())
link['rel'] = 'self' if self_rel else rel
return link | [
"def",
"sharded_cluster_link",
"(",
"rel",
",",
"cluster_id",
"=",
"None",
",",
"shard_id",
"=",
"None",
",",
"router_id",
"=",
"None",
",",
"self_rel",
"=",
"False",
")",
":",
"clusters_href",
"=",
"'/v1/sharded_clusters'",
"link",
"=",
"_SHARDED_CLUSTER_LINKS"... | Helper for getting a ShardedCluster link document, given a rel. | [
"Helper",
"for",
"getting",
"a",
"ShardedCluster",
"link",
"document",
"given",
"a",
"rel",
"."
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/apps/links.py#L171-L178 | train | 37,296 |
10gen/mongo-orchestration | mongo_orchestration/apps/links.py | all_sharded_cluster_links | def all_sharded_cluster_links(cluster_id, shard_id=None,
router_id=None, rel_to=None):
"""Get a list of all links to be included with ShardedClusters."""
return [
sharded_cluster_link(rel, cluster_id, shard_id, router_id,
self_rel=(rel == rel_to))
for rel in (
'get-sharded-clusters', 'get-sharded-cluster-info',
'sharded-cluster-command', 'delete-sharded-cluster',
'add-shard', 'get-shards', 'get-configsvrs',
'get-routers', 'add-router'
)
] | python | def all_sharded_cluster_links(cluster_id, shard_id=None,
router_id=None, rel_to=None):
"""Get a list of all links to be included with ShardedClusters."""
return [
sharded_cluster_link(rel, cluster_id, shard_id, router_id,
self_rel=(rel == rel_to))
for rel in (
'get-sharded-clusters', 'get-sharded-cluster-info',
'sharded-cluster-command', 'delete-sharded-cluster',
'add-shard', 'get-shards', 'get-configsvrs',
'get-routers', 'add-router'
)
] | [
"def",
"all_sharded_cluster_links",
"(",
"cluster_id",
",",
"shard_id",
"=",
"None",
",",
"router_id",
"=",
"None",
",",
"rel_to",
"=",
"None",
")",
":",
"return",
"[",
"sharded_cluster_link",
"(",
"rel",
",",
"cluster_id",
",",
"shard_id",
",",
"router_id",
... | Get a list of all links to be included with ShardedClusters. | [
"Get",
"a",
"list",
"of",
"all",
"links",
"to",
"be",
"included",
"with",
"ShardedClusters",
"."
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/apps/links.py#L181-L193 | train | 37,297 |
10gen/mongo-orchestration | mongo_orchestration/__init__.py | cleanup_storage | def cleanup_storage(*args):
"""Clean up processes after SIGTERM or SIGINT is received."""
ShardedClusters().cleanup()
ReplicaSets().cleanup()
Servers().cleanup()
sys.exit(0) | python | def cleanup_storage(*args):
"""Clean up processes after SIGTERM or SIGINT is received."""
ShardedClusters().cleanup()
ReplicaSets().cleanup()
Servers().cleanup()
sys.exit(0) | [
"def",
"cleanup_storage",
"(",
"*",
"args",
")",
":",
"ShardedClusters",
"(",
")",
".",
"cleanup",
"(",
")",
"ReplicaSets",
"(",
")",
".",
"cleanup",
"(",
")",
"Servers",
"(",
")",
".",
"cleanup",
"(",
")",
"sys",
".",
"exit",
"(",
"0",
")"
] | Clean up processes after SIGTERM or SIGINT is received. | [
"Clean",
"up",
"processes",
"after",
"SIGTERM",
"or",
"SIGINT",
"is",
"received",
"."
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/__init__.py#L32-L37 | train | 37,298 |
10gen/mongo-orchestration | mongo_orchestration/server.py | read_env | def read_env():
"""return command-line arguments"""
parser = argparse.ArgumentParser(description='mongo-orchestration server')
parser.add_argument('-f', '--config',
action='store', default=None, type=str, dest='config')
parser.add_argument('-e', '--env',
action='store', type=str, dest='env', default=None)
parser.add_argument(action='store', type=str, dest='command',
default='start', choices=('start', 'stop', 'restart'))
parser.add_argument('--no-fork',
action='store_true', dest='no_fork', default=False)
parser.add_argument('-b', '--bind',
action='store', dest='bind', type=str,
default=DEFAULT_BIND)
parser.add_argument('-p', '--port',
action='store', dest='port', type=int,
default=DEFAULT_PORT)
parser.add_argument('--enable-majority-read-concern', action='store_true',
default=False)
parser.add_argument('-s', '--server',
action='store', dest='server', type=str,
default=DEFAULT_SERVER, choices=('cherrypy', 'wsgiref'))
parser.add_argument('--version', action='version',
version='Mongo Orchestration v' + __version__)
parser.add_argument('--socket-timeout-ms', action='store',
dest='socket_timeout',
type=int, default=DEFAULT_SOCKET_TIMEOUT)
parser.add_argument('--pidfile', action='store', type=str, dest='pidfile',
default=PID_FILE)
cli_args = parser.parse_args()
if cli_args.env and not cli_args.config:
print("Specified release '%s' without a config file" % cli_args.env)
sys.exit(1)
if cli_args.command == 'stop' or not cli_args.config:
return cli_args
try:
# read config
with open(cli_args.config, 'r') as fd:
config = json.loads(fd.read(), object_pairs_hook=SON)
if not 'releases' in config:
print("No releases defined in %s" % cli_args.config)
sys.exit(1)
releases = config['releases']
if cli_args.env is not None and cli_args.env not in releases:
print("Release '%s' is not defined in %s"
% (cli_args.env, cli_args.config))
sys.exit(1)
cli_args.releases = releases
return cli_args
except (IOError):
print("config file not found")
sys.exit(1)
except (ValueError):
print("config file is corrupted")
sys.exit(1) | python | def read_env():
"""return command-line arguments"""
parser = argparse.ArgumentParser(description='mongo-orchestration server')
parser.add_argument('-f', '--config',
action='store', default=None, type=str, dest='config')
parser.add_argument('-e', '--env',
action='store', type=str, dest='env', default=None)
parser.add_argument(action='store', type=str, dest='command',
default='start', choices=('start', 'stop', 'restart'))
parser.add_argument('--no-fork',
action='store_true', dest='no_fork', default=False)
parser.add_argument('-b', '--bind',
action='store', dest='bind', type=str,
default=DEFAULT_BIND)
parser.add_argument('-p', '--port',
action='store', dest='port', type=int,
default=DEFAULT_PORT)
parser.add_argument('--enable-majority-read-concern', action='store_true',
default=False)
parser.add_argument('-s', '--server',
action='store', dest='server', type=str,
default=DEFAULT_SERVER, choices=('cherrypy', 'wsgiref'))
parser.add_argument('--version', action='version',
version='Mongo Orchestration v' + __version__)
parser.add_argument('--socket-timeout-ms', action='store',
dest='socket_timeout',
type=int, default=DEFAULT_SOCKET_TIMEOUT)
parser.add_argument('--pidfile', action='store', type=str, dest='pidfile',
default=PID_FILE)
cli_args = parser.parse_args()
if cli_args.env and not cli_args.config:
print("Specified release '%s' without a config file" % cli_args.env)
sys.exit(1)
if cli_args.command == 'stop' or not cli_args.config:
return cli_args
try:
# read config
with open(cli_args.config, 'r') as fd:
config = json.loads(fd.read(), object_pairs_hook=SON)
if not 'releases' in config:
print("No releases defined in %s" % cli_args.config)
sys.exit(1)
releases = config['releases']
if cli_args.env is not None and cli_args.env not in releases:
print("Release '%s' is not defined in %s"
% (cli_args.env, cli_args.config))
sys.exit(1)
cli_args.releases = releases
return cli_args
except (IOError):
print("config file not found")
sys.exit(1)
except (ValueError):
print("config file is corrupted")
sys.exit(1) | [
"def",
"read_env",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'mongo-orchestration server'",
")",
"parser",
".",
"add_argument",
"(",
"'-f'",
",",
"'--config'",
",",
"action",
"=",
"'store'",
",",
"default",
"=",... | return command-line arguments | [
"return",
"command",
"-",
"line",
"arguments"
] | 81fd2224205922ea2178b08190b53a33aec47261 | https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/server.py#L36-L92 | train | 37,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.