Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def form_valid(self, form): LOGGER.debug('termsandconditions.views.EmailTermsView.form_valid') template = get_template("termsandconditions/tc_email_terms.html") template_rendered = template.render({"terms": form.cleaned_data.get('terms')}) ...
[ "Override of CreateView method, sends the email." ]
Please provide a description of the function:def form_invalid(self, form): LOGGER.debug("Invalid Email Form Submitted") messages.add_message(self.request, messages.ERROR, _("Invalid Email Address.")) return super(EmailTermsView, self).form_invalid(form)
[ "Override of CreateView method, logs invalid email form submissions." ]
Please provide a description of the function:def terms_required(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): # If user has not logged in, or if they have logged in and already agreed to the terms, let the view through ...
[ "\n This decorator checks to see if the user is logged in, and if so, if they have accepted the site terms.\n ", "Method to wrap the view passed in" ]
Please provide a description of the function:def get_active(slug=DEFAULT_TERMS_SLUG): active_terms = cache.get('tandc.active_terms_' + slug) if active_terms is None: try: active_terms = TermsAndConditions.objects.filter( date_active__isnull=False...
[ "Finds the latest of a particular terms and conditions" ]
Please provide a description of the function: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 = TermsAndConditions.objects.filter(da...
[ "Returns a list of the IDs of of all terms and conditions" ]
Please provide a description of the function: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(id__in=TermsAndConditions.get_active_terms_ids()).order_by('slug') ...
[ "Returns all the latest active terms and conditions" ]
Please provide a description of the function: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_perm() returns True if is_superuser, we don't want ...
[ "Checks to see if a specified user has agreed to all the latest terms and conditions" ]
Please provide a description of the function:def show_terms_if_not_agreed(context, field=TERMS_HTTP_PATH_FIELD): request = context['request'] url = urlparse(request.META[field]) not_agreed_terms = TermsAndConditions.get_active_terms_not_agreed_to(request.user) if not_agreed_terms and is_path_prote...
[ "Displays a modal on a current page if a user has not yet agreed to the\n given terms. If terms are not specified, the default slug is used.\n\n A small snippet is included into your template if a user\n who requested the view has not yet agreed the terms. The snippet takes\n care of displaying a respec...
Please provide a description of the function:def user_accept_terms(backend, user, uid, social_user=None, *args, **kwargs): LOGGER.debug('user_accept_terms') if TermsAndConditions.get_active_terms_not_agreed_to(user): return redirect_to_terms_accept('/') else: return {'social_user': so...
[ "Check if the user has accepted the terms and conditions after creation." ]
Please provide a description of the function:def redirect_to_terms_accept(current_path='/', slug='default'): redirect_url_parts = list(urlparse(ACCEPT_TERMS_PATH)) if slug != 'default': redirect_url_parts[2] += slug querystring = QueryDict(redirect_url_parts[4], mutable=True) querystring[TE...
[ "Redirect the user to the terms and conditions accept page." ]
Please provide a description of the function:def user_terms_updated(sender, **kwargs): 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())
[ "Called when user terms and conditions is changed - to force cache clearing" ]
Please provide a description of the function:def terms_updated(sender, **kwargs): 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.active_terms_' + kwargs.get('instan...
[ "Called when terms and conditions is changed - to force cache clearing" ]
Please provide a description of the function:def paginate(parser, token, paginator_class=None): # Validate arguments. try: tag_name, tag_args = token.contents.split(None, 1) except ValueError: msg = '%r tag requires arguments' % token.contents.split()[0] raise template.TemplateS...
[ "Paginate objects.\n\n Usage:\n\n .. code-block:: html+django\n\n {% paginate entries %}\n\n After this call, the *entries* variable in the template context is replaced\n by only the entries of the current page.\n\n You can also keep your *entries* original variable (usually a queryset)\n a...
Please provide a description of the function:def get_pages(parser, token): # Validate args. try: tag_name, args = token.contents.split(None, 1) except ValueError: var_name = 'pages' else: args = args.split() if len(args) == 2 and args[0] == 'as': var_name...
[ "Add to context the list of page links.\n\n Usage:\n\n .. code-block:: html+django\n\n {% get_pages %}\n\n This is mostly used for Digg-style pagination.\n This call inserts in the template context a *pages* variable, as a sequence\n of page links. You can use *pages* in different ways:\n\n ...
Please provide a description of the function:def show_pages(parser, token): # Validate args. if len(token.contents.split()) != 1: msg = '%r tag takes no arguments' % token.contents.split()[0] raise template.TemplateSyntaxError(msg) # Call the node. return ShowPagesNode()
[ "Show page links.\n\n Usage:\n\n .. code-block:: html+django\n\n {% show_pages %}\n\n It is just a shortcut for:\n\n .. code-block:: html+django\n\n {% get_pages %}\n {{ pages.get_rendered }}\n\n You can set ``ENDLESS_PAGINATION_PAGE_LIST_CALLABLE`` in your *settings.py*\n to ...
Please provide a description of the function:def show_current_number(parser, token): # Validate args. try: tag_name, args = token.contents.split(None, 1) except ValueError: key = None number = None tag_name = token.contents[0] var_name = None else: # ...
[ "Show the current page number, or insert it in the context.\n\n This tag can for example be useful to change the page title according to\n the current page number.\n\n To just show current page number:\n\n .. code-block:: html+django\n\n {% show_current_number %}\n\n If you use multiple pagina...
Please provide a description of the function:def page_template(template, key=PAGE_LABEL): def decorator(view): @wraps(view) def decorated(request, *args, **kwargs): # Trust the developer: he wrote ``context.update(extra_context)`` # in his view. extra_context...
[ "Return a view dynamically switching template if the request is Ajax.\n\n Decorate a view that takes a *template* and *extra_context* keyword\n arguments (like generic views).\n The template is switched to *page_template* if request is ajax and\n if *querystring_key* variable passed by the request equal...
Please provide a description of the function:def _get_template(querystring_key, mapping): default = None try: template_and_keys = mapping.items() except AttributeError: template_and_keys = mapping for template, key in template_and_keys: if key is None: key = PAGE...
[ "Return the template corresponding to the given ``querystring_key``." ]
Please provide a description of the function:def page_templates(mapping): def decorator(view): @wraps(view) def decorated(request, *args, **kwargs): # Trust the developer: he wrote ``context.update(extra_context)`` # in his view. extra_context = kwargs.setdef...
[ "Like the *page_template* decorator but manage multiple paginations.\n\n You can map multiple templates to *querystring_keys* using the *mapping*\n dict, e.g.::\n\n @page_templates({\n 'page_contents1.html': None,\n 'page_contents2.html': 'go_to_page',\n })\n def myv...
Please provide a description of the function:def get_queryset(self): if self.queryset is not None: queryset = self.queryset if hasattr(queryset, '_clone'): queryset = queryset._clone() elif self.model is not None: queryset = self.model._defaul...
[ "Get the list of items for this view.\n\n This must be an interable, and may be a queryset\n (in which qs-specific behavior will be enabled).\n\n See original in ``django.views.generic.list.MultipleObjectMixin``.\n " ]
Please provide a description of the function: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_list.model._meta.object_name.lower() return smar...
[ "Get the name of the item to be used in the context.\n\n See original in ``django.views.generic.list.MultipleObjectMixin``.\n " ]
Please provide a description of the function:def get(self, request, *args, **kwargs): response = super().get(request, args, kwargs) try: response.render() except Http404: request.GET = request.GET.copy() request.GET['page'] = '1' response ...
[ "Wraps super().get(...) in order to return 404 status code if\n the page parameter is invalid\n " ]
Please provide a description of the function: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.lower(), self.template_name_suffix, self.page_template_suf...
[ "Return the template name used for this request.\n\n Only called if *page_template* is not given as a kwarg of\n *self.as_view*.\n " ]
Please provide a description of the function:def get_template_names(self): request = self.request key = 'querystring_key' querystring_key = request.GET.get(key, request.POST.get(key, PAGE_LABEL)) if request.is_ajax() and querystring_key == self.key: retur...
[ "Switch the templates for Ajax requests." ]
Please provide a description of the function:def render_link(self): extra_context = { 'add_nofollow': settings.ADD_NOFOLLOW, 'page': self, 'querystring_key': self.querystring_key, } if self.is_current: template_name = 'el_pagination/curren...
[ "Render the page as a link." ]
Please provide a description of the function:def previous(self): if self._page.has_previous(): return self._endless_page( self._page.previous_page_number(), label=settings.PREVIOUS_LABEL) return ''
[ "Return the previous page.\n\n The page label is defined in ``settings.PREVIOUS_LABEL``.\n Return an empty string if current page is the first.\n " ]
Please provide a description of the function:def next(self): if self._page.has_next(): return self._endless_page( self._page.next_page_number(), label=settings.NEXT_LABEL) return ''
[ "Return the next page.\n\n The page label is defined in ``settings.NEXT_LABEL``.\n Return an empty string if current page is the last.\n " ]
Please provide a description of the function: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 ( (self.number - 2) * pagi...
[ "Return the 1-based index of the first item on this page." ]
Please provide a description of the function: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 return (self.number - 1) * paginator.per_page + p...
[ "Return the 1-based index of the last item on this page." ]
Please provide a description of the function:def get_page_numbers( current_page, num_pages, extremes=DEFAULT_CALLABLE_EXTREMES, arounds=DEFAULT_CALLABLE_AROUNDS, arrows=DEFAULT_CALLABLE_ARROWS): page_range = range(1, num_pages + 1) pages = [] if current_page != 1: ...
[ "Default callable for page listing.\n\n Produce a Digg-style pagination.\n " ]
Please provide a description of the function: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) left_half, right_half = [], [] left_val, right_val = begin, end right_val = end ...
[ "Generate an S-curved range of pages.\n\n Start from both left and right, adding exponentially growing indexes,\n until the two trends collide.\n " ]
Please provide a description of the function: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 = [1] else: pages = ['first', 'previous'] pages.extend(_make_elastic_range(1, current_...
[ "Alternative callable for page listing.\n\n Produce an adaptive pagination, useful for big numbers of pages, by\n splitting the num_pages ranges in two parts at current_page. Each part\n will have its own S-curve.\n " ]
Please provide a description of the function:def get_querystring_for_page( request, page_number, querystring_key, default_number=1): querydict = request.GET.copy() querydict[querystring_key] = page_number # For the default page number (usually 1) the querystring is not required. if page_num...
[ "Return a querystring pointing to *page_number*." ]
Please provide a description of the function:def load_object(path): i = path.rfind('.') module_name, object_name = path[:i], path[i + 1:] # Load module. try: module = import_module(module_name) except ImportError: raise ImproperlyConfigured('Module %r not found' % module_name) ...
[ "Return the Python object represented by dotted *path*." ]
Please provide a description of the function:def south_field_triple(self): "Returns a suitable description of this field for South." args, kwargs = introspector(self) kwargs.update({ 'populate_from': 'None' if callable(self.populate_from) else repr(self.populate_from), 'u...
[]
Please provide a description of the function:def get_prepopulated_value(field, instance): if hasattr(field.populate_from, '__call__'): # AutoSlugField(populate_from=lambda instance: ...) return field.populate_from(instance) else: # AutoSlugField(populate_from='foo') attr = g...
[ "\n Returns preliminary value based on `populate_from`.\n " ]
Please provide a description of the function:def generate_unique_slug(field, instance, slug, manager): original_slug = slug = crop_slug(field, slug) default_lookups = tuple(get_uniqueness_lookups(field, instance, field.unique_with)) index = 1 if not manager: manager = field.model._defau...
[ "\n Generates unique slug by adding a number to given value until no model\n instance can be found with such slug. If ``unique_with`` (a tuple of field\n names) was specified for the field, all these fields are included together\n in the query when looking for a \"rival\" model instance.\n " ]
Please provide a description of the function: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.split('__', 1) else: field_name, inner_lookup ...
[ "\n Returns a dict'able tuple of lookups to ensure uniqueness of a slug.\n " ]
Please provide a description of the function:def derivative_colors(colors): return set([('on_' + c) for c in colors] + [('bright_' + c) for c in colors] + [('on_bright_' + c) for c in colors])
[ "Return the names of valid color variants, given the base colors." ]
Please provide a description of the function: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 compound.split('_'): if merged_segs and merged_segs[-1] in merge...
[ "Split a possibly compound format string into segments.\n\n >>> split_into_formatters('bold_underline_bright_blue_on_red')\n ['bold', 'underline', 'bright_blue', 'on_red']\n >>> split_into_formatters('red_no_italic_shadow_on_bright_cyan')\n ['red', 'no_italic', 'shadow', 'on_bright_cyan']\n " ]
Please provide a description of the function:def _height_and_width(self): # tigetnum('lines') and tigetnum('cols') update only if we call # setupterm() again. for descriptor in self._init_descriptor, sys.__stdout__: try: return struct.unpack( ...
[ "Return a tuple of (terminal height, terminal width).\n\n Start by trying TIOCGWINSZ (Terminal I/O-Control: Get Window Size),\n falling back to environment variables (LINES, COLUMNS), and returning\n (None, None) if those are unavailable or invalid.\n\n " ]
Please provide a description of the function: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 and y is not None: self.stream.write(self.move(y, x)) elif x is not None: ...
[ "Return a context manager for temporarily moving the cursor.\n\n Move the cursor to a certain position on entry, let you print stuff\n there, then return the cursor to its original position::\n\n term = Terminal()\n with term.location(2, 5):\n print('Hello, world!'...
Please provide a description of the function: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\n and restores normal mode on leaving." ]
Please provide a description of the function: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\n makes it visible on leaving." ]
Please provide a description of the function: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 return self._formatting_string(self._reso...
[ "Resolve a sugary or plain capability name, color, or compound\n formatting function name into a callable capability.\n\n Return a ``ParametrizingString`` or a ``FormattingString``.\n\n " ]
Please provide a description of the function: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 code.decode('latin1') return u''
[ "Return a terminal code for a capname or a sugary name, or an empty\n Unicode.\n\n The return value is always Unicode, because otherwise it is clumsy\n (especially in Python 3) to concatenate with real (Unicode) strings.\n\n " ]
Please provide a description of the function: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 ...
[ "Resolve a color like red or on_bright_green into a callable\n capability." ]
Please provide a description of the function:def send_login_code(self, code, context, **kwargs): 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=cod...
[ "\n Send a login code via SMS\n " ]
Please provide a description of the function:def load(filename, **kwargs): with open(filename, 'rb') as f: reader = T7Reader(f, **kwargs) return reader.read_obj()
[ "\n Loads the given t7 file using default settings; kwargs are forwarded\n to `T7Reader`.\n " ]
Please provide a description of the function:def get_assets(): args = [] query = dict() args.append(query) asset_with_id = dao.get_all_listed_assets() asset_ids = [a['id'] for a in asset_with_id] resp_body = dict({'ids': asset_ids}) return Response(_sanitize_record(resp_body), 200, cont...
[ "Get all asset IDs.\n ---\n tags:\n - ddo\n responses:\n 200:\n description: successful action\n " ]
Please provide a description of the function:def get_ddo(did): try: asset_record = dao.get(did) return Response(_sanitize_record(asset_record), 200, content_type='application/json') except Exception as e: logger.error(e) return f'{did} asset DID is not in OceanDB', 404
[ "Get DDO of a particular asset.\n ---\n tags:\n - ddo\n parameters:\n - name: did\n in: path\n description: DID of the asset.\n required: true\n type: string\n responses:\n 200:\n description: successful operation\n 404:\n description: This a...
Please provide a description of the function:def get_metadata(did): try: asset_record = dao.get(did) metadata = _get_metadata(asset_record['service']) return Response(_sanitize_record(metadata), 200, content_type='application/json') except Exception as e: logger.error(e) ...
[ "Get metadata of a particular asset\n ---\n tags:\n - metadata\n parameters:\n - name: did\n in: path\n description: DID of the asset.\n required: true\n type: string\n responses:\n 200:\n description: successful operation.\n 404:\n descripti...
Please provide a description of the function:def register(): assert isinstance(request.json, dict), 'invalid payload format.' required_attributes = ['@context', 'created', 'id', 'publicKey', 'authentication', 'proof', 'service'] required_metadata_base_attributes = ['name', 'd...
[ "Register DDO of a new asset\n ---\n tags:\n - ddo\n consumes:\n - application/json\n parameters:\n - in: body\n name: body\n required: true\n description: DDO of the asset.\n schema:\n type: object\n required:\n - \"@context\"\n ...
Please provide a description of the function:def update(did): required_attributes = ['@context', 'created', 'id', 'publicKey', 'authentication', 'proof', 'service'] required_metadata_base_attributes = ['name', 'dateCreated', 'author', 'license', ...
[ "Update DDO of an existing asset\n ---\n tags:\n - ddo\n consumes:\n - application/json\n parameters:\n - in: body\n name: body\n required: true\n description: DDO of the asset.\n schema:\n type: object\n required:\n - \"@context\"\...
Please provide a description of the function:def retire(did): try: if dao.get(did) is None: return 'This asset DID is not in OceanDB', 404 else: dao.delete(did) return 'Succesfully deleted', 200 except Exception as err: return f'Some error: {str(e...
[ "Retire metadata of an asset\n ---\n tags:\n - ddo\n parameters:\n - name: did\n in: path\n description: DID of the asset.\n required: true\n type: string\n responses:\n 200:\n description: successfully deleted\n 404:\n description: This asse...
Please provide a description of the function:def get_asset_ddos(): args = [] query = dict() args.append(query) assets_with_id = dao.get_all_listed_assets() assets_metadata = {a['id']: a for a in assets_with_id} for i in assets_metadata: _sanitize_record(i) return Response(json.d...
[ "Get DDO of all assets.\n ---\n tags:\n - ddo\n responses:\n 200:\n description: successful action\n " ]
Please provide a description of the function:def query_text(): data = request.args assert isinstance(data, dict), 'invalid `args` type, should already formatted into a dict.' search_model = FullTextModel(text=data.get('text', None), sort=None if data.get('sort', None) i...
[ "Get a list of DDOs that match with the given text.\n ---\n tags:\n - ddo\n parameters:\n - name: text\n in: query\n description: ID of the asset.\n required: true\n type: string\n - name: sort\n in: query\n type: object\n description: Key or ...
Please provide a description of the function:def query_ddo(): assert isinstance(request.json, dict), 'invalid payload format.' data = request.json assert isinstance(data, dict), 'invalid `body` type, should be formatted as a dict.' if 'query' in data: search_model = QueryModel(query=data.ge...
[ "Get a list of DDOs that match with the executed query.\n ---\n tags:\n - ddo\n consumes:\n - application/json\n parameters:\n - in: body\n name: body\n required: true\n description: Asset metadata.\n schema:\n type: object\n properties:\n ...
Please provide a description of the function:def retire_all(): try: all_ids = [a['id'] for a in dao.get_all_assets()] for i in all_ids: dao.delete(i) return 'All ddo successfully deleted', 200 except Exception as e: logger.error(e) return 'An error was fo...
[ "Retire metadata of all the assets.\n ---\n tags:\n - ddo\n responses:\n 200:\n description: successfully deleted\n 500:\n description: Error\n " ]
Please provide a description of the function:def validate(): assert isinstance(request.json, dict), 'invalid payload format.' data = request.json assert isinstance(data, dict), 'invalid `body` type, should be formatted as a dict.' if is_valid_dict(data): return jsonify(True) else: ...
[ "Validate metadata content.\n ---\n tags:\n - ddo\n consumes:\n - application/json\n parameters:\n - in: body\n name: body\n required: true\n description: Asset metadata.\n schema:\n type: object\n responses:\n 200:\n description: succes...
Please provide a description of the function:def setup_logging(default_path='logging.yaml', default_level=logging.INFO, env_key='LOG_CFG'): path = default_path value = os.getenv(env_key, None) if value: path = value if os.path.exists(path): with open(path, 'rt') as f: tr...
[ "Logging Setup" ]
Please provide a description of the function:def load_plugins(self): ''' Given a set of plugin_path strings (directory names on the python path), load any classes with Plugin in the name from any files within those dirs. ''' self._dbg("Loading plugins") if not self.active_plugins...
[]
Please provide a description of the function: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
[]
Please provide a description of the function:def transaction(self, request): request_url = request.build_absolute_uri() parsed_url = urlparse.urlparse(request_url) query = parsed_url.query dd = dict(map(lambda x: x.split("="), query.split("&"))) resp = self.purchase(100,...
[ "Ideally at this method, you will check the \n caller reference against a user id or uniquely\n identifiable attribute (if you are already not \n using it as the caller reference) and the type \n of transaction (either pay, reserve etc). For\n the sake of the example, we assume al...
Please provide a description of the function:def make_union(*transformers, **kwargs): n_jobs = kwargs.pop('n_jobs', 1) concatenate = kwargs.pop('concatenate', True) if kwargs: # We do not currently support `transformer_weights` as we may want to # change its type spec in make_union ...
[ "Construct a FeatureUnion from the given transformers.\n\n This is a shorthand for the FeatureUnion constructor; it does not require,\n and does not permit, naming the transformers. Instead, they will be given\n names automatically based on their types. It also does not allow weighting.\n\n Parameters\n...
Please provide a description of the function:def _iter(self): get_weight = (self.transformer_weights or {}).get return ((name, trans, get_weight(name)) for name, trans in self.transformer_list if trans is not None)
[ "Generate (name, est, weight) tuples excluding None transformers\n " ]
Please provide a description of the function:def get_feature_names(self): feature_names = [] for name, trans, weight in self._iter(): if not hasattr(trans, 'get_feature_names'): raise AttributeError("Transformer %s (type %s) does not " ...
[ "Get feature names from all transformers.\n\n Returns\n -------\n feature_names : list of strings\n Names of the features produced by transform.\n " ]
Please provide a description of the function:def fit(self, X, y=None): self.transformer_list = list(self.transformer_list) self._validate_transformers() with Pool(self.n_jobs) as pool: transformers = pool.starmap(_fit_one_transformer, ((trans, X[trans...
[ "Fit all transformers using X.\n\n Parameters\n ----------\n X : iterable or array-like, depending on transformers\n Input data, used to fit transformers.\n\n y : array-like, shape (n_samples, ...), optional\n Targets for supervised learning.\n\n Returns\n ...
Please provide a description of the function:def fit_transform(self, X, y=None, **fit_params): self._validate_transformers() with Pool(self.n_jobs) as pool: result = pool.starmap(_fit_transform_one, ((trans, weight, X[trans['col_pick']] if hasattr(trans, 'co...
[ "Fit all transformers, transform the data and concatenate results.\n\n Parameters\n ----------\n X : iterable or array-like, depending on transformers\n Input data to be transformed.\n\n y : array-like, shape (n_samples, ...), optional\n Targets for supervised learn...
Please provide a description of the function:def transform(self, X): with Pool(self.n_jobs) as pool: Xs = pool.starmap(_transform_one, ((trans, weight, X[trans['col_pick']] if hasattr(trans, 'col_pick') else X) for name, trans, weight in self._iter())) if not Xs:...
[ "Transform X separately by each transformer, concatenate results.\n\n Parameters\n ----------\n X : iterable or array-like, depending on transformers\n Input data to be transformed.\n\n Returns\n -------\n X_t : array-like or sparse matrix, shape (n_samples, sum_...
Please provide a description of the function:def split_batches(self, data, minibatch_size= None): if minibatch_size==None: minibatch_size= self.minibatch_size if isinstance(data, list) or isinstance(data, tuple): len_data= len(data) else: len_data= data.shape[0] if isinstance(data,pd.DataFrame): data_sp...
[ "Split data into minibatches with a specified size\n\n\t\tParameters\n\t\t----------\n\t\tdata: iterable and indexable\n\t\t\tList-like data to be split into batches. Includes spark_contextipy matrices and Pandas DataFrames.\n\n\t\tminibatch_size: int\n\t\t\tExpected sizes of minibatches split from the data.\n\n\t\...
Please provide a description of the function:def merge_batches(self, data): if isinstance(data[0], ssp.csr_matrix): return ssp.vstack(data) if isinstance(data[0], pd.DataFrame) or isinstance(data[0], pd.Series): return pd.concat(data) return [item for sublist in data for item in sublist]
[ "Merge a list of data minibatches into one single instance representing the data\n\n\t\tParameters\n\t\t----------\n\t\tdata: list\n\t\t\tList of minibatches to merge\n\n\t\tReturns\n\t\t-------\n\t\t(anonymous): sparse matrix | pd.DataFrame | list\n\t\t\tSingle complete list-like data merged from given batches\n\t...
Please provide a description of the function:def shuffle_batch(self, texts, labels= None, seed= None): if seed!=None: random.seed(seed) index_shuf= list(range(len(texts))) random.shuffle(index_shuf) texts= [texts[x] for x in index_shuf] if labels==None: return texts labels= [labels[x] for x in index_sh...
[ "Shuffle a list of samples, as well as the labels if specified\n\n\t\tParameters\n\t\t----------\n\t\ttexts: list-like\n\t\t\tList of samples to shuffle\n\n\t\tlabels: list-like (optional)\n\t\t\tList of labels to shuffle, should be correspondent to the samples given\n\n\t\tseed: int\n\t\t\tThe seed of the pseudo r...
Please provide a description of the function:def parametric_line(x, y): if len(x) != len(y): raise ValueError("Arrays must be the same length") X = np.ones((len(x), len(x)))*np.nan Y = X.copy() for i in range(len(x)): X[i, :(i+1)] = x[:(i+1)] Y[i, :(i+1)] = y[:(i+1)] r...
[ "\n Parameters\n ----------\n x : 1D numpy array\n y : 1D numpy array\n " ]
Please provide a description of the function:def demeshgrid(arr): dim = len(arr.shape) for i in range(dim): Slice1 = [0]*dim Slice2 = [1]*dim Slice1[i] = slice(None) Slice2[i] = slice(None) if (arr[tuple(Slice1)] == arr[tuple(Slice2)]).all(): return arr[t...
[ "Turns an ndarray created by a meshgrid back into a 1D array\n\n Parameters\n ----------\n arr : array of dimension > 1\n This array should have been created by a meshgrid.\n " ]
Please provide a description of the function:def toggle(self, ax=None): if ax is None: adjust_plot = {'bottom': .2} rect = [.78, .03, .1, .07] plt.subplots_adjust(**adjust_plot) self.button_ax = plt.axes(rect) else: self.button_ax = a...
[ "Creates a play/pause button to start/stop the animation\n\n Parameters\n ----------\n ax : matplotlib.axes.Axes, optional\n The matplotlib axes to attach the button to.\n " ]
Please provide a description of the function:def timeline_slider(self, text='Time', ax=None, valfmt=None, color=None): if ax is None: adjust_plot = {'bottom': .2} rect = [.18, .05, .5, .03] plt.subplots_adjust(**adjust_plot) self.slider_ax = plt.axes(rec...
[ "Creates a timeline slider.\n\n Parameters\n ----------\n text : str, optional\n The text to display for the slider. Defaults to 'Time'\n ax : matplotlib.axes.Axes, optional\n The matplotlib axes to attach the slider to.\n valfmt : str, optional\n ...
Please provide a description of the function:def controls(self, timeline_slider_args={}, toggle_args={}): self.timeline_slider(**timeline_slider_args) self.toggle(**toggle_args)
[ "Creates interactive controls for the animation\n\n Creates both a play/pause button, and a time slider at once\n\n Parameters\n ----------\n timeline_slider_args : Dict, optional\n A dictionary of arguments to be passed to timeline_slider()\n toggle_args : Dict, option...
Please provide a description of the function:def save_gif(self, filename): self.timeline.index -= 1 # required for proper starting point for save self.animation.save(filename+'.gif', writer=PillowWriter(fps=self.timeline.fps))
[ "Saves the animation to a gif\n\n A convience function. Provided to let the user avoid dealing\n with writers.\n\n Parameters\n ----------\n filename : str\n the name of the file to be created without the file extension\n " ]
Please provide a description of the function:def save(self, *args, **kwargs): self.timeline.index -= 1 # required for proper starting point for save self.animation.save(*args, **kwargs)
[ "Saves an animation\n\n A wrapper around :meth:`matplotlib.animation.Animation.save`\n " ]
Please provide a description of the function:def vector_comp(X, Y, U, V, skip=5, *, t_axis=0, pcolor_kw={}, quiver_kw={}): # plot the magnitude of the vectors as a pcolormesh magnitude = np.sqrt(U**2+V**2) pcolor_block = Pcolormesh(X, Y, magnitude, t_axis=t_axis, **pcolor_kw) # use a subset of the...
[ "produces an animation of vector fields\n\n This takes 2D vector field, and plots the magnitude as a pcolomesh, and the\n normalized direction as a quiver plot. It then animates it.\n\n This is a convience function. It wraps around the Pcolormesh and Quiver\n blocks. It will be more restrictive than usi...
Please provide a description of the function:def vector_plot(X, Y, U, V, t, skip=5, *, t_axis=0, units='', fps=10, pcolor_kw={}, quiver_kw={}): # plot the magnitude of the vectors as a pcolormesh blocks = vector_comp(X, Y, U, V, skip, t_axis=t_axis, pcolor_kw=pcolor...
[ "produces an animation of vector fields\n\n This takes 2D vector field, and plots the magnitude as a pcolomesh, and the\n normalized direction as a quiver plot. It then animates it.\n\n This is a convience function. It wraps around the Pcolormesh and Quiver\n blocks. It will be more restrictive than usi...
Please provide a description of the function:def isin_alone(elems, line): found = False for e in elems: if line.strip().lower() == e.lower(): found = True break return found
[ "Check if an element from a list is the only element of a string.\n\n :type elems: list\n :type line: str\n\n " ]
Please provide a description of the function:def isin_start(elems, line): found = False elems = [elems] if type(elems) is not list else elems for e in elems: if line.lstrip().lower().startswith(e): found = True break return found
[ "Check if an element from a list starts a string.\n\n :type elems: list\n :type line: str\n\n " ]
Please provide a description of the function: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.\n\n :type elems: list\n :type line: str\n\n " ]
Please provide a description of the function: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\n\n :type data: str\n\n " ]
Please provide a description of the function: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" ]
Please provide a description of the function:def get_list_key(self, data, key, header_lines=1): data = data.splitlines() init = self.get_section_key_line(data, key) if init == -1: return [] start, end = self.get_next_section_lines(data[init:]) # get the spaci...
[ "Get the list of a key elements.\n Each element is a tuple (key=None, description, type=None).\n Note that the tuple's element can differ depending on the key.\n\n :param data: the data to proceed\n :param key: the key\n\n " ]
Please provide a description of the function:def get_raise_list(self, data): return_list = [] lst = self.get_list_key(data, 'raise') for l in lst: # assume raises are only a name and a description name, desc, _ = l return_list.append((name, desc)) ...
[ "Get the list of exceptions.\n The list contains tuples (name, desc)\n\n :param data: the data to proceed\n\n " ]
Please provide a description of the function:def get_return_list(self, data): return_list = [] lst = self.get_list_key(data, 'return') for l in lst: name, desc, rtype = l if l[2] is None: rtype = l[0] name = None de...
[ "Get the list of returned values.\n The list contains tuples (name=None, desc, type=None)\n\n :param data: the data to proceed\n\n " ]
Please provide a description of the function:def get_next_section_lines(self, data): end = -1 start = self.get_next_section_start_line(data) if start != -1: end = self.get_next_section_start_line(data[start + 1:]) return start, end
[ "Get the starting line number and the ending line number of next section.\n It will return (-1, -1) if no section was found.\n The section is a section key (e.g. 'Parameters') then the content\n The ending line number is the line after the end of the section or -1 if\n the section is at ...
Please provide a description of the function:def get_key_section_header(self, key, spaces): if key in self.section_headers: header = self.section_headers[key] else: return '' return header
[ "Get the key of the section header\n\n :param key: the key name\n :param spaces: spaces to set at the beginning of the header\n\n " ]
Please provide a description of the function:def get_section_key_line(self, data, key, opt_extension=''): start = 0 init = 0 while start != -1: start = self.get_next_section_start_line(data[init:]) init += start if start != -1: if data...
[ "Get the next section line for a given key.\n\n :param data: the data to proceed\n :param key: the key\n :param opt_extension: an optional extension to delimit the opt value\n\n " ]
Please provide a description of the function:def get_next_section_start_line(self, data): start = -1 for i, line in enumerate(data): if start != -1: # we found the key so check if this is the underline if line.strip() and isin_alone(['-' * len(line.st...
[ "Get the starting line number of next section.\n It will return -1 if no section was found.\n The section is a section key (e.g. 'Parameters') followed by underline\n (made by -), then the content\n\n :param data: a list of strings containing the docstring's lines\n :type data: li...
Please provide a description of the function:def get_list_key(self, data, key, header_lines=2): return super(NumpydocTools, self).get_list_key(data, key, header_lines=header_lines)
[ "Get the list of a key elements.\n Each element is a tuple (key=None, description, type=None).\n Note that the tuple's element can differ depending on the key.\n\n :param data: the data to proceed\n :param key: the key\n\n " ]
Please provide a description of the function:def get_raw_not_managed(self, data): keys = ['also', 'ref', 'note', 'other', 'example', 'method', 'attr'] elems = [self.opt[k] for k in self.opt if k in keys] data = data.splitlines() start = 0 init = 0 raw = '' ...
[ "Get elements not managed. They can be used as is.\n\n :param data: the data to proceed\n\n " ]
Please provide a description of the function:def get_key_section_header(self, key, spaces): header = super(NumpydocTools, self).get_key_section_header(key, spaces) header = spaces + header + '\n' + spaces + '-' * len(header) + '\n' return header
[ "Get the key of the header section\n\n :param key: the key name\n :param spaces: spaces to set at the beginning of the header\n\n " ]
Please provide a description of the function:def get_section_key_line(self, data, key, opt_extension=':'): return super(GoogledocTools, self).get_section_key_line(data, key, opt_extension)
[ "Get the next section line for a given key.\n\n :param data: the data to proceed\n :param key: the key\n :param opt_extension: an optional extension to delimit the opt value\n\n " ]
Please provide a description of the function:def get_next_section_start_line(self, data): start = -1 for i, line in enumerate(data): if isin_alone([k + ":" for k in self.opt.values()], line): start = i break return start
[ "Get the starting line number of next section.\n It will return -1 if no section was found.\n The section is a section key (e.g. 'Parameters:')\n then the content\n\n :param data: a list of strings containing the docstring's lines\n :returns: the index of next section else -1\n\n ...
Please provide a description of the function:def get_key_section_header(self, key, spaces): header = super(GoogledocTools, self).get_key_section_header(key, spaces) header = spaces + header + ':' + '\n' return header
[ "Get the key of the section header\n\n :param key: the key name\n :param spaces: spaces to set at the beginning of the header\n\n " ]