repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
cyface/django-termsandconditions
termsandconditions/views.py
TermsView.get_context_data
def get_context_data(self, **kwargs): """Pass additional context data""" context = super(TermsView, self).get_context_data(**kwargs) context['terms_base_template'] = getattr(settings, 'TERMS_BASE_TEMPLATE', DEFAULT_TERMS_BASE_TEMPLATE) return context
python
def get_context_data(self, **kwargs): """Pass additional context data""" context = super(TermsView, self).get_context_data(**kwargs) context['terms_base_template'] = getattr(settings, 'TERMS_BASE_TEMPLATE', DEFAULT_TERMS_BASE_TEMPLATE) return context
[ "def", "get_context_data", "(", "self", ",", "*", "*", "kwargs", ")", ":", "context", "=", "super", "(", "TermsView", ",", "self", ")", ".", "get_context_data", "(", "*", "*", "kwargs", ")", "context", "[", "'terms_base_template'", "]", "=", "getattr", "...
Pass additional context data
[ "Pass", "additional", "context", "data" ]
e18f06d0bad1e047f99222d1153f6e2b3bd5224f
https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/views.py#L53-L57
train
cyface/django-termsandconditions
termsandconditions/views.py
AcceptTermsView.get_initial
def get_initial(self): """Override of CreateView method, queries for which T&C to accept and catches returnTo from URL""" LOGGER.debug('termsandconditions.views.AcceptTermsView.get_initial') terms = self.get_terms(self.kwargs) return_to = self.request.GET.get('returnTo', '/') r...
python
def get_initial(self): """Override of CreateView method, queries for which T&C to accept and catches returnTo from URL""" LOGGER.debug('termsandconditions.views.AcceptTermsView.get_initial') terms = self.get_terms(self.kwargs) return_to = self.request.GET.get('returnTo', '/') r...
[ "def", "get_initial", "(", "self", ")", ":", "LOGGER", ".", "debug", "(", "'termsandconditions.views.AcceptTermsView.get_initial'", ")", "terms", "=", "self", ".", "get_terms", "(", "self", ".", "kwargs", ")", "return_to", "=", "self", ".", "request", ".", "GE...
Override of CreateView method, queries for which T&C to accept and catches returnTo from URL
[ "Override", "of", "CreateView", "method", "queries", "for", "which", "T&C", "to", "accept", "and", "catches", "returnTo", "from", "URL" ]
e18f06d0bad1e047f99222d1153f6e2b3bd5224f
https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/views.py#L82-L89
train
cyface/django-termsandconditions
termsandconditions/views.py
AcceptTermsView.post
def post(self, request, *args, **kwargs): """ Handles POST request. """ return_url = request.POST.get('returnTo', '/') terms_ids = request.POST.getlist('terms') if not terms_ids: # pragma: nocover return HttpResponseRedirect(return_url) if DJANGO_VE...
python
def post(self, request, *args, **kwargs): """ Handles POST request. """ return_url = request.POST.get('returnTo', '/') terms_ids = request.POST.getlist('terms') if not terms_ids: # pragma: nocover return HttpResponseRedirect(return_url) if DJANGO_VE...
[ "def", "post", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return_url", "=", "request", ".", "POST", ".", "get", "(", "'returnTo'", ",", "'/'", ")", "terms_ids", "=", "request", ".", "POST", ".", "getlist", "(...
Handles POST request.
[ "Handles", "POST", "request", "." ]
e18f06d0bad1e047f99222d1153f6e2b3bd5224f
https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/views.py#L91-L133
train
cyface/django-termsandconditions
termsandconditions/views.py
EmailTermsView.form_valid
def form_valid(self, form): """Override of CreateView method, sends the email.""" LOGGER.debug('termsandconditions.views.EmailTermsView.form_valid') template = get_template("termsandconditions/tc_email_terms.html") template_rendered = template.render({"terms": form.cleaned_data.get('ter...
python
def form_valid(self, form): """Override of CreateView method, sends the email.""" LOGGER.debug('termsandconditions.views.EmailTermsView.form_valid') template = get_template("termsandconditions/tc_email_terms.html") template_rendered = template.render({"terms": form.cleaned_data.get('ter...
[ "def", "form_valid", "(", "self", ",", "form", ")", ":", "LOGGER", ".", "debug", "(", "'termsandconditions.views.EmailTermsView.form_valid'", ")", "template", "=", "get_template", "(", "\"termsandconditions/tc_email_terms.html\"", ")", "template_rendered", "=", "template"...
Override of CreateView method, sends the email.
[ "Override", "of", "CreateView", "method", "sends", "the", "email", "." ]
e18f06d0bad1e047f99222d1153f6e2b3bd5224f
https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/views.py#L162-L184
train
cyface/django-termsandconditions
termsandconditions/views.py
EmailTermsView.form_invalid
def form_invalid(self, form): """Override of CreateView method, logs invalid email form submissions.""" LOGGER.debug("Invalid Email Form Submitted") messages.add_message(self.request, messages.ERROR, _("Invalid Email Address.")) return super(EmailTermsView, self).form_invalid(form)
python
def form_invalid(self, form): """Override of CreateView method, logs invalid email form submissions.""" LOGGER.debug("Invalid Email Form Submitted") messages.add_message(self.request, messages.ERROR, _("Invalid Email Address.")) return super(EmailTermsView, self).form_invalid(form)
[ "def", "form_invalid", "(", "self", ",", "form", ")", ":", "LOGGER", ".", "debug", "(", "\"Invalid Email Form Submitted\"", ")", "messages", ".", "add_message", "(", "self", ".", "request", ",", "messages", ".", "ERROR", ",", "_", "(", "\"Invalid Email Address...
Override of CreateView method, logs invalid email form submissions.
[ "Override", "of", "CreateView", "method", "logs", "invalid", "email", "form", "submissions", "." ]
e18f06d0bad1e047f99222d1153f6e2b3bd5224f
https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/views.py#L186-L190
train
cyface/django-termsandconditions
termsandconditions/decorators.py
terms_required
def terms_required(view_func): """ This decorator checks to see if the user is logged in, and if so, if they have accepted the site terms. """ @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): """Method to wrap the view passed in""" ...
python
def terms_required(view_func): """ This decorator checks to see if the user is logged in, and if so, if they have accepted the site terms. """ @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): """Method to wrap the view passed in""" ...
[ "def", "terms_required", "(", "view_func", ")", ":", "@", "wraps", "(", "view_func", ",", "assigned", "=", "available_attrs", "(", "view_func", ")", ")", "def", "_wrapped_view", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"...
This decorator checks to see if the user is logged in, and if so, if they have accepted the site terms.
[ "This", "decorator", "checks", "to", "see", "if", "the", "user", "is", "logged", "in", "and", "if", "so", "if", "they", "have", "accepted", "the", "site", "terms", "." ]
e18f06d0bad1e047f99222d1153f6e2b3bd5224f
https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/decorators.py#L11-L36
train
cyface/django-termsandconditions
termsandconditions/models.py
TermsAndConditions.get_active
def get_active(slug=DEFAULT_TERMS_SLUG): """Finds the latest of a particular terms and conditions""" active_terms = cache.get('tandc.active_terms_' + slug) if active_terms is None: try: active_terms = TermsAndConditions.objects.filter( date_active...
python
def get_active(slug=DEFAULT_TERMS_SLUG): """Finds the latest of a particular terms and conditions""" active_terms = cache.get('tandc.active_terms_' + slug) if active_terms is None: try: active_terms = TermsAndConditions.objects.filter( date_active...
[ "def", "get_active", "(", "slug", "=", "DEFAULT_TERMS_SLUG", ")", ":", "active_terms", "=", "cache", ".", "get", "(", "'tandc.active_terms_'", "+", "slug", ")", "if", "active_terms", "is", "None", ":", "try", ":", "active_terms", "=", "TermsAndConditions", "."...
Finds the latest of a particular terms and conditions
[ "Finds", "the", "latest", "of", "a", "particular", "terms", "and", "conditions" ]
e18f06d0bad1e047f99222d1153f6e2b3bd5224f
https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/models.py#L75-L90
train
cyface/django-termsandconditions
termsandconditions/models.py
TermsAndConditions.get_active_terms_ids
def get_active_terms_ids(): """Returns a list of the IDs of of all terms and conditions""" active_terms_ids = cache.get('tandc.active_terms_ids') if active_terms_ids is None: active_terms_dict = {} active_terms_ids = [] active_terms_set = TermsAndConditions....
python
def get_active_terms_ids(): """Returns a list of the IDs of of all terms and conditions""" active_terms_ids = cache.get('tandc.active_terms_ids') if active_terms_ids is None: active_terms_dict = {} active_terms_ids = [] active_terms_set = TermsAndConditions....
[ "def", "get_active_terms_ids", "(", ")", ":", "active_terms_ids", "=", "cache", ".", "get", "(", "'tandc.active_terms_ids'", ")", "if", "active_terms_ids", "is", "None", ":", "active_terms_dict", "=", "{", "}", "active_terms_ids", "=", "[", "]", "active_terms_set"...
Returns a list of the IDs of of all terms and conditions
[ "Returns", "a", "list", "of", "the", "IDs", "of", "of", "all", "terms", "and", "conditions" ]
e18f06d0bad1e047f99222d1153f6e2b3bd5224f
https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/models.py#L93-L112
train
cyface/django-termsandconditions
termsandconditions/models.py
TermsAndConditions.get_active_terms_list
def get_active_terms_list(): """Returns all the latest active terms and conditions""" active_terms_list = cache.get('tandc.active_terms_list') if active_terms_list is None: active_terms_list = TermsAndConditions.objects.filter(id__in=TermsAndConditions.get_active_terms_ids()).order_...
python
def get_active_terms_list(): """Returns all the latest active terms and conditions""" active_terms_list = cache.get('tandc.active_terms_list') if active_terms_list is None: active_terms_list = TermsAndConditions.objects.filter(id__in=TermsAndConditions.get_active_terms_ids()).order_...
[ "def", "get_active_terms_list", "(", ")", ":", "active_terms_list", "=", "cache", ".", "get", "(", "'tandc.active_terms_list'", ")", "if", "active_terms_list", "is", "None", ":", "active_terms_list", "=", "TermsAndConditions", ".", "objects", ".", "filter", "(", "...
Returns all the latest active terms and conditions
[ "Returns", "all", "the", "latest", "active", "terms", "and", "conditions" ]
e18f06d0bad1e047f99222d1153f6e2b3bd5224f
https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/models.py#L115-L123
train
cyface/django-termsandconditions
termsandconditions/models.py
TermsAndConditions.get_active_terms_not_agreed_to
def get_active_terms_not_agreed_to(user): """Checks to see if a specified user has agreed to all the latest terms and conditions""" if TERMS_EXCLUDE_USERS_WITH_PERM is not None: if user.has_perm(TERMS_EXCLUDE_USERS_WITH_PERM) and not user.is_superuser: # Django's has_perm() ...
python
def get_active_terms_not_agreed_to(user): """Checks to see if a specified user has agreed to all the latest terms and conditions""" if TERMS_EXCLUDE_USERS_WITH_PERM is not None: if user.has_perm(TERMS_EXCLUDE_USERS_WITH_PERM) and not user.is_superuser: # Django's has_perm() ...
[ "def", "get_active_terms_not_agreed_to", "(", "user", ")", ":", "if", "TERMS_EXCLUDE_USERS_WITH_PERM", "is", "not", "None", ":", "if", "user", ".", "has_perm", "(", "TERMS_EXCLUDE_USERS_WITH_PERM", ")", "and", "not", "user", ".", "is_superuser", ":", "# Django's has...
Checks to see if a specified user has agreed to all the latest terms and conditions
[ "Checks", "to", "see", "if", "a", "specified", "user", "has", "agreed", "to", "all", "the", "latest", "terms", "and", "conditions" ]
e18f06d0bad1e047f99222d1153f6e2b3bd5224f
https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/models.py#L126-L146
train
cyface/django-termsandconditions
termsandconditions/templatetags/terms_tags.py
show_terms_if_not_agreed
def show_terms_if_not_agreed(context, field=TERMS_HTTP_PATH_FIELD): """Displays a modal on a current page if a user has not yet agreed to the given terms. If terms are not specified, the default slug is used. A small snippet is included into your template if a user who requested the view has not yet ag...
python
def show_terms_if_not_agreed(context, field=TERMS_HTTP_PATH_FIELD): """Displays a modal on a current page if a user has not yet agreed to the given terms. If terms are not specified, the default slug is used. A small snippet is included into your template if a user who requested the view has not yet ag...
[ "def", "show_terms_if_not_agreed", "(", "context", ",", "field", "=", "TERMS_HTTP_PATH_FIELD", ")", ":", "request", "=", "context", "[", "'request'", "]", "url", "=", "urlparse", "(", "request", ".", "META", "[", "field", "]", ")", "not_agreed_terms", "=", "...
Displays a modal on a current page if a user has not yet agreed to the given terms. If terms are not specified, the default slug is used. A small snippet is included into your template if a user who requested the view has not yet agreed the terms. The snippet takes care of displaying a respective modal...
[ "Displays", "a", "modal", "on", "a", "current", "page", "if", "a", "user", "has", "not", "yet", "agreed", "to", "the", "given", "terms", ".", "If", "terms", "are", "not", "specified", "the", "default", "slug", "is", "used", "." ]
e18f06d0bad1e047f99222d1153f6e2b3bd5224f
https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/templatetags/terms_tags.py#L15-L30
train
cyface/django-termsandconditions
termsandconditions/pipeline.py
user_accept_terms
def user_accept_terms(backend, user, uid, social_user=None, *args, **kwargs): """Check if the user has accepted the terms and conditions after creation.""" LOGGER.debug('user_accept_terms') if TermsAndConditions.get_active_terms_not_agreed_to(user): return redirect_to_terms_accept('/') else: ...
python
def user_accept_terms(backend, user, uid, social_user=None, *args, **kwargs): """Check if the user has accepted the terms and conditions after creation.""" LOGGER.debug('user_accept_terms') if TermsAndConditions.get_active_terms_not_agreed_to(user): return redirect_to_terms_accept('/') else: ...
[ "def", "user_accept_terms", "(", "backend", ",", "user", ",", "uid", ",", "social_user", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "LOGGER", ".", "debug", "(", "'user_accept_terms'", ")", "if", "TermsAndConditions", ".", "get_active...
Check if the user has accepted the terms and conditions after creation.
[ "Check", "if", "the", "user", "has", "accepted", "the", "terms", "and", "conditions", "after", "creation", "." ]
e18f06d0bad1e047f99222d1153f6e2b3bd5224f
https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/pipeline.py#L17-L25
train
cyface/django-termsandconditions
termsandconditions/pipeline.py
redirect_to_terms_accept
def redirect_to_terms_accept(current_path='/', slug='default'): """Redirect the user to the terms and conditions accept page.""" redirect_url_parts = list(urlparse(ACCEPT_TERMS_PATH)) if slug != 'default': redirect_url_parts[2] += slug querystring = QueryDict(redirect_url_parts[4], mutable=True)...
python
def redirect_to_terms_accept(current_path='/', slug='default'): """Redirect the user to the terms and conditions accept page.""" redirect_url_parts = list(urlparse(ACCEPT_TERMS_PATH)) if slug != 'default': redirect_url_parts[2] += slug querystring = QueryDict(redirect_url_parts[4], mutable=True)...
[ "def", "redirect_to_terms_accept", "(", "current_path", "=", "'/'", ",", "slug", "=", "'default'", ")", ":", "redirect_url_parts", "=", "list", "(", "urlparse", "(", "ACCEPT_TERMS_PATH", ")", ")", "if", "slug", "!=", "'default'", ":", "redirect_url_parts", "[", ...
Redirect the user to the terms and conditions accept page.
[ "Redirect", "the", "user", "to", "the", "terms", "and", "conditions", "accept", "page", "." ]
e18f06d0bad1e047f99222d1153f6e2b3bd5224f
https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/pipeline.py#L28-L36
train
cyface/django-termsandconditions
termsandconditions/signals.py
user_terms_updated
def user_terms_updated(sender, **kwargs): """Called when user terms and conditions is changed - to force cache clearing""" LOGGER.debug("User T&C Updated Signal Handler") if kwargs.get('instance').user: cache.delete('tandc.not_agreed_terms_' + kwargs.get('instance').user.get_username())
python
def user_terms_updated(sender, **kwargs): """Called when user terms and conditions is changed - to force cache clearing""" LOGGER.debug("User T&C Updated Signal Handler") if kwargs.get('instance').user: cache.delete('tandc.not_agreed_terms_' + kwargs.get('instance').user.get_username())
[ "def", "user_terms_updated", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "LOGGER", ".", "debug", "(", "\"User T&C Updated Signal Handler\"", ")", "if", "kwargs", ".", "get", "(", "'instance'", ")", ".", "user", ":", "cache", ".", "delete", "(", "'tan...
Called when user terms and conditions is changed - to force cache clearing
[ "Called", "when", "user", "terms", "and", "conditions", "is", "changed", "-", "to", "force", "cache", "clearing" ]
e18f06d0bad1e047f99222d1153f6e2b3bd5224f
https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/signals.py#L15-L19
train
cyface/django-termsandconditions
termsandconditions/signals.py
terms_updated
def terms_updated(sender, **kwargs): """Called when terms and conditions is changed - to force cache clearing""" LOGGER.debug("T&C Updated Signal Handler") cache.delete('tandc.active_terms_ids') cache.delete('tandc.active_terms_list') if kwargs.get('instance').slug: cache.delete('tandc.activ...
python
def terms_updated(sender, **kwargs): """Called when terms and conditions is changed - to force cache clearing""" LOGGER.debug("T&C Updated Signal Handler") cache.delete('tandc.active_terms_ids') cache.delete('tandc.active_terms_list') if kwargs.get('instance').slug: cache.delete('tandc.activ...
[ "def", "terms_updated", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "LOGGER", ".", "debug", "(", "\"T&C Updated Signal Handler\"", ")", "cache", ".", "delete", "(", "'tandc.active_terms_ids'", ")", "cache", ".", "delete", "(", "'tandc.active_terms_list'", ...
Called when terms and conditions is changed - to force cache clearing
[ "Called", "when", "terms", "and", "conditions", "is", "changed", "-", "to", "force", "cache", "clearing" ]
e18f06d0bad1e047f99222d1153f6e2b3bd5224f
https://github.com/cyface/django-termsandconditions/blob/e18f06d0bad1e047f99222d1153f6e2b3bd5224f/termsandconditions/signals.py#L23-L31
train
shtalinberg/django-el-pagination
el_pagination/templatetags/el_pagination_tags.py
paginate
def paginate(parser, token, paginator_class=None): """Paginate objects. Usage: .. code-block:: html+django {% paginate entries %} After this call, the *entries* variable in the template context is replaced by only the entries of the current page. You can also keep your *entries* ori...
python
def paginate(parser, token, paginator_class=None): """Paginate objects. Usage: .. code-block:: html+django {% paginate entries %} After this call, the *entries* variable in the template context is replaced by only the entries of the current page. You can also keep your *entries* ori...
[ "def", "paginate", "(", "parser", ",", "token", ",", "paginator_class", "=", "None", ")", ":", "# Validate arguments.", "try", ":", "tag_name", ",", "tag_args", "=", "token", ".", "contents", ".", "split", "(", "None", ",", "1", ")", "except", "ValueError"...
Paginate objects. Usage: .. code-block:: html+django {% paginate entries %} After this call, the *entries* variable in the template context is replaced by only the entries of the current page. You can also keep your *entries* original variable (usually a queryset) and add to the con...
[ "Paginate", "objects", "." ]
889ba62b46cb58292d554753a0bfda0b0a6d57da
https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/templatetags/el_pagination_tags.py#L45-L185
train
shtalinberg/django-el-pagination
el_pagination/templatetags/el_pagination_tags.py
get_pages
def get_pages(parser, token): """Add to context the list of page links. Usage: .. code-block:: html+django {% get_pages %} This is mostly used for Digg-style pagination. This call inserts in the template context a *pages* variable, as a sequence of page links. You can use *pages* in ...
python
def get_pages(parser, token): """Add to context the list of page links. Usage: .. code-block:: html+django {% get_pages %} This is mostly used for Digg-style pagination. This call inserts in the template context a *pages* variable, as a sequence of page links. You can use *pages* in ...
[ "def", "get_pages", "(", "parser", ",", "token", ")", ":", "# Validate args.", "try", ":", "tag_name", ",", "args", "=", "token", ".", "contents", ".", "split", "(", "None", ",", "1", ")", "except", "ValueError", ":", "var_name", "=", "'pages'", "else", ...
Add to context the list of page links. Usage: .. code-block:: html+django {% get_pages %} This is mostly used for Digg-style pagination. This call inserts in the template context a *pages* variable, as a sequence of page links. You can use *pages* in different ways: - just print *pa...
[ "Add", "to", "context", "the", "list", "of", "page", "links", "." ]
889ba62b46cb58292d554753a0bfda0b0a6d57da
https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/templatetags/el_pagination_tags.py#L378-L500
train
shtalinberg/django-el-pagination
el_pagination/templatetags/el_pagination_tags.py
show_pages
def show_pages(parser, token): """Show page links. Usage: .. code-block:: html+django {% show_pages %} It is just a shortcut for: .. code-block:: html+django {% get_pages %} {{ pages.get_rendered }} You can set ``ENDLESS_PAGINATION_PAGE_LIST_CALLABLE`` in your *set...
python
def show_pages(parser, token): """Show page links. Usage: .. code-block:: html+django {% show_pages %} It is just a shortcut for: .. code-block:: html+django {% get_pages %} {{ pages.get_rendered }} You can set ``ENDLESS_PAGINATION_PAGE_LIST_CALLABLE`` in your *set...
[ "def", "show_pages", "(", "parser", ",", "token", ")", ":", "# Validate args.", "if", "len", "(", "token", ".", "contents", ".", "split", "(", ")", ")", "!=", "1", ":", "msg", "=", "'%r tag takes no arguments'", "%", "token", ".", "contents", ".", "split...
Show page links. Usage: .. code-block:: html+django {% show_pages %} It is just a shortcut for: .. code-block:: html+django {% get_pages %} {{ pages.get_rendered }} You can set ``ENDLESS_PAGINATION_PAGE_LIST_CALLABLE`` in your *settings.py* to a callable, or to a d...
[ "Show", "page", "links", "." ]
889ba62b46cb58292d554753a0bfda0b0a6d57da
https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/templatetags/el_pagination_tags.py#L526-L556
train
shtalinberg/django-el-pagination
el_pagination/templatetags/el_pagination_tags.py
show_current_number
def show_current_number(parser, token): """Show the current page number, or insert it in the context. This tag can for example be useful to change the page title according to the current page number. To just show current page number: .. code-block:: html+django {% show_current_number %} ...
python
def show_current_number(parser, token): """Show the current page number, or insert it in the context. This tag can for example be useful to change the page title according to the current page number. To just show current page number: .. code-block:: html+django {% show_current_number %} ...
[ "def", "show_current_number", "(", "parser", ",", "token", ")", ":", "# Validate args.", "try", ":", "tag_name", ",", "args", "=", "token", ".", "contents", ".", "split", "(", "None", ",", "1", ")", "except", "ValueError", ":", "key", "=", "None", "numbe...
Show the current page number, or insert it in the context. This tag can for example be useful to change the page title according to the current page number. To just show current page number: .. code-block:: html+django {% show_current_number %} If you use multiple paginations in the sam...
[ "Show", "the", "current", "page", "number", "or", "insert", "it", "in", "the", "context", "." ]
889ba62b46cb58292d554753a0bfda0b0a6d57da
https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/templatetags/el_pagination_tags.py#L579-L649
train
shtalinberg/django-el-pagination
el_pagination/decorators.py
page_template
def page_template(template, key=PAGE_LABEL): """Return a view dynamically switching template if the request is Ajax. Decorate a view that takes a *template* and *extra_context* keyword arguments (like generic views). The template is switched to *page_template* if request is ajax and if *querystring...
python
def page_template(template, key=PAGE_LABEL): """Return a view dynamically switching template if the request is Ajax. Decorate a view that takes a *template* and *extra_context* keyword arguments (like generic views). The template is switched to *page_template* if request is ajax and if *querystring...
[ "def", "page_template", "(", "template", ",", "key", "=", "PAGE_LABEL", ")", ":", "def", "decorator", "(", "view", ")", ":", "@", "wraps", "(", "view", ")", "def", "decorated", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "#...
Return a view dynamically switching template if the request is Ajax. Decorate a view that takes a *template* and *extra_context* keyword arguments (like generic views). The template is switched to *page_template* if request is ajax and if *querystring_key* variable passed by the request equals to *key*...
[ "Return", "a", "view", "dynamically", "switching", "template", "if", "the", "request", "is", "Ajax", "." ]
889ba62b46cb58292d554753a0bfda0b0a6d57da
https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/decorators.py#L13-L39
train
shtalinberg/django-el-pagination
el_pagination/decorators.py
_get_template
def _get_template(querystring_key, mapping): """Return the template corresponding to the given ``querystring_key``.""" default = None try: template_and_keys = mapping.items() except AttributeError: template_and_keys = mapping for template, key in template_and_keys: if key is ...
python
def _get_template(querystring_key, mapping): """Return the template corresponding to the given ``querystring_key``.""" default = None try: template_and_keys = mapping.items() except AttributeError: template_and_keys = mapping for template, key in template_and_keys: if key is ...
[ "def", "_get_template", "(", "querystring_key", ",", "mapping", ")", ":", "default", "=", "None", "try", ":", "template_and_keys", "=", "mapping", ".", "items", "(", ")", "except", "AttributeError", ":", "template_and_keys", "=", "mapping", "for", "template", ...
Return the template corresponding to the given ``querystring_key``.
[ "Return", "the", "template", "corresponding", "to", "the", "given", "querystring_key", "." ]
889ba62b46cb58292d554753a0bfda0b0a6d57da
https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/decorators.py#L42-L55
train
shtalinberg/django-el-pagination
el_pagination/views.py
MultipleObjectMixin.get_queryset
def get_queryset(self): """Get the list of items for this view. This must be an interable, and may be a queryset (in which qs-specific behavior will be enabled). See original in ``django.views.generic.list.MultipleObjectMixin``. """ if self.queryset is not None: ...
python
def get_queryset(self): """Get the list of items for this view. This must be an interable, and may be a queryset (in which qs-specific behavior will be enabled). See original in ``django.views.generic.list.MultipleObjectMixin``. """ if self.queryset is not None: ...
[ "def", "get_queryset", "(", "self", ")", ":", "if", "self", ".", "queryset", "is", "not", "None", ":", "queryset", "=", "self", ".", "queryset", "if", "hasattr", "(", "queryset", ",", "'_clone'", ")", ":", "queryset", "=", "queryset", ".", "_clone", "(...
Get the list of items for this view. This must be an interable, and may be a queryset (in which qs-specific behavior will be enabled). See original in ``django.views.generic.list.MultipleObjectMixin``.
[ "Get", "the", "list", "of", "items", "for", "this", "view", "." ]
889ba62b46cb58292d554753a0bfda0b0a6d57da
https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/views.py#L22-L39
train
shtalinberg/django-el-pagination
el_pagination/views.py
MultipleObjectMixin.get_context_object_name
def get_context_object_name(self, object_list): """Get the name of the item to be used in the context. See original in ``django.views.generic.list.MultipleObjectMixin``. """ if self.context_object_name: return self.context_object_name elif hasattr(object_list, 'model...
python
def get_context_object_name(self, object_list): """Get the name of the item to be used in the context. See original in ``django.views.generic.list.MultipleObjectMixin``. """ if self.context_object_name: return self.context_object_name elif hasattr(object_list, 'model...
[ "def", "get_context_object_name", "(", "self", ",", "object_list", ")", ":", "if", "self", ".", "context_object_name", ":", "return", "self", ".", "context_object_name", "elif", "hasattr", "(", "object_list", ",", "'model'", ")", ":", "object_name", "=", "object...
Get the name of the item to be used in the context. See original in ``django.views.generic.list.MultipleObjectMixin``.
[ "Get", "the", "name", "of", "the", "item", "to", "be", "used", "in", "the", "context", "." ]
889ba62b46cb58292d554753a0bfda0b0a6d57da
https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/views.py#L50-L61
train
shtalinberg/django-el-pagination
el_pagination/views.py
AjaxMultipleObjectTemplateResponseMixin.get_page_template
def get_page_template(self, **kwargs): """Return the template name used for this request. Only called if *page_template* is not given as a kwarg of *self.as_view*. """ opts = self.object_list.model._meta return '{0}/{1}{2}{3}.html'.format( opts.app_label, ...
python
def get_page_template(self, **kwargs): """Return the template name used for this request. Only called if *page_template* is not given as a kwarg of *self.as_view*. """ opts = self.object_list.model._meta return '{0}/{1}{2}{3}.html'.format( opts.app_label, ...
[ "def", "get_page_template", "(", "self", ",", "*", "*", "kwargs", ")", ":", "opts", "=", "self", ".", "object_list", ".", "model", ".", "_meta", "return", "'{0}/{1}{2}{3}.html'", ".", "format", "(", "opts", ".", "app_label", ",", "opts", ".", "object_name"...
Return the template name used for this request. Only called if *page_template* is not given as a kwarg of *self.as_view*.
[ "Return", "the", "template", "name", "used", "for", "this", "request", "." ]
889ba62b46cb58292d554753a0bfda0b0a6d57da
https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/views.py#L135-L147
train
shtalinberg/django-el-pagination
el_pagination/models.py
ELPage.render_link
def render_link(self): """Render the page as a link.""" extra_context = { 'add_nofollow': settings.ADD_NOFOLLOW, 'page': self, 'querystring_key': self.querystring_key, } if self.is_current: template_name = 'el_pagination/current_link.html' ...
python
def render_link(self): """Render the page as a link.""" extra_context = { 'add_nofollow': settings.ADD_NOFOLLOW, 'page': self, 'querystring_key': self.querystring_key, } if self.is_current: template_name = 'el_pagination/current_link.html' ...
[ "def", "render_link", "(", "self", ")", ":", "extra_context", "=", "{", "'add_nofollow'", ":", "settings", ".", "ADD_NOFOLLOW", ",", "'page'", ":", "self", ",", "'querystring_key'", ":", "self", ".", "querystring_key", ",", "}", "if", "self", ".", "is_curren...
Render the page as a link.
[ "Render", "the", "page", "as", "a", "link", "." ]
889ba62b46cb58292d554753a0bfda0b0a6d57da
https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/models.py#L63-L83
train
shtalinberg/django-el-pagination
el_pagination/models.py
PageList.previous
def previous(self): """Return the previous page. The page label is defined in ``settings.PREVIOUS_LABEL``. Return an empty string if current page is the first. """ if self._page.has_previous(): return self._endless_page( self._page.previous_page_numbe...
python
def previous(self): """Return the previous page. The page label is defined in ``settings.PREVIOUS_LABEL``. Return an empty string if current page is the first. """ if self._page.has_previous(): return self._endless_page( self._page.previous_page_numbe...
[ "def", "previous", "(", "self", ")", ":", "if", "self", ".", "_page", ".", "has_previous", "(", ")", ":", "return", "self", ".", "_endless_page", "(", "self", ".", "_page", ".", "previous_page_number", "(", ")", ",", "label", "=", "settings", ".", "PRE...
Return the previous page. The page label is defined in ``settings.PREVIOUS_LABEL``. Return an empty string if current page is the first.
[ "Return", "the", "previous", "page", "." ]
889ba62b46cb58292d554753a0bfda0b0a6d57da
https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/models.py#L243-L253
train
shtalinberg/django-el-pagination
el_pagination/models.py
PageList.next
def next(self): """Return the next page. The page label is defined in ``settings.NEXT_LABEL``. Return an empty string if current page is the last. """ if self._page.has_next(): return self._endless_page( self._page.next_page_number(), ...
python
def next(self): """Return the next page. The page label is defined in ``settings.NEXT_LABEL``. Return an empty string if current page is the last. """ if self._page.has_next(): return self._endless_page( self._page.next_page_number(), ...
[ "def", "next", "(", "self", ")", ":", "if", "self", ".", "_page", ".", "has_next", "(", ")", ":", "return", "self", ".", "_endless_page", "(", "self", ".", "_page", ".", "next_page_number", "(", ")", ",", "label", "=", "settings", ".", "NEXT_LABEL", ...
Return the next page. The page label is defined in ``settings.NEXT_LABEL``. Return an empty string if current page is the last.
[ "Return", "the", "next", "page", "." ]
889ba62b46cb58292d554753a0bfda0b0a6d57da
https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/models.py#L255-L265
train
shtalinberg/django-el-pagination
el_pagination/paginators.py
CustomPage.start_index
def start_index(self): """Return the 1-based index of the first item on this page.""" paginator = self.paginator # Special case, return zero if no items. if paginator.count == 0: return 0 elif self.number == 1: return 1 return ( (self.n...
python
def start_index(self): """Return the 1-based index of the first item on this page.""" paginator = self.paginator # Special case, return zero if no items. if paginator.count == 0: return 0 elif self.number == 1: return 1 return ( (self.n...
[ "def", "start_index", "(", "self", ")", ":", "paginator", "=", "self", ".", "paginator", "# Special case, return zero if no items.", "if", "paginator", ".", "count", "==", "0", ":", "return", "0", "elif", "self", ".", "number", "==", "1", ":", "return", "1",...
Return the 1-based index of the first item on this page.
[ "Return", "the", "1", "-", "based", "index", "of", "the", "first", "item", "on", "this", "page", "." ]
889ba62b46cb58292d554753a0bfda0b0a6d57da
https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/paginators.py#L17-L26
train
shtalinberg/django-el-pagination
el_pagination/paginators.py
CustomPage.end_index
def end_index(self): """Return the 1-based index of the last item on this page.""" paginator = self.paginator # Special case for the last page because there can be orphans. if self.number == paginator.num_pages: return paginator.count return (self.number - 1) * pagina...
python
def end_index(self): """Return the 1-based index of the last item on this page.""" paginator = self.paginator # Special case for the last page because there can be orphans. if self.number == paginator.num_pages: return paginator.count return (self.number - 1) * pagina...
[ "def", "end_index", "(", "self", ")", ":", "paginator", "=", "self", ".", "paginator", "# Special case for the last page because there can be orphans.", "if", "self", ".", "number", "==", "paginator", ".", "num_pages", ":", "return", "paginator", ".", "count", "retu...
Return the 1-based index of the last item on this page.
[ "Return", "the", "1", "-", "based", "index", "of", "the", "last", "item", "on", "this", "page", "." ]
889ba62b46cb58292d554753a0bfda0b0a6d57da
https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/paginators.py#L28-L34
train
shtalinberg/django-el-pagination
el_pagination/utils.py
get_page_numbers
def get_page_numbers( current_page, num_pages, extremes=DEFAULT_CALLABLE_EXTREMES, arounds=DEFAULT_CALLABLE_AROUNDS, arrows=DEFAULT_CALLABLE_ARROWS): """Default callable for page listing. Produce a Digg-style pagination. """ page_range = range(1, num_pages + 1) pages...
python
def get_page_numbers( current_page, num_pages, extremes=DEFAULT_CALLABLE_EXTREMES, arounds=DEFAULT_CALLABLE_AROUNDS, arrows=DEFAULT_CALLABLE_ARROWS): """Default callable for page listing. Produce a Digg-style pagination. """ page_range = range(1, num_pages + 1) pages...
[ "def", "get_page_numbers", "(", "current_page", ",", "num_pages", ",", "extremes", "=", "DEFAULT_CALLABLE_EXTREMES", ",", "arounds", "=", "DEFAULT_CALLABLE_AROUNDS", ",", "arrows", "=", "DEFAULT_CALLABLE_ARROWS", ")", ":", "page_range", "=", "range", "(", "1", ",", ...
Default callable for page listing. Produce a Digg-style pagination.
[ "Default", "callable", "for", "page", "listing", "." ]
889ba62b46cb58292d554753a0bfda0b0a6d57da
https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/utils.py#L50-L104
train
shtalinberg/django-el-pagination
el_pagination/utils.py
_make_elastic_range
def _make_elastic_range(begin, end): """Generate an S-curved range of pages. Start from both left and right, adding exponentially growing indexes, until the two trends collide. """ # Limit growth for huge numbers of pages. starting_factor = max(1, (end - begin) // 100) factor = _iter_factor...
python
def _make_elastic_range(begin, end): """Generate an S-curved range of pages. Start from both left and right, adding exponentially growing indexes, until the two trends collide. """ # Limit growth for huge numbers of pages. starting_factor = max(1, (end - begin) // 100) factor = _iter_factor...
[ "def", "_make_elastic_range", "(", "begin", ",", "end", ")", ":", "# Limit growth for huge numbers of pages.", "starting_factor", "=", "max", "(", "1", ",", "(", "end", "-", "begin", ")", "//", "100", ")", "factor", "=", "_iter_factors", "(", "starting_factor", ...
Generate an S-curved range of pages. Start from both left and right, adding exponentially growing indexes, until the two trends collide.
[ "Generate", "an", "S", "-", "curved", "range", "of", "pages", "." ]
889ba62b46cb58292d554753a0bfda0b0a6d57da
https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/utils.py#L118-L140
train
shtalinberg/django-el-pagination
el_pagination/utils.py
get_elastic_page_numbers
def get_elastic_page_numbers(current_page, num_pages): """Alternative callable for page listing. Produce an adaptive pagination, useful for big numbers of pages, by splitting the num_pages ranges in two parts at current_page. Each part will have its own S-curve. """ if num_pages <= 10: ...
python
def get_elastic_page_numbers(current_page, num_pages): """Alternative callable for page listing. Produce an adaptive pagination, useful for big numbers of pages, by splitting the num_pages ranges in two parts at current_page. Each part will have its own S-curve. """ if num_pages <= 10: ...
[ "def", "get_elastic_page_numbers", "(", "current_page", ",", "num_pages", ")", ":", "if", "num_pages", "<=", "10", ":", "return", "list", "(", "range", "(", "1", ",", "num_pages", "+", "1", ")", ")", "if", "current_page", "==", "1", ":", "pages", "=", ...
Alternative callable for page listing. Produce an adaptive pagination, useful for big numbers of pages, by splitting the num_pages ranges in two parts at current_page. Each part will have its own S-curve.
[ "Alternative", "callable", "for", "page", "listing", "." ]
889ba62b46cb58292d554753a0bfda0b0a6d57da
https://github.com/shtalinberg/django-el-pagination/blob/889ba62b46cb58292d554753a0bfda0b0a6d57da/el_pagination/utils.py#L143-L160
train
justinmayer/django-autoslug
autoslug/utils.py
get_prepopulated_value
def get_prepopulated_value(field, instance): """ Returns preliminary value based on `populate_from`. """ if hasattr(field.populate_from, '__call__'): # AutoSlugField(populate_from=lambda instance: ...) return field.populate_from(instance) else: # AutoSlugField(populate_from='...
python
def get_prepopulated_value(field, instance): """ Returns preliminary value based on `populate_from`. """ if hasattr(field.populate_from, '__call__'): # AutoSlugField(populate_from=lambda instance: ...) return field.populate_from(instance) else: # AutoSlugField(populate_from='...
[ "def", "get_prepopulated_value", "(", "field", ",", "instance", ")", ":", "if", "hasattr", "(", "field", ".", "populate_from", ",", "'__call__'", ")", ":", "# AutoSlugField(populate_from=lambda instance: ...)", "return", "field", ".", "populate_from", "(", "instance",...
Returns preliminary value based on `populate_from`.
[ "Returns", "preliminary", "value", "based", "on", "populate_from", "." ]
b3991daddf5a476a829b48c28afad4ae08a18179
https://github.com/justinmayer/django-autoslug/blob/b3991daddf5a476a829b48c28afad4ae08a18179/autoslug/utils.py#L35-L45
train
justinmayer/django-autoslug
autoslug/utils.py
get_uniqueness_lookups
def get_uniqueness_lookups(field, instance, unique_with): """ Returns a dict'able tuple of lookups to ensure uniqueness of a slug. """ for original_lookup_name in unique_with: if '__' in original_lookup_name: field_name, inner_lookup = original_lookup_name.split('__', 1) else...
python
def get_uniqueness_lookups(field, instance, unique_with): """ Returns a dict'able tuple of lookups to ensure uniqueness of a slug. """ for original_lookup_name in unique_with: if '__' in original_lookup_name: field_name, inner_lookup = original_lookup_name.split('__', 1) else...
[ "def", "get_uniqueness_lookups", "(", "field", ",", "instance", ",", "unique_with", ")", ":", "for", "original_lookup_name", "in", "unique_with", ":", "if", "'__'", "in", "original_lookup_name", ":", "field_name", ",", "inner_lookup", "=", "original_lookup_name", "....
Returns a dict'able tuple of lookups to ensure uniqueness of a slug.
[ "Returns", "a", "dict", "able", "tuple", "of", "lookups", "to", "ensure", "uniqueness", "of", "a", "slug", "." ]
b3991daddf5a476a829b48c28afad4ae08a18179
https://github.com/justinmayer/django-autoslug/blob/b3991daddf5a476a829b48c28afad4ae08a18179/autoslug/utils.py#L94-L162
train
erikrose/blessings
blessings/__init__.py
derivative_colors
def derivative_colors(colors): """Return the names of valid color variants, given the base colors.""" return set([('on_' + c) for c in colors] + [('bright_' + c) for c in colors] + [('on_bright_' + c) for c in colors])
python
def derivative_colors(colors): """Return the names of valid color variants, given the base colors.""" return set([('on_' + c) for c in colors] + [('bright_' + c) for c in colors] + [('on_bright_' + c) for c in colors])
[ "def", "derivative_colors", "(", "colors", ")", ":", "return", "set", "(", "[", "(", "'on_'", "+", "c", ")", "for", "c", "in", "colors", "]", "+", "[", "(", "'bright_'", "+", "c", ")", "for", "c", "in", "colors", "]", "+", "[", "(", "'on_bright_'...
Return the names of valid color variants, given the base colors.
[ "Return", "the", "names", "of", "valid", "color", "variants", "given", "the", "base", "colors", "." ]
b1d4daf948d1db8455af64836906785204d09055
https://github.com/erikrose/blessings/blob/b1d4daf948d1db8455af64836906785204d09055/blessings/__init__.py#L414-L418
train
erikrose/blessings
blessings/__init__.py
split_into_formatters
def split_into_formatters(compound): """Split a possibly compound format string into segments. >>> split_into_formatters('bold_underline_bright_blue_on_red') ['bold', 'underline', 'bright_blue', 'on_red'] >>> split_into_formatters('red_no_italic_shadow_on_bright_cyan') ['red', 'no_italic', 'shadow'...
python
def split_into_formatters(compound): """Split a possibly compound format string into segments. >>> split_into_formatters('bold_underline_bright_blue_on_red') ['bold', 'underline', 'bright_blue', 'on_red'] >>> split_into_formatters('red_no_italic_shadow_on_bright_cyan') ['red', 'no_italic', 'shadow'...
[ "def", "split_into_formatters", "(", "compound", ")", ":", "merged_segs", "=", "[", "]", "# These occur only as prefixes, so they can always be merged:", "mergeable_prefixes", "=", "[", "'no'", ",", "'on'", ",", "'bright'", ",", "'on_bright'", "]", "for", "s", "in", ...
Split a possibly compound format string into segments. >>> split_into_formatters('bold_underline_bright_blue_on_red') ['bold', 'underline', 'bright_blue', 'on_red'] >>> split_into_formatters('red_no_italic_shadow_on_bright_cyan') ['red', 'no_italic', 'shadow', 'on_bright_cyan']
[ "Split", "a", "possibly", "compound", "format", "string", "into", "segments", "." ]
b1d4daf948d1db8455af64836906785204d09055
https://github.com/erikrose/blessings/blob/b1d4daf948d1db8455af64836906785204d09055/blessings/__init__.py#L548-L564
train
erikrose/blessings
blessings/__init__.py
Terminal.location
def location(self, x=None, y=None): """Return a context manager for temporarily moving the cursor. Move the cursor to a certain position on entry, let you print stuff there, then return the cursor to its original position:: term = Terminal() with term.location(2, 5): ...
python
def location(self, x=None, y=None): """Return a context manager for temporarily moving the cursor. Move the cursor to a certain position on entry, let you print stuff there, then return the cursor to its original position:: term = Terminal() with term.location(2, 5): ...
[ "def", "location", "(", "self", ",", "x", "=", "None", ",", "y", "=", "None", ")", ":", "# Save position and move to the requested column, row, or both:", "self", ".", "stream", ".", "write", "(", "self", ".", "save", ")", "if", "x", "is", "not", "None", "...
Return a context manager for temporarily moving the cursor. Move the cursor to a certain position on entry, let you print stuff there, then return the cursor to its original position:: term = Terminal() with term.location(2, 5): print('Hello, world!') ...
[ "Return", "a", "context", "manager", "for", "temporarily", "moving", "the", "cursor", "." ]
b1d4daf948d1db8455af64836906785204d09055
https://github.com/erikrose/blessings/blob/b1d4daf948d1db8455af64836906785204d09055/blessings/__init__.py#L242-L273
train
erikrose/blessings
blessings/__init__.py
Terminal.fullscreen
def fullscreen(self): """Return a context manager that enters fullscreen mode while inside it and restores normal mode on leaving.""" self.stream.write(self.enter_fullscreen) try: yield finally: self.stream.write(self.exit_fullscreen)
python
def fullscreen(self): """Return a context manager that enters fullscreen mode while inside it and restores normal mode on leaving.""" self.stream.write(self.enter_fullscreen) try: yield finally: self.stream.write(self.exit_fullscreen)
[ "def", "fullscreen", "(", "self", ")", ":", "self", ".", "stream", ".", "write", "(", "self", ".", "enter_fullscreen", ")", "try", ":", "yield", "finally", ":", "self", ".", "stream", ".", "write", "(", "self", ".", "exit_fullscreen", ")" ]
Return a context manager that enters fullscreen mode while inside it and restores normal mode on leaving.
[ "Return", "a", "context", "manager", "that", "enters", "fullscreen", "mode", "while", "inside", "it", "and", "restores", "normal", "mode", "on", "leaving", "." ]
b1d4daf948d1db8455af64836906785204d09055
https://github.com/erikrose/blessings/blob/b1d4daf948d1db8455af64836906785204d09055/blessings/__init__.py#L276-L283
train
erikrose/blessings
blessings/__init__.py
Terminal.hidden_cursor
def hidden_cursor(self): """Return a context manager that hides the cursor while inside it and makes it visible on leaving.""" self.stream.write(self.hide_cursor) try: yield finally: self.stream.write(self.normal_cursor)
python
def hidden_cursor(self): """Return a context manager that hides the cursor while inside it and makes it visible on leaving.""" self.stream.write(self.hide_cursor) try: yield finally: self.stream.write(self.normal_cursor)
[ "def", "hidden_cursor", "(", "self", ")", ":", "self", ".", "stream", ".", "write", "(", "self", ".", "hide_cursor", ")", "try", ":", "yield", "finally", ":", "self", ".", "stream", ".", "write", "(", "self", ".", "normal_cursor", ")" ]
Return a context manager that hides the cursor while inside it and makes it visible on leaving.
[ "Return", "a", "context", "manager", "that", "hides", "the", "cursor", "while", "inside", "it", "and", "makes", "it", "visible", "on", "leaving", "." ]
b1d4daf948d1db8455af64836906785204d09055
https://github.com/erikrose/blessings/blob/b1d4daf948d1db8455af64836906785204d09055/blessings/__init__.py#L286-L293
train
erikrose/blessings
blessings/__init__.py
Terminal._resolve_formatter
def _resolve_formatter(self, attr): """Resolve a sugary or plain capability name, color, or compound formatting function name into a callable capability. Return a ``ParametrizingString`` or a ``FormattingString``. """ if attr in COLORS: return self._resolve_color(at...
python
def _resolve_formatter(self, attr): """Resolve a sugary or plain capability name, color, or compound formatting function name into a callable capability. Return a ``ParametrizingString`` or a ``FormattingString``. """ if attr in COLORS: return self._resolve_color(at...
[ "def", "_resolve_formatter", "(", "self", ",", "attr", ")", ":", "if", "attr", "in", "COLORS", ":", "return", "self", ".", "_resolve_color", "(", "attr", ")", "elif", "attr", "in", "COMPOUNDABLES", ":", "# Bold, underline, or something that takes no parameters", "...
Resolve a sugary or plain capability name, color, or compound formatting function name into a callable capability. Return a ``ParametrizingString`` or a ``FormattingString``.
[ "Resolve", "a", "sugary", "or", "plain", "capability", "name", "color", "or", "compound", "formatting", "function", "name", "into", "a", "callable", "capability", "." ]
b1d4daf948d1db8455af64836906785204d09055
https://github.com/erikrose/blessings/blob/b1d4daf948d1db8455af64836906785204d09055/blessings/__init__.py#L347-L368
train
erikrose/blessings
blessings/__init__.py
Terminal._resolve_capability
def _resolve_capability(self, atom): """Return a terminal code for a capname or a sugary name, or an empty Unicode. The return value is always Unicode, because otherwise it is clumsy (especially in Python 3) to concatenate with real (Unicode) strings. """ code = tigetst...
python
def _resolve_capability(self, atom): """Return a terminal code for a capname or a sugary name, or an empty Unicode. The return value is always Unicode, because otherwise it is clumsy (especially in Python 3) to concatenate with real (Unicode) strings. """ code = tigetst...
[ "def", "_resolve_capability", "(", "self", ",", "atom", ")", ":", "code", "=", "tigetstr", "(", "self", ".", "_sugar", ".", "get", "(", "atom", ",", "atom", ")", ")", "if", "code", ":", "# See the comment in ParametrizingString for why this is latin1.", "return"...
Return a terminal code for a capname or a sugary name, or an empty Unicode. The return value is always Unicode, because otherwise it is clumsy (especially in Python 3) to concatenate with real (Unicode) strings.
[ "Return", "a", "terminal", "code", "for", "a", "capname", "or", "a", "sugary", "name", "or", "an", "empty", "Unicode", "." ]
b1d4daf948d1db8455af64836906785204d09055
https://github.com/erikrose/blessings/blob/b1d4daf948d1db8455af64836906785204d09055/blessings/__init__.py#L370-L382
train
erikrose/blessings
blessings/__init__.py
Terminal._resolve_color
def _resolve_color(self, color): """Resolve a color like red or on_bright_green into a callable capability.""" # TODO: Does curses automatically exchange red and blue and cyan and # yellow when a terminal supports setf/setb rather than setaf/setab? # I'll be blasted if I can find...
python
def _resolve_color(self, color): """Resolve a color like red or on_bright_green into a callable capability.""" # TODO: Does curses automatically exchange red and blue and cyan and # yellow when a terminal supports setf/setb rather than setaf/setab? # I'll be blasted if I can find...
[ "def", "_resolve_color", "(", "self", ",", "color", ")", ":", "# TODO: Does curses automatically exchange red and blue and cyan and", "# yellow when a terminal supports setf/setb rather than setaf/setab?", "# I'll be blasted if I can find any documentation. The following", "# assumes it does."...
Resolve a color like red or on_bright_green into a callable capability.
[ "Resolve", "a", "color", "like", "red", "or", "on_bright_green", "into", "a", "callable", "capability", "." ]
b1d4daf948d1db8455af64836906785204d09055
https://github.com/erikrose/blessings/blob/b1d4daf948d1db8455af64836906785204d09055/blessings/__init__.py#L384-L398
train
relekang/django-nopassword
nopassword/backends/sms.py
TwilioBackend.send_login_code
def send_login_code(self, code, context, **kwargs): """ Send a login code via SMS """ from_number = self.from_number or getattr(settings, 'DEFAULT_FROM_NUMBER') sms_content = render_to_string(self.template_name, context) self.twilio_client.messages.create( to...
python
def send_login_code(self, code, context, **kwargs): """ Send a login code via SMS """ from_number = self.from_number or getattr(settings, 'DEFAULT_FROM_NUMBER') sms_content = render_to_string(self.template_name, context) self.twilio_client.messages.create( to...
[ "def", "send_login_code", "(", "self", ",", "code", ",", "context", ",", "*", "*", "kwargs", ")", ":", "from_number", "=", "self", ".", "from_number", "or", "getattr", "(", "settings", ",", "'DEFAULT_FROM_NUMBER'", ")", "sms_content", "=", "render_to_string", ...
Send a login code via SMS
[ "Send", "a", "login", "code", "via", "SMS" ]
d1d0f99617b1394c860864852326be673f9b935f
https://github.com/relekang/django-nopassword/blob/d1d0f99617b1394c860864852326be673f9b935f/nopassword/backends/sms.py#L20-L31
train
bshillingford/python-torchfile
torchfile.py
load
def load(filename, **kwargs): """ Loads the given t7 file using default settings; kwargs are forwarded to `T7Reader`. """ with open(filename, 'rb') as f: reader = T7Reader(f, **kwargs) return reader.read_obj()
python
def load(filename, **kwargs): """ Loads the given t7 file using default settings; kwargs are forwarded to `T7Reader`. """ with open(filename, 'rb') as f: reader = T7Reader(f, **kwargs) return reader.read_obj()
[ "def", "load", "(", "filename", ",", "*", "*", "kwargs", ")", ":", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "f", ":", "reader", "=", "T7Reader", "(", "f", ",", "*", "*", "kwargs", ")", "return", "reader", ".", "read_obj", "(", ")"...
Loads the given t7 file using default settings; kwargs are forwarded to `T7Reader`.
[ "Loads", "the", "given", "t7", "file", "using", "default", "settings", ";", "kwargs", "are", "forwarded", "to", "T7Reader", "." ]
20b3e13b6267c254e9df67446844010629f48d61
https://github.com/bshillingford/python-torchfile/blob/20b3e13b6267c254e9df67446844010629f48d61/torchfile.py#L417-L424
train
slackapi/python-rtmbot
rtmbot/core.py
Job.check
def check(self): ''' Returns True if `interval` seconds have passed since it last ran ''' if self.lastrun + self.interval < time.time(): return True else: return False
python
def check(self): ''' Returns True if `interval` seconds have passed since it last ran ''' if self.lastrun + self.interval < time.time(): return True else: return False
[ "def", "check", "(", "self", ")", ":", "if", "self", ".", "lastrun", "+", "self", ".", "interval", "<", "time", ".", "time", "(", ")", ":", "return", "True", "else", ":", "return", "False" ]
Returns True if `interval` seconds have passed since it last ran
[ "Returns", "True", "if", "interval", "seconds", "have", "passed", "since", "it", "last", "ran" ]
1adc5df6791a9f6e7070ab1ff0d1c95db7dbb0ab
https://github.com/slackapi/python-rtmbot/blob/1adc5df6791a9f6e7070ab1ff0d1c95db7dbb0ab/rtmbot/core.py#L293-L298
train
anttttti/Wordbatch
wordbatch/feature_union.py
make_union
def make_union(*transformers, **kwargs): """Construct a FeatureUnion from the given transformers. This is a shorthand for the FeatureUnion constructor; it does not require, and does not permit, naming the transformers. Instead, they will be given names automatically based on their types. It also does n...
python
def make_union(*transformers, **kwargs): """Construct a FeatureUnion from the given transformers. This is a shorthand for the FeatureUnion constructor; it does not require, and does not permit, naming the transformers. Instead, they will be given names automatically based on their types. It also does n...
[ "def", "make_union", "(", "*", "transformers", ",", "*", "*", "kwargs", ")", ":", "n_jobs", "=", "kwargs", ".", "pop", "(", "'n_jobs'", ",", "1", ")", "concatenate", "=", "kwargs", ".", "pop", "(", "'concatenate'", ",", "True", ")", "if", "kwargs", "...
Construct a FeatureUnion from the given transformers. This is a shorthand for the FeatureUnion constructor; it does not require, and does not permit, naming the transformers. Instead, they will be given names automatically based on their types. It also does not allow weighting. Parameters --------...
[ "Construct", "a", "FeatureUnion", "from", "the", "given", "transformers", "." ]
ef57b5c1d87d9c82fb096598125c2511f9819e4d
https://github.com/anttttti/Wordbatch/blob/ef57b5c1d87d9c82fb096598125c2511f9819e4d/wordbatch/feature_union.py#L208-L249
train
anttttti/Wordbatch
wordbatch/feature_union.py
FeatureUnion.get_feature_names
def get_feature_names(self): """Get feature names from all transformers. Returns ------- feature_names : list of strings Names of the features produced by transform. """ feature_names = [] for name, trans, weight in self._iter(): if not ha...
python
def get_feature_names(self): """Get feature names from all transformers. Returns ------- feature_names : list of strings Names of the features produced by transform. """ feature_names = [] for name, trans, weight in self._iter(): if not ha...
[ "def", "get_feature_names", "(", "self", ")", ":", "feature_names", "=", "[", "]", "for", "name", ",", "trans", ",", "weight", "in", "self", ".", "_iter", "(", ")", ":", "if", "not", "hasattr", "(", "trans", ",", "'get_feature_names'", ")", ":", "raise...
Get feature names from all transformers. Returns ------- feature_names : list of strings Names of the features produced by transform.
[ "Get", "feature", "names", "from", "all", "transformers", "." ]
ef57b5c1d87d9c82fb096598125c2511f9819e4d
https://github.com/anttttti/Wordbatch/blob/ef57b5c1d87d9c82fb096598125c2511f9819e4d/wordbatch/feature_union.py#L97-L113
train
anttttti/Wordbatch
wordbatch/feature_union.py
FeatureUnion.fit
def fit(self, X, y=None): """Fit all transformers using X. Parameters ---------- X : iterable or array-like, depending on transformers Input data, used to fit transformers. y : array-like, shape (n_samples, ...), optional Targets for supervised learning....
python
def fit(self, X, y=None): """Fit all transformers using X. Parameters ---------- X : iterable or array-like, depending on transformers Input data, used to fit transformers. y : array-like, shape (n_samples, ...), optional Targets for supervised learning....
[ "def", "fit", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "self", ".", "transformer_list", "=", "list", "(", "self", ".", "transformer_list", ")", "self", ".", "_validate_transformers", "(", ")", "with", "Pool", "(", "self", ".", "n_jobs", ...
Fit all transformers using X. Parameters ---------- X : iterable or array-like, depending on transformers Input data, used to fit transformers. y : array-like, shape (n_samples, ...), optional Targets for supervised learning. Returns ------- ...
[ "Fit", "all", "transformers", "using", "X", "." ]
ef57b5c1d87d9c82fb096598125c2511f9819e4d
https://github.com/anttttti/Wordbatch/blob/ef57b5c1d87d9c82fb096598125c2511f9819e4d/wordbatch/feature_union.py#L115-L137
train
anttttti/Wordbatch
wordbatch/feature_union.py
FeatureUnion.fit_transform
def fit_transform(self, X, y=None, **fit_params): """Fit all transformers, transform the data and concatenate results. Parameters ---------- X : iterable or array-like, depending on transformers Input data to be transformed. y : array-like, shape (n_samples, ...), o...
python
def fit_transform(self, X, y=None, **fit_params): """Fit all transformers, transform the data and concatenate results. Parameters ---------- X : iterable or array-like, depending on transformers Input data to be transformed. y : array-like, shape (n_samples, ...), o...
[ "def", "fit_transform", "(", "self", ",", "X", ",", "y", "=", "None", ",", "*", "*", "fit_params", ")", ":", "self", ".", "_validate_transformers", "(", ")", "with", "Pool", "(", "self", ".", "n_jobs", ")", "as", "pool", ":", "result", "=", "pool", ...
Fit all transformers, transform the data and concatenate results. Parameters ---------- X : iterable or array-like, depending on transformers Input data to be transformed. y : array-like, shape (n_samples, ...), optional Targets for supervised learning. ...
[ "Fit", "all", "transformers", "transform", "the", "data", "and", "concatenate", "results", "." ]
ef57b5c1d87d9c82fb096598125c2511f9819e4d
https://github.com/anttttti/Wordbatch/blob/ef57b5c1d87d9c82fb096598125c2511f9819e4d/wordbatch/feature_union.py#L139-L171
train
anttttti/Wordbatch
wordbatch/feature_union.py
FeatureUnion.transform
def transform(self, X): """Transform X separately by each transformer, concatenate results. Parameters ---------- X : iterable or array-like, depending on transformers Input data to be transformed. Returns ------- X_t : array-like or sparse matrix, s...
python
def transform(self, X): """Transform X separately by each transformer, concatenate results. Parameters ---------- X : iterable or array-like, depending on transformers Input data to be transformed. Returns ------- X_t : array-like or sparse matrix, s...
[ "def", "transform", "(", "self", ",", "X", ")", ":", "with", "Pool", "(", "self", ".", "n_jobs", ")", "as", "pool", ":", "Xs", "=", "pool", ".", "starmap", "(", "_transform_one", ",", "(", "(", "trans", ",", "weight", ",", "X", "[", "trans", "[",...
Transform X separately by each transformer, concatenate results. Parameters ---------- X : iterable or array-like, depending on transformers Input data to be transformed. Returns ------- X_t : array-like or sparse matrix, shape (n_samples, sum_n_components) ...
[ "Transform", "X", "separately", "by", "each", "transformer", "concatenate", "results", "." ]
ef57b5c1d87d9c82fb096598125c2511f9819e4d
https://github.com/anttttti/Wordbatch/blob/ef57b5c1d87d9c82fb096598125c2511f9819e4d/wordbatch/feature_union.py#L173-L198
train
anttttti/Wordbatch
wordbatch/batcher.py
Batcher.split_batches
def split_batches(self, data, minibatch_size= None): """Split data into minibatches with a specified size Parameters ---------- data: iterable and indexable List-like data to be split into batches. Includes spark_contextipy matrices and Pandas DataFrames. minibatch_size: int Expected sizes of minibatc...
python
def split_batches(self, data, minibatch_size= None): """Split data into minibatches with a specified size Parameters ---------- data: iterable and indexable List-like data to be split into batches. Includes spark_contextipy matrices and Pandas DataFrames. minibatch_size: int Expected sizes of minibatc...
[ "def", "split_batches", "(", "self", ",", "data", ",", "minibatch_size", "=", "None", ")", ":", "if", "minibatch_size", "==", "None", ":", "minibatch_size", "=", "self", ".", "minibatch_size", "if", "isinstance", "(", "data", ",", "list", ")", "or", "isins...
Split data into minibatches with a specified size Parameters ---------- data: iterable and indexable List-like data to be split into batches. Includes spark_contextipy matrices and Pandas DataFrames. minibatch_size: int Expected sizes of minibatches split from the data. Returns ------- data_split...
[ "Split", "data", "into", "minibatches", "with", "a", "specified", "size" ]
ef57b5c1d87d9c82fb096598125c2511f9819e4d
https://github.com/anttttti/Wordbatch/blob/ef57b5c1d87d9c82fb096598125c2511f9819e4d/wordbatch/batcher.py#L77-L102
train
anttttti/Wordbatch
wordbatch/batcher.py
Batcher.merge_batches
def merge_batches(self, data): """Merge a list of data minibatches into one single instance representing the data Parameters ---------- data: list List of minibatches to merge Returns ------- (anonymous): sparse matrix | pd.DataFrame | list Single complete list-like data merged from given batches ...
python
def merge_batches(self, data): """Merge a list of data minibatches into one single instance representing the data Parameters ---------- data: list List of minibatches to merge Returns ------- (anonymous): sparse matrix | pd.DataFrame | list Single complete list-like data merged from given batches ...
[ "def", "merge_batches", "(", "self", ",", "data", ")", ":", "if", "isinstance", "(", "data", "[", "0", "]", ",", "ssp", ".", "csr_matrix", ")", ":", "return", "ssp", ".", "vstack", "(", "data", ")", "if", "isinstance", "(", "data", "[", "0", "]", ...
Merge a list of data minibatches into one single instance representing the data Parameters ---------- data: list List of minibatches to merge Returns ------- (anonymous): sparse matrix | pd.DataFrame | list Single complete list-like data merged from given batches
[ "Merge", "a", "list", "of", "data", "minibatches", "into", "one", "single", "instance", "representing", "the", "data" ]
ef57b5c1d87d9c82fb096598125c2511f9819e4d
https://github.com/anttttti/Wordbatch/blob/ef57b5c1d87d9c82fb096598125c2511f9819e4d/wordbatch/batcher.py#L104-L119
train
anttttti/Wordbatch
wordbatch/batcher.py
Batcher.shuffle_batch
def shuffle_batch(self, texts, labels= None, seed= None): """Shuffle a list of samples, as well as the labels if specified Parameters ---------- texts: list-like List of samples to shuffle labels: list-like (optional) List of labels to shuffle, should be correspondent to the samples given seed: int...
python
def shuffle_batch(self, texts, labels= None, seed= None): """Shuffle a list of samples, as well as the labels if specified Parameters ---------- texts: list-like List of samples to shuffle labels: list-like (optional) List of labels to shuffle, should be correspondent to the samples given seed: int...
[ "def", "shuffle_batch", "(", "self", ",", "texts", ",", "labels", "=", "None", ",", "seed", "=", "None", ")", ":", "if", "seed", "!=", "None", ":", "random", ".", "seed", "(", "seed", ")", "index_shuf", "=", "list", "(", "range", "(", "len", "(", ...
Shuffle a list of samples, as well as the labels if specified Parameters ---------- texts: list-like List of samples to shuffle labels: list-like (optional) List of labels to shuffle, should be correspondent to the samples given seed: int The seed of the pseudo random number generator to use for s...
[ "Shuffle", "a", "list", "of", "samples", "as", "well", "as", "the", "labels", "if", "specified" ]
ef57b5c1d87d9c82fb096598125c2511f9819e4d
https://github.com/anttttti/Wordbatch/blob/ef57b5c1d87d9c82fb096598125c2511f9819e4d/wordbatch/batcher.py#L230-L259
train
t-makaro/animatplot
animatplot/util.py
demeshgrid
def demeshgrid(arr): """Turns an ndarray created by a meshgrid back into a 1D array Parameters ---------- arr : array of dimension > 1 This array should have been created by a meshgrid. """ dim = len(arr.shape) for i in range(dim): Slice1 = [0]*dim Slice2 = [1]*dim ...
python
def demeshgrid(arr): """Turns an ndarray created by a meshgrid back into a 1D array Parameters ---------- arr : array of dimension > 1 This array should have been created by a meshgrid. """ dim = len(arr.shape) for i in range(dim): Slice1 = [0]*dim Slice2 = [1]*dim ...
[ "def", "demeshgrid", "(", "arr", ")", ":", "dim", "=", "len", "(", "arr", ".", "shape", ")", "for", "i", "in", "range", "(", "dim", ")", ":", "Slice1", "=", "[", "0", "]", "*", "dim", "Slice2", "=", "[", "1", "]", "*", "dim", "Slice1", "[", ...
Turns an ndarray created by a meshgrid back into a 1D array Parameters ---------- arr : array of dimension > 1 This array should have been created by a meshgrid.
[ "Turns", "an", "ndarray", "created", "by", "a", "meshgrid", "back", "into", "a", "1D", "array" ]
632d988687fca7e7415e9fa49fe7eebc3f0991c6
https://github.com/t-makaro/animatplot/blob/632d988687fca7e7415e9fa49fe7eebc3f0991c6/animatplot/util.py#L23-L38
train
t-makaro/animatplot
animatplot/animation.py
Animation.timeline_slider
def timeline_slider(self, text='Time', ax=None, valfmt=None, color=None): """Creates a timeline slider. Parameters ---------- text : str, optional The text to display for the slider. Defaults to 'Time' ax : matplotlib.axes.Axes, optional The matplotlib ax...
python
def timeline_slider(self, text='Time', ax=None, valfmt=None, color=None): """Creates a timeline slider. Parameters ---------- text : str, optional The text to display for the slider. Defaults to 'Time' ax : matplotlib.axes.Axes, optional The matplotlib ax...
[ "def", "timeline_slider", "(", "self", ",", "text", "=", "'Time'", ",", "ax", "=", "None", ",", "valfmt", "=", "None", ",", "color", "=", "None", ")", ":", "if", "ax", "is", "None", ":", "adjust_plot", "=", "{", "'bottom'", ":", ".2", "}", "rect", ...
Creates a timeline slider. Parameters ---------- text : str, optional The text to display for the slider. Defaults to 'Time' ax : matplotlib.axes.Axes, optional The matplotlib axes to attach the slider to. valfmt : str, optional a format speci...
[ "Creates", "a", "timeline", "slider", "." ]
632d988687fca7e7415e9fa49fe7eebc3f0991c6
https://github.com/t-makaro/animatplot/blob/632d988687fca7e7415e9fa49fe7eebc3f0991c6/animatplot/animation.py#L100-L150
train
t-makaro/animatplot
animatplot/animation.py
Animation.controls
def controls(self, timeline_slider_args={}, toggle_args={}): """Creates interactive controls for the animation Creates both a play/pause button, and a time slider at once Parameters ---------- timeline_slider_args : Dict, optional A dictionary of arguments to be pas...
python
def controls(self, timeline_slider_args={}, toggle_args={}): """Creates interactive controls for the animation Creates both a play/pause button, and a time slider at once Parameters ---------- timeline_slider_args : Dict, optional A dictionary of arguments to be pas...
[ "def", "controls", "(", "self", ",", "timeline_slider_args", "=", "{", "}", ",", "toggle_args", "=", "{", "}", ")", ":", "self", ".", "timeline_slider", "(", "*", "*", "timeline_slider_args", ")", "self", ".", "toggle", "(", "*", "*", "toggle_args", ")" ...
Creates interactive controls for the animation Creates both a play/pause button, and a time slider at once Parameters ---------- timeline_slider_args : Dict, optional A dictionary of arguments to be passed to timeline_slider() toggle_args : Dict, optional ...
[ "Creates", "interactive", "controls", "for", "the", "animation" ]
632d988687fca7e7415e9fa49fe7eebc3f0991c6
https://github.com/t-makaro/animatplot/blob/632d988687fca7e7415e9fa49fe7eebc3f0991c6/animatplot/animation.py#L152-L165
train
t-makaro/animatplot
animatplot/animation.py
Animation.save_gif
def save_gif(self, filename): """Saves the animation to a gif A convience function. Provided to let the user avoid dealing with writers. Parameters ---------- filename : str the name of the file to be created without the file extension """ se...
python
def save_gif(self, filename): """Saves the animation to a gif A convience function. Provided to let the user avoid dealing with writers. Parameters ---------- filename : str the name of the file to be created without the file extension """ se...
[ "def", "save_gif", "(", "self", ",", "filename", ")", ":", "self", ".", "timeline", ".", "index", "-=", "1", "# required for proper starting point for save", "self", ".", "animation", ".", "save", "(", "filename", "+", "'.gif'", ",", "writer", "=", "PillowWrit...
Saves the animation to a gif A convience function. Provided to let the user avoid dealing with writers. Parameters ---------- filename : str the name of the file to be created without the file extension
[ "Saves", "the", "animation", "to", "a", "gif" ]
632d988687fca7e7415e9fa49fe7eebc3f0991c6
https://github.com/t-makaro/animatplot/blob/632d988687fca7e7415e9fa49fe7eebc3f0991c6/animatplot/animation.py#L167-L179
train
t-makaro/animatplot
animatplot/animation.py
Animation.save
def save(self, *args, **kwargs): """Saves an animation A wrapper around :meth:`matplotlib.animation.Animation.save` """ self.timeline.index -= 1 # required for proper starting point for save self.animation.save(*args, **kwargs)
python
def save(self, *args, **kwargs): """Saves an animation A wrapper around :meth:`matplotlib.animation.Animation.save` """ self.timeline.index -= 1 # required for proper starting point for save self.animation.save(*args, **kwargs)
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "timeline", ".", "index", "-=", "1", "# required for proper starting point for save", "self", ".", "animation", ".", "save", "(", "*", "args", ",", "*", "*", ...
Saves an animation A wrapper around :meth:`matplotlib.animation.Animation.save`
[ "Saves", "an", "animation" ]
632d988687fca7e7415e9fa49fe7eebc3f0991c6
https://github.com/t-makaro/animatplot/blob/632d988687fca7e7415e9fa49fe7eebc3f0991c6/animatplot/animation.py#L181-L187
train
dadadel/pyment
pyment/docstring.py
isin_alone
def isin_alone(elems, line): """Check if an element from a list is the only element of a string. :type elems: list :type line: str """ found = False for e in elems: if line.strip().lower() == e.lower(): found = True break return found
python
def isin_alone(elems, line): """Check if an element from a list is the only element of a string. :type elems: list :type line: str """ found = False for e in elems: if line.strip().lower() == e.lower(): found = True break return found
[ "def", "isin_alone", "(", "elems", ",", "line", ")", ":", "found", "=", "False", "for", "e", "in", "elems", ":", "if", "line", ".", "strip", "(", ")", ".", "lower", "(", ")", "==", "e", ".", "lower", "(", ")", ":", "found", "=", "True", "break"...
Check if an element from a list is the only element of a string. :type elems: list :type line: str
[ "Check", "if", "an", "element", "from", "a", "list", "is", "the", "only", "element", "of", "a", "string", "." ]
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L26-L38
train
dadadel/pyment
pyment/docstring.py
isin_start
def isin_start(elems, line): """Check if an element from a list starts a string. :type elems: list :type line: str """ found = False elems = [elems] if type(elems) is not list else elems for e in elems: if line.lstrip().lower().startswith(e): found = True br...
python
def isin_start(elems, line): """Check if an element from a list starts a string. :type elems: list :type line: str """ found = False elems = [elems] if type(elems) is not list else elems for e in elems: if line.lstrip().lower().startswith(e): found = True br...
[ "def", "isin_start", "(", "elems", ",", "line", ")", ":", "found", "=", "False", "elems", "=", "[", "elems", "]", "if", "type", "(", "elems", ")", "is", "not", "list", "else", "elems", "for", "e", "in", "elems", ":", "if", "line", ".", "lstrip", ...
Check if an element from a list starts a string. :type elems: list :type line: str
[ "Check", "if", "an", "element", "from", "a", "list", "starts", "a", "string", "." ]
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L41-L54
train
dadadel/pyment
pyment/docstring.py
isin
def isin(elems, line): """Check if an element from a list is in a string. :type elems: list :type line: str """ found = False for e in elems: if e in line.lower(): found = True break return found
python
def isin(elems, line): """Check if an element from a list is in a string. :type elems: list :type line: str """ found = False for e in elems: if e in line.lower(): found = True break return found
[ "def", "isin", "(", "elems", ",", "line", ")", ":", "found", "=", "False", "for", "e", "in", "elems", ":", "if", "e", "in", "line", ".", "lower", "(", ")", ":", "found", "=", "True", "break", "return", "found" ]
Check if an element from a list is in a string. :type elems: list :type line: str
[ "Check", "if", "an", "element", "from", "a", "list", "is", "in", "a", "string", "." ]
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L57-L69
train
dadadel/pyment
pyment/docstring.py
get_leading_spaces
def get_leading_spaces(data): """Get the leading space of a string if it is not empty :type data: str """ spaces = '' m = re.match(r'^(\s*)', data) if m: spaces = m.group(1) return spaces
python
def get_leading_spaces(data): """Get the leading space of a string if it is not empty :type data: str """ spaces = '' m = re.match(r'^(\s*)', data) if m: spaces = m.group(1) return spaces
[ "def", "get_leading_spaces", "(", "data", ")", ":", "spaces", "=", "''", "m", "=", "re", ".", "match", "(", "r'^(\\s*)'", ",", "data", ")", "if", "m", ":", "spaces", "=", "m", ".", "group", "(", "1", ")", "return", "spaces" ]
Get the leading space of a string if it is not empty :type data: str
[ "Get", "the", "leading", "space", "of", "a", "string", "if", "it", "is", "not", "empty" ]
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L72-L82
train
dadadel/pyment
pyment/docstring.py
DocToolsBase.get_mandatory_sections
def get_mandatory_sections(self): """Get mandatory sections""" return [s for s in self.opt if s not in self.optional_sections and s not in self.excluded_sections]
python
def get_mandatory_sections(self): """Get mandatory sections""" return [s for s in self.opt if s not in self.optional_sections and s not in self.excluded_sections]
[ "def", "get_mandatory_sections", "(", "self", ")", ":", "return", "[", "s", "for", "s", "in", "self", ".", "opt", "if", "s", "not", "in", "self", ".", "optional_sections", "and", "s", "not", "in", "self", ".", "excluded_sections", "]" ]
Get mandatory sections
[ "Get", "mandatory", "sections" ]
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L133-L137
train
dadadel/pyment
pyment/docstring.py
NumpydocTools.get_raw_not_managed
def get_raw_not_managed(self, data): """Get elements not managed. They can be used as is. :param data: the data to proceed """ keys = ['also', 'ref', 'note', 'other', 'example', 'method', 'attr'] elems = [self.opt[k] for k in self.opt if k in keys] data = data.splitline...
python
def get_raw_not_managed(self, data): """Get elements not managed. They can be used as is. :param data: the data to proceed """ keys = ['also', 'ref', 'note', 'other', 'example', 'method', 'attr'] elems = [self.opt[k] for k in self.opt if k in keys] data = data.splitline...
[ "def", "get_raw_not_managed", "(", "self", ",", "data", ")", ":", "keys", "=", "[", "'also'", ",", "'ref'", ",", "'note'", ",", "'other'", ",", "'example'", ",", "'method'", ",", "'attr'", "]", "elems", "=", "[", "self", ".", "opt", "[", "k", "]", ...
Get elements not managed. They can be used as is. :param data: the data to proceed
[ "Get", "elements", "not", "managed", ".", "They", "can", "be", "used", "as", "is", "." ]
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L411-L437
train
dadadel/pyment
pyment/docstring.py
NumpydocTools.get_key_section_header
def get_key_section_header(self, key, spaces): """Get the key of the header section :param key: the key name :param spaces: spaces to set at the beginning of the header """ header = super(NumpydocTools, self).get_key_section_header(key, spaces) header = spaces + header ...
python
def get_key_section_header(self, key, spaces): """Get the key of the header section :param key: the key name :param spaces: spaces to set at the beginning of the header """ header = super(NumpydocTools, self).get_key_section_header(key, spaces) header = spaces + header ...
[ "def", "get_key_section_header", "(", "self", ",", "key", ",", "spaces", ")", ":", "header", "=", "super", "(", "NumpydocTools", ",", "self", ")", ".", "get_key_section_header", "(", "key", ",", "spaces", ")", "header", "=", "spaces", "+", "header", "+", ...
Get the key of the header section :param key: the key name :param spaces: spaces to set at the beginning of the header
[ "Get", "the", "key", "of", "the", "header", "section" ]
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L439-L448
train
dadadel/pyment
pyment/docstring.py
DocsTools.autodetect_style
def autodetect_style(self, data): """Determine the style of a docstring, and sets it as the default input one for the instance. :param data: the docstring's data to recognize. :type data: str :returns: the style detected else 'unknown' :rtype: str """ # ...
python
def autodetect_style(self, data): """Determine the style of a docstring, and sets it as the default input one for the instance. :param data: the docstring's data to recognize. :type data: str :returns: the style detected else 'unknown' :rtype: str """ # ...
[ "def", "autodetect_style", "(", "self", ",", "data", ")", ":", "# evaluate styles with keys", "found_keys", "=", "defaultdict", "(", "int", ")", "for", "style", "in", "self", ".", "tagstyles", ":", "for", "key", "in", "self", ".", "opt", ":", "found_keys", ...
Determine the style of a docstring, and sets it as the default input one for the instance. :param data: the docstring's data to recognize. :type data: str :returns: the style detected else 'unknown' :rtype: str
[ "Determine", "the", "style", "of", "a", "docstring", "and", "sets", "it", "as", "the", "default", "input", "one", "for", "the", "instance", "." ]
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L647-L693
train
dadadel/pyment
pyment/docstring.py
DocsTools._get_options
def _get_options(self, style): """Get the list of keywords for a particular style :param style: the style that the keywords are wanted """ return [self.opt[o][style]['name'] for o in self.opt]
python
def _get_options(self, style): """Get the list of keywords for a particular style :param style: the style that the keywords are wanted """ return [self.opt[o][style]['name'] for o in self.opt]
[ "def", "_get_options", "(", "self", ",", "style", ")", ":", "return", "[", "self", ".", "opt", "[", "o", "]", "[", "style", "]", "[", "'name'", "]", "for", "o", "in", "self", ".", "opt", "]" ]
Get the list of keywords for a particular style :param style: the style that the keywords are wanted
[ "Get", "the", "list", "of", "keywords", "for", "a", "particular", "style" ]
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L713-L719
train
dadadel/pyment
pyment/docstring.py
DocsTools.get_group_key_line
def get_group_key_line(self, data, key): """Get the next group-style key's line number. :param data: string to parse :param key: the key category :returns: the found line number else -1 """ idx = -1 for i, line in enumerate(data.splitlines()): if isi...
python
def get_group_key_line(self, data, key): """Get the next group-style key's line number. :param data: string to parse :param key: the key category :returns: the found line number else -1 """ idx = -1 for i, line in enumerate(data.splitlines()): if isi...
[ "def", "get_group_key_line", "(", "self", ",", "data", ",", "key", ")", ":", "idx", "=", "-", "1", "for", "i", ",", "line", "in", "enumerate", "(", "data", ".", "splitlines", "(", ")", ")", ":", "if", "isin_start", "(", "self", ".", "groups", "[", ...
Get the next group-style key's line number. :param data: string to parse :param key: the key category :returns: the found line number else -1
[ "Get", "the", "next", "group", "-", "style", "key", "s", "line", "number", "." ]
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L776-L788
train
dadadel/pyment
pyment/docstring.py
DocsTools.get_group_key_index
def get_group_key_index(self, data, key): """Get the next groups style's starting line index for a key :param data: string to parse :param key: the key category :returns: the index if found else -1 """ idx = -1 li = self.get_group_key_line(data, key) if ...
python
def get_group_key_index(self, data, key): """Get the next groups style's starting line index for a key :param data: string to parse :param key: the key category :returns: the index if found else -1 """ idx = -1 li = self.get_group_key_line(data, key) if ...
[ "def", "get_group_key_index", "(", "self", ",", "data", ",", "key", ")", ":", "idx", "=", "-", "1", "li", "=", "self", ".", "get_group_key_line", "(", "data", ",", "key", ")", "if", "li", "!=", "-", "1", ":", "idx", "=", "0", "for", "line", "in",...
Get the next groups style's starting line index for a key :param data: string to parse :param key: the key category :returns: the index if found else -1
[ "Get", "the", "next", "groups", "style", "s", "starting", "line", "index", "for", "a", "key" ]
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L794-L808
train
dadadel/pyment
pyment/docstring.py
DocsTools.get_group_line
def get_group_line(self, data): """Get the next group-style key's line. :param data: the data to proceed :returns: the line number """ idx = -1 for key in self.groups: i = self.get_group_key_line(data, key) if (i < idx and i != -1) or idx == -1: ...
python
def get_group_line(self, data): """Get the next group-style key's line. :param data: the data to proceed :returns: the line number """ idx = -1 for key in self.groups: i = self.get_group_key_line(data, key) if (i < idx and i != -1) or idx == -1: ...
[ "def", "get_group_line", "(", "self", ",", "data", ")", ":", "idx", "=", "-", "1", "for", "key", "in", "self", ".", "groups", ":", "i", "=", "self", ".", "get_group_key_line", "(", "data", ",", "key", ")", "if", "(", "i", "<", "idx", "and", "i", ...
Get the next group-style key's line. :param data: the data to proceed :returns: the line number
[ "Get", "the", "next", "group", "-", "style", "key", "s", "line", "." ]
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L810-L822
train
dadadel/pyment
pyment/docstring.py
DocsTools.get_group_index
def get_group_index(self, data): """Get the next groups style's starting line index :param data: string to parse :returns: the index if found else -1 """ idx = -1 li = self.get_group_line(data) if li != -1: idx = 0 for line in data.splitl...
python
def get_group_index(self, data): """Get the next groups style's starting line index :param data: string to parse :returns: the index if found else -1 """ idx = -1 li = self.get_group_line(data) if li != -1: idx = 0 for line in data.splitl...
[ "def", "get_group_index", "(", "self", ",", "data", ")", ":", "idx", "=", "-", "1", "li", "=", "self", ".", "get_group_line", "(", "data", ")", "if", "li", "!=", "-", "1", ":", "idx", "=", "0", "for", "line", "in", "data", ".", "splitlines", "(",...
Get the next groups style's starting line index :param data: string to parse :returns: the index if found else -1
[ "Get", "the", "next", "groups", "style", "s", "starting", "line", "index" ]
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L824-L837
train
dadadel/pyment
pyment/docstring.py
DocsTools.get_key_index
def get_key_index(self, data, key, starting=True): """Get from a docstring the next option with a given key. :param data: string to parse :param starting: does the key element must start the line (Default value = True) :type starting: boolean :param key: the key category. Can be...
python
def get_key_index(self, data, key, starting=True): """Get from a docstring the next option with a given key. :param data: string to parse :param starting: does the key element must start the line (Default value = True) :type starting: boolean :param key: the key category. Can be...
[ "def", "get_key_index", "(", "self", ",", "data", ",", "key", ",", "starting", "=", "True", ")", ":", "key", "=", "self", ".", "opt", "[", "key", "]", "[", "self", ".", "style", "[", "'in'", "]", "]", "[", "'name'", "]", "if", "key", ".", "star...
Get from a docstring the next option with a given key. :param data: string to parse :param starting: does the key element must start the line (Default value = True) :type starting: boolean :param key: the key category. Can be 'param', 'type', 'return', ... :returns: index of fou...
[ "Get", "from", "a", "docstring", "the", "next", "option", "with", "a", "given", "key", "." ]
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L839-L874
train
dadadel/pyment
pyment/docstring.py
DocString._extract_docs_description
def _extract_docs_description(self): """Extract main description from docstring""" # FIXME: the indentation of descriptions is lost data = '\n'.join([d.rstrip().replace(self.docs['out']['spaces'], '', 1) for d in self.docs['in']['raw'].splitlines()]) if self.dst.style['in'] == 'groups': ...
python
def _extract_docs_description(self): """Extract main description from docstring""" # FIXME: the indentation of descriptions is lost data = '\n'.join([d.rstrip().replace(self.docs['out']['spaces'], '', 1) for d in self.docs['in']['raw'].splitlines()]) if self.dst.style['in'] == 'groups': ...
[ "def", "_extract_docs_description", "(", "self", ")", ":", "# FIXME: the indentation of descriptions is lost", "data", "=", "'\\n'", ".", "join", "(", "[", "d", ".", "rstrip", "(", ")", ".", "replace", "(", "self", ".", "docs", "[", "'out'", "]", "[", "'spac...
Extract main description from docstring
[ "Extract", "main", "description", "from", "docstring" ]
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L1387-L1416
train
dadadel/pyment
pyment/docstring.py
DocString._extract_groupstyle_docs_params
def _extract_groupstyle_docs_params(self): """Extract group style parameters""" data = '\n'.join([d.rstrip().replace(self.docs['out']['spaces'], '', 1) for d in self.docs['in']['raw'].splitlines()]) idx = self.dst.get_group_key_line(data, 'param') if idx >= 0: data = data.spl...
python
def _extract_groupstyle_docs_params(self): """Extract group style parameters""" data = '\n'.join([d.rstrip().replace(self.docs['out']['spaces'], '', 1) for d in self.docs['in']['raw'].splitlines()]) idx = self.dst.get_group_key_line(data, 'param') if idx >= 0: data = data.spl...
[ "def", "_extract_groupstyle_docs_params", "(", "self", ")", ":", "data", "=", "'\\n'", ".", "join", "(", "[", "d", ".", "rstrip", "(", ")", ".", "replace", "(", "self", ".", "docs", "[", "'out'", "]", "[", "'spaces'", "]", ",", "''", ",", "1", ")",...
Extract group style parameters
[ "Extract", "group", "style", "parameters" ]
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L1418-L1441
train
dadadel/pyment
pyment/docstring.py
DocString._extract_docs_return
def _extract_docs_return(self): """Extract return description and type""" if self.dst.style['in'] == 'numpydoc': data = '\n'.join([d.rstrip().replace(self.docs['out']['spaces'], '', 1) for d in self.docs['in']['raw'].splitlines()]) self.docs['in']['return'] = self.dst.numpydoc.ge...
python
def _extract_docs_return(self): """Extract return description and type""" if self.dst.style['in'] == 'numpydoc': data = '\n'.join([d.rstrip().replace(self.docs['out']['spaces'], '', 1) for d in self.docs['in']['raw'].splitlines()]) self.docs['in']['return'] = self.dst.numpydoc.ge...
[ "def", "_extract_docs_return", "(", "self", ")", ":", "if", "self", ".", "dst", ".", "style", "[", "'in'", "]", "==", "'numpydoc'", ":", "data", "=", "'\\n'", ".", "join", "(", "[", "d", ".", "rstrip", "(", ")", ".", "replace", "(", "self", ".", ...
Extract return description and type
[ "Extract", "return", "description", "and", "type" ]
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L1585-L1599
train
dadadel/pyment
pyment/docstring.py
DocString._extract_docs_other
def _extract_docs_other(self): """Extract other specific sections""" if self.dst.style['in'] == 'numpydoc': data = '\n'.join([d.rstrip().replace(self.docs['out']['spaces'], '', 1) for d in self.docs['in']['raw'].splitlines()]) lst = self.dst.numpydoc.get_list_key(data, 'also') ...
python
def _extract_docs_other(self): """Extract other specific sections""" if self.dst.style['in'] == 'numpydoc': data = '\n'.join([d.rstrip().replace(self.docs['out']['spaces'], '', 1) for d in self.docs['in']['raw'].splitlines()]) lst = self.dst.numpydoc.get_list_key(data, 'also') ...
[ "def", "_extract_docs_other", "(", "self", ")", ":", "if", "self", ".", "dst", ".", "style", "[", "'in'", "]", "==", "'numpydoc'", ":", "data", "=", "'\\n'", ".", "join", "(", "[", "d", ".", "rstrip", "(", ")", ".", "replace", "(", "self", ".", "...
Extract other specific sections
[ "Extract", "other", "specific", "sections" ]
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L1601-L1610
train
dadadel/pyment
pyment/docstring.py
DocString._set_desc
def _set_desc(self): """Sets the global description if any""" # TODO: manage different in/out styles if self.docs['in']['desc']: self.docs['out']['desc'] = self.docs['in']['desc'] else: self.docs['out']['desc'] = ''
python
def _set_desc(self): """Sets the global description if any""" # TODO: manage different in/out styles if self.docs['in']['desc']: self.docs['out']['desc'] = self.docs['in']['desc'] else: self.docs['out']['desc'] = ''
[ "def", "_set_desc", "(", "self", ")", ":", "# TODO: manage different in/out styles", "if", "self", ".", "docs", "[", "'in'", "]", "[", "'desc'", "]", ":", "self", ".", "docs", "[", "'out'", "]", "[", "'desc'", "]", "=", "self", ".", "docs", "[", "'in'"...
Sets the global description if any
[ "Sets", "the", "global", "description", "if", "any" ]
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L1638-L1644
train
dadadel/pyment
pyment/docstring.py
DocString._set_params
def _set_params(self): """Sets the parameters with types, descriptions and default value if any""" # TODO: manage different in/out styles if self.docs['in']['params']: # list of parameters is like: (name, description, type) self.docs['out']['params'] = list(self.docs['in'...
python
def _set_params(self): """Sets the parameters with types, descriptions and default value if any""" # TODO: manage different in/out styles if self.docs['in']['params']: # list of parameters is like: (name, description, type) self.docs['out']['params'] = list(self.docs['in'...
[ "def", "_set_params", "(", "self", ")", ":", "# TODO: manage different in/out styles", "if", "self", ".", "docs", "[", "'in'", "]", "[", "'params'", "]", ":", "# list of parameters is like: (name, description, type)", "self", ".", "docs", "[", "'out'", "]", "[", "...
Sets the parameters with types, descriptions and default value if any
[ "Sets", "the", "parameters", "with", "types", "descriptions", "and", "default", "value", "if", "any" ]
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L1646-L1671
train
dadadel/pyment
pyment/docstring.py
DocString._set_raises
def _set_raises(self): """Sets the raises and descriptions""" # TODO: manage different in/out styles # manage setting if not mandatory for numpy but optional if self.docs['in']['raises']: if self.dst.style['out'] != 'numpydoc' or self.dst.style['in'] == 'numpydoc' or \ ...
python
def _set_raises(self): """Sets the raises and descriptions""" # TODO: manage different in/out styles # manage setting if not mandatory for numpy but optional if self.docs['in']['raises']: if self.dst.style['out'] != 'numpydoc' or self.dst.style['in'] == 'numpydoc' or \ ...
[ "def", "_set_raises", "(", "self", ")", ":", "# TODO: manage different in/out styles", "# manage setting if not mandatory for numpy but optional", "if", "self", ".", "docs", "[", "'in'", "]", "[", "'raises'", "]", ":", "if", "self", ".", "dst", ".", "style", "[", ...
Sets the raises and descriptions
[ "Sets", "the", "raises", "and", "descriptions" ]
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L1673-L1682
train
dadadel/pyment
pyment/docstring.py
DocString._set_return
def _set_return(self): """Sets the return parameter with description and rtype if any""" # TODO: manage return retrieved from element code (external) # TODO: manage different in/out styles if type(self.docs['in']['return']) is list and self.dst.style['out'] not in ['groups', 'numpydoc', ...
python
def _set_return(self): """Sets the return parameter with description and rtype if any""" # TODO: manage return retrieved from element code (external) # TODO: manage different in/out styles if type(self.docs['in']['return']) is list and self.dst.style['out'] not in ['groups', 'numpydoc', ...
[ "def", "_set_return", "(", "self", ")", ":", "# TODO: manage return retrieved from element code (external)", "# TODO: manage different in/out styles", "if", "type", "(", "self", ".", "docs", "[", "'in'", "]", "[", "'return'", "]", ")", "is", "list", "and", "self", "...
Sets the return parameter with description and rtype if any
[ "Sets", "the", "return", "parameter", "with", "description", "and", "rtype", "if", "any" ]
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L1684-L1700
train
dadadel/pyment
pyment/docstring.py
DocString._set_other
def _set_other(self): """Sets other specific sections""" # manage not setting if not mandatory for numpy if self.dst.style['in'] == 'numpydoc': if self.docs['in']['raw'] is not None: self.docs['out']['post'] = self.dst.numpydoc.get_raw_not_managed(self.docs['in']['raw...
python
def _set_other(self): """Sets other specific sections""" # manage not setting if not mandatory for numpy if self.dst.style['in'] == 'numpydoc': if self.docs['in']['raw'] is not None: self.docs['out']['post'] = self.dst.numpydoc.get_raw_not_managed(self.docs['in']['raw...
[ "def", "_set_other", "(", "self", ")", ":", "# manage not setting if not mandatory for numpy", "if", "self", ".", "dst", ".", "style", "[", "'in'", "]", "==", "'numpydoc'", ":", "if", "self", ".", "docs", "[", "'in'", "]", "[", "'raw'", "]", "is", "not", ...
Sets other specific sections
[ "Sets", "other", "specific", "sections" ]
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L1702-L1709
train
dadadel/pyment
pyment/docstring.py
DocString._set_raw
def _set_raw(self): """Sets the output raw docstring""" sep = self.dst.get_sep(target='out') sep = sep + ' ' if sep != ' ' else sep with_space = lambda s: '\n'.join([self.docs['out']['spaces'] + l if i > 0 else l for i, l in enumerate(s.splitlines())]) # sets the description sec...
python
def _set_raw(self): """Sets the output raw docstring""" sep = self.dst.get_sep(target='out') sep = sep + ' ' if sep != ' ' else sep with_space = lambda s: '\n'.join([self.docs['out']['spaces'] + l if i > 0 else l for i, l in enumerate(s.splitlines())]) # sets the description sec...
[ "def", "_set_raw", "(", "self", ")", ":", "sep", "=", "self", ".", "dst", ".", "get_sep", "(", "target", "=", "'out'", ")", "sep", "=", "sep", "+", "' '", "if", "sep", "!=", "' '", "else", "sep", "with_space", "=", "lambda", "s", ":", "'\\n'", "....
Sets the output raw docstring
[ "Sets", "the", "output", "raw", "docstring" ]
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L1912-L1950
train
dadadel/pyment
pyment/docstring.py
DocString.generate_docs
def generate_docs(self): """Generates the output docstring""" if self.dst.style['out'] == 'numpydoc' and self.dst.numpydoc.first_line is not None: self.first_line = self.dst.numpydoc.first_line self._set_desc() self._set_params() self._set_return() self._set_r...
python
def generate_docs(self): """Generates the output docstring""" if self.dst.style['out'] == 'numpydoc' and self.dst.numpydoc.first_line is not None: self.first_line = self.dst.numpydoc.first_line self._set_desc() self._set_params() self._set_return() self._set_r...
[ "def", "generate_docs", "(", "self", ")", ":", "if", "self", ".", "dst", ".", "style", "[", "'out'", "]", "==", "'numpydoc'", "and", "self", ".", "dst", ".", "numpydoc", ".", "first_line", "is", "not", "None", ":", "self", ".", "first_line", "=", "se...
Generates the output docstring
[ "Generates", "the", "output", "docstring" ]
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/docstring.py#L1952-L1962
train
dadadel/pyment
pyment/pymentapp.py
get_files_from_dir
def get_files_from_dir(path, recursive=True, depth=0, file_ext='.py'): """Retrieve the list of files from a folder. @param path: file or directory where to search files @param recursive: if True will search also sub-directories @param depth: if explore recursively, the depth of sub directories to follo...
python
def get_files_from_dir(path, recursive=True, depth=0, file_ext='.py'): """Retrieve the list of files from a folder. @param path: file or directory where to search files @param recursive: if True will search also sub-directories @param depth: if explore recursively, the depth of sub directories to follo...
[ "def", "get_files_from_dir", "(", "path", ",", "recursive", "=", "True", ",", "depth", "=", "0", ",", "file_ext", "=", "'.py'", ")", ":", "file_list", "=", "[", "]", "if", "os", ".", "path", ".", "isfile", "(", "path", ")", "or", "path", "==", "'-'...
Retrieve the list of files from a folder. @param path: file or directory where to search files @param recursive: if True will search also sub-directories @param depth: if explore recursively, the depth of sub directories to follow @param file_ext: the files extension to get. Default is '.py' @retur...
[ "Retrieve", "the", "list", "of", "files", "from", "a", "folder", "." ]
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/pymentapp.py#L17-L40
train
dadadel/pyment
pyment/pymentapp.py
get_config
def get_config(config_file): """Get the configuration from a file. @param config_file: the configuration file @return: the configuration @rtype: dict """ config = {} tobool = lambda s: True if s.lower() == 'true' else False if config_file: try: f = open(config_file,...
python
def get_config(config_file): """Get the configuration from a file. @param config_file: the configuration file @return: the configuration @rtype: dict """ config = {} tobool = lambda s: True if s.lower() == 'true' else False if config_file: try: f = open(config_file,...
[ "def", "get_config", "(", "config_file", ")", ":", "config", "=", "{", "}", "tobool", "=", "lambda", "s", ":", "True", "if", "s", ".", "lower", "(", ")", "==", "'true'", "else", "False", "if", "config_file", ":", "try", ":", "f", "=", "open", "(", ...
Get the configuration from a file. @param config_file: the configuration file @return: the configuration @rtype: dict
[ "Get", "the", "configuration", "from", "a", "file", "." ]
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/pymentapp.py#L43-L66
train
dadadel/pyment
pyment/pyment.py
PyComment.get_output_docs
def get_output_docs(self): """Return the output docstrings once formatted :returns: the formatted docstrings :rtype: list """ if not self.parsed: self._parse() lst = [] for e in self.docs_list: lst.append(e['docs'].get_raw_docs()) ...
python
def get_output_docs(self): """Return the output docstrings once formatted :returns: the formatted docstrings :rtype: list """ if not self.parsed: self._parse() lst = [] for e in self.docs_list: lst.append(e['docs'].get_raw_docs()) ...
[ "def", "get_output_docs", "(", "self", ")", ":", "if", "not", "self", ".", "parsed", ":", "self", ".", "_parse", "(", ")", "lst", "=", "[", "]", "for", "e", "in", "self", ".", "docs_list", ":", "lst", ".", "append", "(", "e", "[", "'docs'", "]", ...
Return the output docstrings once formatted :returns: the formatted docstrings :rtype: list
[ "Return", "the", "output", "docstrings", "once", "formatted" ]
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/pyment.py#L222-L234
train
dadadel/pyment
pyment/pyment.py
PyComment.compute_before_after
def compute_before_after(self): """Compute the list of lines before and after the proposed docstring changes. :return: tuple of before,after where each is a list of lines of python code. """ if not self.parsed: self._parse() list_from = self.input_lines list_...
python
def compute_before_after(self): """Compute the list of lines before and after the proposed docstring changes. :return: tuple of before,after where each is a list of lines of python code. """ if not self.parsed: self._parse() list_from = self.input_lines list_...
[ "def", "compute_before_after", "(", "self", ")", ":", "if", "not", "self", ".", "parsed", ":", "self", ".", "_parse", "(", ")", "list_from", "=", "self", ".", "input_lines", "list_to", "=", "[", "]", "last", "=", "0", "for", "e", "in", "self", ".", ...
Compute the list of lines before and after the proposed docstring changes. :return: tuple of before,after where each is a list of lines of python code.
[ "Compute", "the", "list", "of", "lines", "before", "and", "after", "the", "proposed", "docstring", "changes", "." ]
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/pyment.py#L236-L260
train
dadadel/pyment
pyment/pyment.py
PyComment.diff
def diff(self, source_path='', target_path='', which=-1): """Build the diff between original docstring and proposed docstring. :type which: int -> -1 means all the dosctrings of the file -> >=0 means the index of the docstring to proceed (Default value = -1) :param source_pa...
python
def diff(self, source_path='', target_path='', which=-1): """Build the diff between original docstring and proposed docstring. :type which: int -> -1 means all the dosctrings of the file -> >=0 means the index of the docstring to proceed (Default value = -1) :param source_pa...
[ "def", "diff", "(", "self", ",", "source_path", "=", "''", ",", "target_path", "=", "''", ",", "which", "=", "-", "1", ")", ":", "list_from", ",", "list_to", "=", "self", ".", "compute_before_after", "(", ")", "if", "source_path", ".", "startswith", "(...
Build the diff between original docstring and proposed docstring. :type which: int -> -1 means all the dosctrings of the file -> >=0 means the index of the docstring to proceed (Default value = -1) :param source_path: (Default value = '') :param target_path: (Default value...
[ "Build", "the", "diff", "between", "original", "docstring", "and", "proposed", "docstring", "." ]
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/pyment.py#L262-L287
train
dadadel/pyment
pyment/pyment.py
PyComment.get_patch_lines
def get_patch_lines(self, source_path, target_path): """Return the diff between source_path and target_path :param source_path: name of the original file (Default value = '') :param target_path: name of the final file (Default value = '') :return: the diff as a list of \n terminated li...
python
def get_patch_lines(self, source_path, target_path): """Return the diff between source_path and target_path :param source_path: name of the original file (Default value = '') :param target_path: name of the final file (Default value = '') :return: the diff as a list of \n terminated li...
[ "def", "get_patch_lines", "(", "self", ",", "source_path", ",", "target_path", ")", ":", "diff", "=", "self", ".", "diff", "(", "source_path", ",", "target_path", ")", "return", "[", "\"# Patch generated by Pyment v{0}\\n\\n\"", ".", "format", "(", "__version__", ...
Return the diff between source_path and target_path :param source_path: name of the original file (Default value = '') :param target_path: name of the final file (Default value = '') :return: the diff as a list of \n terminated lines :rtype: List[str]
[ "Return", "the", "diff", "between", "source_path", "and", "target_path" ]
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/pyment.py#L289-L300
train
dadadel/pyment
pyment/pyment.py
PyComment.write_patch_file
def write_patch_file(self, patch_file, lines_to_write): """Write lines_to_write to a the file called patch_file :param patch_file: file name of the patch to generate :param lines_to_write: lines to write to the file - they should be \n terminated :type lines_to_write: list[str] ...
python
def write_patch_file(self, patch_file, lines_to_write): """Write lines_to_write to a the file called patch_file :param patch_file: file name of the patch to generate :param lines_to_write: lines to write to the file - they should be \n terminated :type lines_to_write: list[str] ...
[ "def", "write_patch_file", "(", "self", ",", "patch_file", ",", "lines_to_write", ")", ":", "with", "open", "(", "patch_file", ",", "'w'", ")", "as", "f", ":", "f", ".", "writelines", "(", "lines_to_write", ")" ]
Write lines_to_write to a the file called patch_file :param patch_file: file name of the patch to generate :param lines_to_write: lines to write to the file - they should be \n terminated :type lines_to_write: list[str] :return: None
[ "Write", "lines_to_write", "to", "a", "the", "file", "called", "patch_file" ]
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/pyment.py#L302-L312
train
dadadel/pyment
pyment/pyment.py
PyComment.overwrite_source_file
def overwrite_source_file(self, lines_to_write): """overwrite the file with line_to_write :param lines_to_write: lines to write to the file - they should be \n terminated :type lines_to_write: List[str] :return: None """ tmp_filename = '{0}.writing'.format(self.input_fi...
python
def overwrite_source_file(self, lines_to_write): """overwrite the file with line_to_write :param lines_to_write: lines to write to the file - they should be \n terminated :type lines_to_write: List[str] :return: None """ tmp_filename = '{0}.writing'.format(self.input_fi...
[ "def", "overwrite_source_file", "(", "self", ",", "lines_to_write", ")", ":", "tmp_filename", "=", "'{0}.writing'", ".", "format", "(", "self", ".", "input_file", ")", "ok", "=", "False", "try", ":", "with", "open", "(", "tmp_filename", ",", "'w'", ")", "a...
overwrite the file with line_to_write :param lines_to_write: lines to write to the file - they should be \n terminated :type lines_to_write: List[str] :return: None
[ "overwrite", "the", "file", "with", "line_to_write" ]
3d1bdf87d083ff56230bd0bf7c5252e20552b7b6
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/pyment.py#L314-L335
train
what-studio/profiling
profiling/sortkeys.py
by_own_time_per_call
def by_own_time_per_call(stat): """Sorting by exclusive elapsed time per call in descending order.""" return (-stat.own_time_per_call if stat.own_hits else -stat.own_time, by_deep_time_per_call(stat))
python
def by_own_time_per_call(stat): """Sorting by exclusive elapsed time per call in descending order.""" return (-stat.own_time_per_call if stat.own_hits else -stat.own_time, by_deep_time_per_call(stat))
[ "def", "by_own_time_per_call", "(", "stat", ")", ":", "return", "(", "-", "stat", ".", "own_time_per_call", "if", "stat", ".", "own_hits", "else", "-", "stat", ".", "own_time", ",", "by_deep_time_per_call", "(", "stat", ")", ")" ]
Sorting by exclusive elapsed time per call in descending order.
[ "Sorting", "by", "exclusive", "elapsed", "time", "per", "call", "in", "descending", "order", "." ]
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/sortkeys.py#L61-L64
train
what-studio/profiling
profiling/profiler.py
Profiler.result
def result(self): """Gets the frozen statistics to serialize by Pickle.""" try: cpu_time = max(0, time.clock() - self._cpu_time_started) wall_time = max(0, time.time() - self._wall_time_started) except AttributeError: cpu_time = wall_time = 0.0 return ...
python
def result(self): """Gets the frozen statistics to serialize by Pickle.""" try: cpu_time = max(0, time.clock() - self._cpu_time_started) wall_time = max(0, time.time() - self._wall_time_started) except AttributeError: cpu_time = wall_time = 0.0 return ...
[ "def", "result", "(", "self", ")", ":", "try", ":", "cpu_time", "=", "max", "(", "0", ",", "time", ".", "clock", "(", ")", "-", "self", ".", "_cpu_time_started", ")", "wall_time", "=", "max", "(", "0", ",", "time", ".", "time", "(", ")", "-", "...
Gets the frozen statistics to serialize by Pickle.
[ "Gets", "the", "frozen", "statistics", "to", "serialize", "by", "Pickle", "." ]
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/profiler.py#L65-L72
train
what-studio/profiling
profiling/profiler.py
Profiler.dump
def dump(self, dump_filename, pickle_protocol=pickle.HIGHEST_PROTOCOL): """Saves the profiling result to a file :param dump_filename: path to a file :type dump_filename: str :param pickle_protocol: version of pickle protocol :type pickle_protocol: int """ result...
python
def dump(self, dump_filename, pickle_protocol=pickle.HIGHEST_PROTOCOL): """Saves the profiling result to a file :param dump_filename: path to a file :type dump_filename: str :param pickle_protocol: version of pickle protocol :type pickle_protocol: int """ result...
[ "def", "dump", "(", "self", ",", "dump_filename", ",", "pickle_protocol", "=", "pickle", ".", "HIGHEST_PROTOCOL", ")", ":", "result", "=", "self", ".", "result", "(", ")", "with", "open", "(", "dump_filename", ",", "'wb'", ")", "as", "f", ":", "pickle", ...
Saves the profiling result to a file :param dump_filename: path to a file :type dump_filename: str :param pickle_protocol: version of pickle protocol :type pickle_protocol: int
[ "Saves", "the", "profiling", "result", "to", "a", "file" ]
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/profiler.py#L74-L86
train
what-studio/profiling
profiling/profiler.py
Profiler.make_viewer
def make_viewer(self, title=None, at=None): """Makes a statistics viewer from the profiling result. """ viewer = StatisticsViewer() viewer.set_profiler_class(self.__class__) stats, cpu_time, wall_time = self.result() viewer.set_result(stats, cpu_time, wall_time, title=tit...
python
def make_viewer(self, title=None, at=None): """Makes a statistics viewer from the profiling result. """ viewer = StatisticsViewer() viewer.set_profiler_class(self.__class__) stats, cpu_time, wall_time = self.result() viewer.set_result(stats, cpu_time, wall_time, title=tit...
[ "def", "make_viewer", "(", "self", ",", "title", "=", "None", ",", "at", "=", "None", ")", ":", "viewer", "=", "StatisticsViewer", "(", ")", "viewer", ".", "set_profiler_class", "(", "self", ".", "__class__", ")", "stats", ",", "cpu_time", ",", "wall_tim...
Makes a statistics viewer from the profiling result.
[ "Makes", "a", "statistics", "viewer", "from", "the", "profiling", "result", "." ]
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/profiler.py#L88-L96
train
what-studio/profiling
profiling/remote/__init__.py
pack_msg
def pack_msg(method, msg, pickle_protocol=PICKLE_PROTOCOL): """Packs a method and message.""" dump = io.BytesIO() pickle.dump(msg, dump, pickle_protocol) size = dump.tell() return (struct.pack(METHOD_STRUCT_FORMAT, method) + struct.pack(SIZE_STRUCT_FORMAT, size) + dump.getvalue())
python
def pack_msg(method, msg, pickle_protocol=PICKLE_PROTOCOL): """Packs a method and message.""" dump = io.BytesIO() pickle.dump(msg, dump, pickle_protocol) size = dump.tell() return (struct.pack(METHOD_STRUCT_FORMAT, method) + struct.pack(SIZE_STRUCT_FORMAT, size) + dump.getvalue())
[ "def", "pack_msg", "(", "method", ",", "msg", ",", "pickle_protocol", "=", "PICKLE_PROTOCOL", ")", ":", "dump", "=", "io", ".", "BytesIO", "(", ")", "pickle", ".", "dump", "(", "msg", ",", "dump", ",", "pickle_protocol", ")", "size", "=", "dump", ".", ...
Packs a method and message.
[ "Packs", "a", "method", "and", "message", "." ]
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/remote/__init__.py#L60-L66
train
what-studio/profiling
profiling/remote/__init__.py
recv
def recv(sock, size): """Receives exactly `size` bytes. This function blocks the thread.""" data = sock.recv(size, socket.MSG_WAITALL) if len(data) < size: raise socket.error(ECONNRESET, 'Connection closed') return data
python
def recv(sock, size): """Receives exactly `size` bytes. This function blocks the thread.""" data = sock.recv(size, socket.MSG_WAITALL) if len(data) < size: raise socket.error(ECONNRESET, 'Connection closed') return data
[ "def", "recv", "(", "sock", ",", "size", ")", ":", "data", "=", "sock", ".", "recv", "(", "size", ",", "socket", ".", "MSG_WAITALL", ")", "if", "len", "(", "data", ")", "<", "size", ":", "raise", "socket", ".", "error", "(", "ECONNRESET", ",", "'...
Receives exactly `size` bytes. This function blocks the thread.
[ "Receives", "exactly", "size", "bytes", ".", "This", "function", "blocks", "the", "thread", "." ]
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/remote/__init__.py#L69-L74
train
what-studio/profiling
profiling/remote/__init__.py
recv_msg
def recv_msg(sock): """Receives a method and message from the socket. This function blocks the current thread. """ data = recv(sock, struct.calcsize(METHOD_STRUCT_FORMAT)) method, = struct.unpack(METHOD_STRUCT_FORMAT, data) data = recv(sock, struct.calcsize(SIZE_STRUCT_FORMAT)) size, = stru...
python
def recv_msg(sock): """Receives a method and message from the socket. This function blocks the current thread. """ data = recv(sock, struct.calcsize(METHOD_STRUCT_FORMAT)) method, = struct.unpack(METHOD_STRUCT_FORMAT, data) data = recv(sock, struct.calcsize(SIZE_STRUCT_FORMAT)) size, = stru...
[ "def", "recv_msg", "(", "sock", ")", ":", "data", "=", "recv", "(", "sock", ",", "struct", ".", "calcsize", "(", "METHOD_STRUCT_FORMAT", ")", ")", "method", ",", "=", "struct", ".", "unpack", "(", "METHOD_STRUCT_FORMAT", ",", "data", ")", "data", "=", ...
Receives a method and message from the socket. This function blocks the current thread.
[ "Receives", "a", "method", "and", "message", "from", "the", "socket", ".", "This", "function", "blocks", "the", "current", "thread", "." ]
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/remote/__init__.py#L77-L87
train
what-studio/profiling
profiling/remote/__init__.py
ProfilingServer.connected
def connected(self, client): """Call this method when a client connected.""" self.clients.add(client) self._log_connected(client) self._start_watching(client) self.send_msg(client, WELCOME, (self.pickle_protocol, __version__), pickle_protocol=0) prof...
python
def connected(self, client): """Call this method when a client connected.""" self.clients.add(client) self._log_connected(client) self._start_watching(client) self.send_msg(client, WELCOME, (self.pickle_protocol, __version__), pickle_protocol=0) prof...
[ "def", "connected", "(", "self", ",", "client", ")", ":", "self", ".", "clients", ".", "add", "(", "client", ")", "self", ".", "_log_connected", "(", "client", ")", "self", ".", "_start_watching", "(", "client", ")", "self", ".", "send_msg", "(", "clie...
Call this method when a client connected.
[ "Call", "this", "method", "when", "a", "client", "connected", "." ]
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/remote/__init__.py#L205-L228
train
what-studio/profiling
profiling/remote/__init__.py
ProfilingServer.disconnected
def disconnected(self, client): """Call this method when a client disconnected.""" if client not in self.clients: # already disconnected. return self.clients.remove(client) self._log_disconnected(client) self._close(client)
python
def disconnected(self, client): """Call this method when a client disconnected.""" if client not in self.clients: # already disconnected. return self.clients.remove(client) self._log_disconnected(client) self._close(client)
[ "def", "disconnected", "(", "self", ",", "client", ")", ":", "if", "client", "not", "in", "self", ".", "clients", ":", "# already disconnected.", "return", "self", ".", "clients", ".", "remove", "(", "client", ")", "self", ".", "_log_disconnected", "(", "c...
Call this method when a client disconnected.
[ "Call", "this", "method", "when", "a", "client", "disconnected", "." ]
49666ba3ea295eb73782ae6c18a4ec7929d7d8b7
https://github.com/what-studio/profiling/blob/49666ba3ea295eb73782ae6c18a4ec7929d7d8b7/profiling/remote/__init__.py#L230-L237
train