Code
stringlengths
103
85.9k
Summary
sequencelengths
0
94
Please provide a description of the function:def is_obsolete(self): if self.cache_updated: now = timezone.now() delta = now - self.cache_updated if delta.seconds < self.cache_validity: return False return True
[ "returns True is data is obsolete and needs revalidation\n " ]
Please provide a description of the function:def update_cache(self, data=None): if data: self.cache_data = data self.cache_updated = timezone.now() self.save()
[ "call with new data or set data to self.cache_data and call this\n " ]
Please provide a description of the function:def data(self): if self.is_obsolete(): self.update_cache(self.get_data()) return self.cache_data
[ "this property just calls ``get_data``\n but here you can serilalize your data or render as html\n these data will be saved to self.cached_content\n also will be accessable from template\n " ]
Please provide a description of the function:def data(self): if self.is_obsolete(): data = self.get_data() for datum in data: if 'published_parsed' in datum: datum['published_parsed'] = \ self.parse_time(datum['published_parsed']) try: dumped_data = json.dumps(data) except: self.update_cache(data) else: self.update_cache(dumped_data) return data try: return json.loads(self.cache_data) except: return self.cache_data return self.get_data()
[ "load and cache data in json format\n " ]
Please provide a description of the function:def get_loaded_modules(modules): '''load modules and order it by ordering key''' _modules = [] for mod in modules: mod_cfg = get_conf_from_module(mod) _modules.append((mod, mod_cfg,)) _modules = sorted(_modules, key=lambda m: m[1].get('ordering')) return _modules
[]
Please provide a description of the function:def merge(a, b): if isinstance(a, CONFIG_VALID) \ and isinstance(b, CONFIG_VALID): # dict update if isinstance(a, dict) and isinstance(b, dict): a.update(b) return a # list update _a = list(a) for x in list(b): if x not in _a: _a.append(x) return _a if a and b: raise Exception("Cannot merge") raise NotImplementedError
[ "return merged tuples or lists without duplicates\n note: ensure if admin theme is before admin\n " ]
Please provide a description of the function:def _is_leonardo_module(whatever): '''check if is leonardo module''' # check if is python module if hasattr(whatever, 'default') \ or hasattr(whatever, 'leonardo_module_conf'): return True # check if is python object for key in dir(whatever): if 'LEONARDO' in key: return True
[]
Please provide a description of the function:def extract_conf_from(mod, conf=ModuleConfig(CONF_SPEC), depth=0, max_depth=2): # extract config keys from module or object for key, default_value in six.iteritems(conf): conf[key] = _get_key_from_module(mod, key, default_value) # support for recursive dependecies try: filtered_apps = [app for app in conf['apps'] if app not in BLACKLIST] except TypeError: pass except Exception as e: warnings.warn('Error %s during loading %s' % (e, conf['apps'])) for app in filtered_apps: try: app_module = import_module(app) if app_module != mod: app_module = _get_correct_module(app_module) if depth < max_depth: mod_conf = extract_conf_from(app_module, depth=depth+1) for k, v in six.iteritems(mod_conf): # prevent config duplicity # skip config merge if k == 'config': continue if isinstance(v, dict): conf[k].update(v) elif isinstance(v, (list, tuple)): conf[k] = merge(conf[k], v) except Exception as e: pass # swallow, but maybe log for info what happens return conf
[ "recursively extract keys from module or object\n by passed config scheme\n " ]
Please provide a description of the function:def _get_correct_module(mod): module_location = getattr( mod, 'leonardo_module_conf', getattr(mod, "LEONARDO_MODULE_CONF", None)) if module_location: mod = import_module(module_location) elif hasattr(mod, 'default_app_config'): # use django behavior mod_path, _, cls_name = mod.default_app_config.rpartition('.') _mod = import_module(mod_path) config_class = getattr(_mod, cls_name) # check if is leonardo config compliant if _is_leonardo_module(config_class): mod = config_class return mod
[ "returns imported module\n check if is ``leonardo_module_conf`` specified and then import them\n " ]
Please provide a description of the function:def get_conf_from_module(mod): conf = ModuleConfig(CONF_SPEC) # get imported module mod = _get_correct_module(mod) conf.set_module(mod) # extarct from default object or from module if hasattr(mod, 'default'): default = mod.default conf = extract_conf_from(default, conf) else: conf = extract_conf_from(mod, conf) return conf
[ "return configuration from module with defaults no worry about None type\n\n " ]
Please provide a description of the function:def get_anonymous_request(leonardo_page): request_factory = RequestFactory() request = request_factory.get( leonardo_page.get_absolute_url(), data={}) request.feincms_page = request.leonardo_page = leonardo_page request.frontend_editing = False request.user = AnonymousUser() if not hasattr(request, '_feincms_extra_context'): request._feincms_extra_context = {} request.path = leonardo_page.get_absolute_url() request.frontend_editing = False leonardo_page.run_request_processors(request) request.LEONARDO_CONFIG = ContextConfig(request) handler = BaseHandler() handler.load_middleware() # Apply request middleware for middleware_method in handler._request_middleware: try: middleware_method(request) except: pass # call processors for fn in reversed(list(leonardo_page.request_processors.values())): fn(leonardo_page, request) return request
[ "returns inicialized request\n " ]
Please provide a description of the function:def webfont_cookie(request): '''Adds WEBFONT Flag to the context''' if hasattr(request, 'COOKIES') and request.COOKIES.get(WEBFONT_COOKIE_NAME, None): return { WEBFONT_COOKIE_NAME.upper(): True } return { WEBFONT_COOKIE_NAME.upper(): False }
[]
Please provide a description of the function:def debug(request, message, extra_tags='', fail_silently=False, async=False): if ASYNC and async: messages.debug(_get_user(request), message) else: add_message(request, constants.DEBUG, message, extra_tags=extra_tags, fail_silently=fail_silently)
[ "Adds a message with the ``DEBUG`` level." ]
Please provide a description of the function:def info(request, message, extra_tags='', fail_silently=False, async=False): if ASYNC and async: messages.info(_get_user(request), message) else: add_message(request, constants.INFO, message, extra_tags=extra_tags, fail_silently=fail_silently)
[ "Adds a message with the ``INFO`` level." ]
Please provide a description of the function:def success(request, message, extra_tags='', fail_silently=False, async=False): if ASYNC and async: messages.success(_get_user(request), message) else: add_message(request, constants.SUCCESS, message, extra_tags=extra_tags, fail_silently=fail_silently)
[ "Adds a message with the ``SUCCESS`` level." ]
Please provide a description of the function:def warning(request, message, extra_tags='', fail_silently=False, async=False): if ASYNC and async: messages.debug(_get_user(request), message) else: add_message(request, constants.WARNING, message, extra_tags=extra_tags, fail_silently=fail_silently)
[ "Adds a message with the ``WARNING`` level." ]
Please provide a description of the function:def error(request, message, extra_tags='', fail_silently=False, async=False): if ASYNC and async: messages.debug(_get_user(request), message) else: add_message(request, constants.ERROR, message, extra_tags=extra_tags, fail_silently=fail_silently)
[ "Adds a message with the ``ERROR`` level." ]
Please provide a description of the function:def get_all_widget_classes(): from leonardo.module.web.models import Widget _widgets = getattr(settings, 'WIDGETS', Widget.__subclasses__()) widgets = [] if isinstance(_widgets, dict): for group, widget_cls in six.iteritems(_widgets): widgets.extend(widget_cls) elif isinstance(_widgets, list): widgets = _widgets return load_widget_classes(widgets)
[ "returns collected Leonardo Widgets\n\n if not declared in settings is used __subclasses__\n which not supports widget subclassing\n\n " ]
Please provide a description of the function:def get_grouped_widgets(feincms_object, request=None): '''returns tuple(choices, grouped, ungrouped) requires feincms_object for getting content types request optionaly for checking permissions, but not required grouped = {'web': (id, label, icon)} ''' grouped = {} ungrouped = [] choices = [] for ct in feincms_object._feincms_content_types: # Skip cts that we shouldn't be adding anyway opts = ct._meta # check permissions if request and request.user: from django.contrib.auth import get_permission_codename perm = opts.app_label + "." + \ get_permission_codename('add', opts) if not request.user.has_perm(perm): continue ct_info = ('.'.join([ct._meta.app_label, ct.__name__.lower()]), ct._meta.verbose_name, ct.get_widget_icon) if hasattr(ct, 'optgroup'): if ct.optgroup in grouped: grouped[ct.optgroup].append(ct_info) else: grouped[ct.optgroup] = [ct_info] else: ungrouped.append(ct_info) choices.append(ct_info) return choices, grouped, ungrouped
[]
Please provide a description of the function:def render_region(widget=None, request=None, view=None, page=None, region=None): # change the request if not isinstance(request, dict): request.query_string = None request.method = "GET" if not hasattr(request, '_feincms_extra_context'): request._feincms_extra_context = {} leonardo_page = widget.parent if widget else page render_region = widget.region if widget else region # call processors for fn in reversed(list(leonardo_page.request_processors.values())): try: r = fn(leonardo_page, request) except: pass contents = {} for content in leonardo_page.content.all_of_type(tuple( leonardo_page._feincms_content_types_with_process)): try: r = content.process(request, view=view) except: pass else: # this is HttpResponse object or string if not isinstance(r, six.string_types): r.render() contents[content.fe_identifier] = getattr(r, 'content', r) else: contents[content.fe_identifier] = r from leonardo.templatetags.leonardo_tags import _render_content region_content = ''.join( contents[content.fe_identifier] if content.fe_identifier in contents else _render_content( content, request=request, context={}) for content in getattr(leonardo_page.content, render_region)) return region_content
[ "returns rendered content\n this is not too clear and little tricky,\n because external apps needs calling process method\n " ]
Please provide a description of the function:def handle_dimensions(self, obj): from .tables import WidgetDimensionFormset from ..models import WidgetDimension formset = WidgetDimensionFormset( self.request.POST, prefix='dimensions') if formset.is_valid(): formset.save() else: for form in formset.forms: if form.is_valid(): if 'id' in form.cleaned_data: form.save() else: # little ugly data = form.cleaned_data data['widget_type'] = \ ContentType.objects.get_for_model(obj) data['widget_id'] = obj.id data.pop('DELETE', None) wd = WidgetDimension(**data) # do not update widget view wd.update_view = False wd.save() if formset.is_valid(): # delete objects for obj in formset.deleted_objects: if obj.id != None: obj.delete() return True
[ "save dimensions\n " ]
Please provide a description of the function:def get_form(self, form_class): if not hasattr(self, '_form'): kwargs = self.get_form_kwargs() self._form = form_class(**kwargs) return self._form
[ "Returns an instance of the form to be used in this view." ]
Please provide a description of the function:def get_form(self, form_class): kwargs = self.kwargs kwargs.update(self.get_form_kwargs()) kwargs.update({ 'request': self.request, 'next_view': WidgetCreateView }) return form_class(**kwargs)
[ "Returns an instance of the form to be used in this view." ]
Please provide a description of the function:def get_form(self, form_class): if not hasattr(self, '_form'): kwargs = self.get_form_kwargs() self._form = form_class(instance=self.object, **kwargs) return self._form
[ "Returns an instance of the form to be used in this view." ]
Please provide a description of the function:def get_edit_handler(self): '''TODO: Fix add-to-field''' # just a flag self.generic = 'false' return ''' <span class="input-group-btn"> <a href="#" id="item-edit-%(id)s" data-add-to-field="id_file" class="btn btn-default disabled"><span class="fa fa-pencil"></span></a></span> <script> if ($('*[data-add-item-url="%(url)s"]').val()) { $('#item-edit-%(id)s').removeClass('disabled'); } $('*[data-add-item-url="%(url)s"]').on('change', function (e) { if ($('*[data-add-item-url="%(url)s"]').val()) { $('#item-edit-%(id)s').removeClass('disabled'); } else { $('#item-edit-%(id)s').addClass('disabled'); } }); $("#item-edit-%(id)s").click(function() { var generic = %(generic)s; var ajax_opts = {}; var id = $('*[data-add-item-url="%(url)s"]').val(); if (generic) { ajax_opts = { url: "/widget/js-reverse/", method: 'POST', data: { viewname: '%(update_viewname)s', kwargs: JSON.stringify({ cls_name: '%(cls_name)s', id: id, form_cls: '%(form_cls)s' }) } }; } else { ajax_opts = { url: "/widget/js-reverse/", method: 'POST', data: { viewname: '%(update_viewname)s', args: JSON.stringify({id: id}) } }; } $.ajax(ajax_opts) .done(function( data ) { horizon.modals._request = $.ajax(data.url, { beforeSend: function () { horizon.modals.modal_spinner(gettext("Loading")); }, complete: function () { // Clear the global storage; horizon.modals._request = null; horizon.modals.spinner.modal('hide'); }, error: function(jqXHR, status, errorThrown) { if (jqXHR.status === 401){ var redir_url = jqXHR.getResponseHeader("X-Horizon-Location"); if (redir_url){ location.href = redir_url; } else { location.reload(true); } } else { if (!horizon.ajax.get_messages(jqXHR)) { // Generic error handler. Really generic. horizon.alert("danger", gettext( "An error occurred. Please try again later.")); } } }, success: function (data, textStatus, jqXHR) { var update_field_id = 'data-add-to-field', modal, form; modal = horizon.modals.success( data, textStatus, jqXHR); if (update_field_id) { form = modal.find("form"); if (form.length) { form.attr("data-add-to-field", update_field_id); } } } }); }); }); </script> ''' % {'update_viewname': self.get_update_view_name(), 'cls_name': self.get_cls_name(), 'url': self.get_add_item_url(), 'form_cls': self.get_form_cls(), 'id': self.__hash__(), 'generic': self.generic}
[]
Please provide a description of the function:def get_feincms_inlines(self, model, request): model._needs_content_types() inlines = [] for content_type in model._feincms_content_types: if not self.can_add_content(request, content_type): continue attrs = { '__module__': model.__module__, 'model': content_type, } if hasattr(content_type, 'feincms_item_editor_inline'): inline = content_type.feincms_item_editor_inline attrs['form'] = inline.form #if hasattr(content_type, 'feincms_item_editor_form'): # warnings.warn( # 'feincms_item_editor_form on %s is ignored because ' # 'feincms_item_editor_inline is set too' % content_type, # RuntimeWarning) else: inline = FeinCMSInline attrs['form'] = getattr( content_type, 'feincms_item_editor_form', inline.form) name = '%sFeinCMSInline' % content_type.__name__ # TODO: We generate a new class every time. Is that really wanted? inline_class = type(str(name), (inline,), attrs) inlines.append(inline_class) return inlines
[ " Generate genuine django inlines for registered content types. " ]
Please provide a description of the function:def get_changeform_initial_data(self, request): '''Copy initial data from parent''' initial = super(PageAdmin, self).get_changeform_initial_data(request) if ('translation_of' in request.GET): original = self.model._tree_manager.get( pk=request.GET.get('translation_of')) initial['layout'] = original.layout initial['theme'] = original.theme initial['color_scheme'] = original.color_scheme # optionaly translate title and make slug old_lang = translation.get_language() translation.activate(request.GET.get('language')) title = _(original.title) if title != original.title: initial['title'] = title initial['slug'] = slugify(title) translation.activate(old_lang) return initial
[]
Please provide a description of the function:def install_package(package, upgrade=True, target=None): # Not using 'import pip; pip.main([])' because it breaks the logger with INSTALL_LOCK: if check_package_exists(package, target): return True _LOGGER.info('Attempting install of %s', package) args = [sys.executable, '-m', 'pip', 'install', '--quiet', package] if upgrade: args.append('--upgrade') if target: args += ['--target', os.path.abspath(target)] try: return subprocess.call(args) == 0 except subprocess.SubprocessError: _LOGGER.exception('Unable to install pacakge %s', package) return False
[ "Install a package on PyPi. Accepts pip compatible package strings.\n\n Return boolean if install successful.\n " ]
Please provide a description of the function:def check_package_exists(package, lib_dir): try: req = pkg_resources.Requirement.parse(package) except ValueError: # This is a zip file req = pkg_resources.Requirement.parse(urlparse(package).fragment) # Check packages from lib dir if lib_dir is not None: if any(dist in req for dist in pkg_resources.find_distributions(lib_dir)): return True # Check packages from global + virtual environment # pylint: disable=not-an-iterable return any(dist in req for dist in pkg_resources.working_set)
[ "Check if a package is installed globally or in lib_dir.\n\n Returns True when the requirement is met.\n Returns False when the package is not installed or doesn't meet req.\n " ]
Please provide a description of the function:def render_widget(self, request, widget_id): '''Returns rendered widget in JSON response''' widget = get_widget_from_id(widget_id) response = widget.render(**{'request': request}) return JsonResponse({'result': response, 'id': widget_id})
[]
Please provide a description of the function:def render_region(self, request): '''Returns rendered region in JSON response''' page = self.get_object() try: region = request.POST['region'] except KeyError: region = request.GET['region'] request.query_string = None from leonardo.utils.widgets import render_region result = render_region(page=page, request=request, region=region) return JsonResponse({'result': result, 'region': region})
[]
Please provide a description of the function:def handle_ajax_method(self, request, method): response = {} def get_param(request, name): try: return request.POST[name] except KeyError: return request.GET.get(name, None) widget_id = get_param(request, "widget_id") class_name = get_param(request, "class_name") if method in 'widget_content': return self.render_widget(request, widget_id) if method == 'region': return self.render_region(request) # handle methods called directly on widget if widget_id: widget = get_widget_from_id(widget_id) try: func = getattr(widget, method) except AttributeError: response["exception"] = "%s method is not implmented on %s" % ( method, widget) else: response["result"] = func(request) elif class_name: # handle calling classmethod without instance try: cls = get_model(*class_name.split('.')) except Exception as e: response["exception"] = str(e) return JsonResponse(data=response) if method == "render_preview": # TODO: i think that we need only simple form # for loading relations but maybe this would be need it # custom_form_cls = getattr( # cls, 'feincms_item_editor_form', None) # if custom_form_cls: # FormCls = modelform_factory(cls, form=custom_form_cls, # exclude=('pk', 'id')) FormCls = modelform_factory(cls, exclude=('pk', 'id')) form = FormCls(request.POST) if form.is_valid(): widget = cls(**form.cleaned_data) request.frontend_editing = False try: content = widget.render(**{'request': request}) except Exception as e: response['result'] = widget.handle_exception(request, e) else: response['result'] = content response['id'] = widget_id else: response['result'] = form.errors response['id'] = widget_id else: # standard method try: func = getattr(cls, method) except Exception as e: response["exception"] = str(e) else: response["result"] = func(request) return JsonResponse(data=response)
[ "handle ajax methods and return serialized reponse\n in the default state allows only authentificated users\n\n - Depends on method parameter render whole region or single widget\n\n - If widget_id is present then try to load this widget\n and call method on them\n\n - If class_name is present then try to load class\n and then call static method on this class\n\n - If class_name is present then try to load class\n and if method_name == render_preview then\n render widget preview without instance\n\n " ]
Please provide a description of the function:def post_process_fieldsets(context, fieldset): # abort if fieldset is customized if fieldset.model_admin.fieldsets: return fieldset fields_to_include = set(fieldset.form.fields.keys()) for f in ('id', 'DELETE', 'ORDER'): fields_to_include.discard(f) def _filter_recursive(fields): ret = [] for f in fields: if isinstance(f, (list, tuple)): # Several fields on one line sub = _filter_recursive(f) # Only add if there's at least one field left if sub: ret.append(sub) elif f in fields_to_include: ret.append(f) fields_to_include.discard(f) return ret new_fields = _filter_recursive(fieldset.fields) # Add all other fields (ApplicationContent's admin_fields) to # the end of the fieldset for f in fields_to_include: new_fields.append(f) if context.get('request'): new_fields.extend(list( fieldset.model_admin.get_readonly_fields( context.get('request'), context.get('original'), ) )) fieldset.fields = new_fields return ''
[ "\n Removes a few fields from FeinCMS admin inlines, those being\n ``id``, ``DELETE`` and ``ORDER`` currently.\n Additionally, it ensures that dynamically added fields (i.e.\n ``ApplicationContent``'s ``admin_fields`` option) are shown.\n " ]
Please provide a description of the function:def add_bootstrap_class(field): if not isinstance(field.field.widget, ( django.forms.widgets.CheckboxInput, django.forms.widgets.CheckboxSelectMultiple, django.forms.widgets.RadioSelect, django.forms.widgets.FileInput, str )): field_classes = set(field.field.widget.attrs.get('class', '').split()) field_classes.add('form-control') field.field.widget.attrs['class'] = ' '.join(field_classes) return field
[ "Add a \"form-control\" CSS class to the field's widget.\n\n This is so that Bootstrap styles it properly.\n " ]
Please provide a description of the function:def ajax_upload(self, request, folder_id=None): mimetype = "application/json" if request.is_ajax() else "text/html" content_type_key = 'content_type' response_params = {content_type_key: mimetype} folder = None if folder_id: try: # Get folder folder = Folder.objects.get(pk=folder_id) except Folder.DoesNotExist: return HttpResponse(json.dumps({'error': NO_FOLDER_ERROR}), **response_params) # check permissions if folder and not folder.has_add_children_permission(request): return HttpResponse( json.dumps({'error': NO_PERMISSIONS_FOR_FOLDER}), **response_params) try: if len(request.FILES) == 1: # dont check if request is ajax or not, just grab the file upload, filename, is_raw = handle_request_files_upload(request) else: # else process the request as usual upload, filename, is_raw = handle_upload(request) # Get clipboad # TODO: Deprecated/refactor # clipboard = Clipboard.objects.get_or_create(user=request.user)[0] # find the file type for filer_class in media_settings.MEDIA_FILE_MODELS: FileSubClass = load_object(filer_class) # TODO: What if there are more than one that qualify? if FileSubClass.matches_file_type(filename, upload, request): FileForm = modelform_factory( model=FileSubClass, fields=('original_filename', 'owner', 'file') ) break uploadform = FileForm({'original_filename': filename, 'owner': request.user.pk}, {'file': upload}) if uploadform.is_valid(): file_obj = uploadform.save(commit=False) # Enforce the FILER_IS_PUBLIC_DEFAULT file_obj.is_public = settings.MEDIA_IS_PUBLIC_DEFAULT file_obj.folder = folder file_obj.save() # TODO: Deprecated/refactor # clipboard_item = ClipboardItem( # clipboard=clipboard, file=file_obj) # clipboard_item.save() json_response = { 'thumbnail': file_obj.icons['32'], 'alt_text': '', 'label': str(file_obj), 'file_id': file_obj.pk, } return HttpResponse(json.dumps(json_response), **response_params) else: form_errors = '; '.join(['%s: %s' % ( field, ', '.join(errors)) for field, errors in list(uploadform.errors.items()) ]) raise UploadException( "AJAX request not valid: form invalid '%s'" % (form_errors,)) except UploadException as e: return HttpResponse(json.dumps({'error': str(e)}), **response_params)
[ "\n receives an upload from the uploader. Receives only one file at the time.\n " ]
Please provide a description of the function:def set_options(self, **options): self.interactive = False self.verbosity = options['verbosity'] self.symlink = "" self.clear = False ignore_patterns = [] self.ignore_patterns = list(set(ignore_patterns)) self.page_themes_updated = 0 self.skins_updated = 0
[ "\n Set instance variables based on an options dict\n " ]
Please provide a description of the function:def collect(self): self.ignore_patterns = [ '*.png', '*.jpg', '*.js', '*.gif', '*.ttf', '*.md', '*.rst', '*.svg'] page_themes = PageTheme.objects.all() for finder in get_finders(): for path, storage in finder.list(self.ignore_patterns): for t in page_themes: static_path = 'themes/{0}'.format(t.name.split('/')[-1]) if static_path in path: try: page_theme = PageTheme.objects.get(id=t.id) except PageTheme.DoesNotExist: raise Exception( "Run sync_themes before this command") except Exception as e: self.stdout.write( "Cannot load {} into database original error: {}".format(t, e)) # find and load skins skins_path = os.path.join( storage.path('/'.join(path.split('/')[0:-1]))) for dirpath, skins, filenames in os.walk(skins_path): for skin in [s for s in skins if s not in ['fonts']]: for skin_dirpath, skins, filenames in os.walk(os.path.join(dirpath, skin)): skin, created = PageColorScheme.objects.get_or_create( theme=page_theme, label=skin, name=skin.title()) for f in filenames: if 'styles' in f: with codecs.open(os.path.join(skin_dirpath, f)) as style_file: skin.styles = style_file.read() elif 'variables' in f: with codecs.open(os.path.join(skin_dirpath, f)) as variables_file: skin.variables = variables_file.read() skin.save() self.skins_updated += 1 self.page_themes_updated += len(page_themes)
[ "\n Load and save ``PageColorScheme`` for every ``PageTheme``\n\n .. code-block:: bash\n\n static/themes/bootswatch/united/variables.scss\n static/themes/bootswatch/united/styles.scss\n\n " ]
Please provide a description of the function:def dbtemplate_save(sender, instance, created, **kwargs): if created: if 'widget' in instance.name: name = instance.name.split('/')[-1] kwargs = { 'name': name.split('.')[0], 'label': name.split('.')[0].capitalize(), 'template': instance, } if 'base/widget' in instance.name: from leonardo.module.web.models import WidgetBaseTheme theme_cls = WidgetBaseTheme else: from leonardo.module.web.models import WidgetContentTheme theme_cls = WidgetContentTheme from leonardo.utils.widgets import find_widget_class w_cls_name = instance.name.split('/')[-2] w_cls = find_widget_class(w_cls_name) if w_cls is None: raise Exception('widget class for %s not found' % w_cls_name) kwargs['widget_class'] = w_cls.__name__ theme_cls(**kwargs).save() if 'base/page' in instance.name: from leonardo.module.web.models import PageTheme page_theme = PageTheme() page_theme.label = '{} layout'.format( instance.name.split("/")[-1].split('.')[0].title()) page_theme.name = instance.name.split("/")[-1] page_theme.template = instance page_theme.save()
[ "create widget/page content/base theme from given db template::\n /widget/icon/my_awesome.html\n /base/widget/my_new_widget_box.html\n /base/page/my_new_page_layout.html\n " ]
Please provide a description of the function:def has_generic_permission(self, request, permission_type): user = request.user if not user.is_authenticated(): return False elif user.is_superuser: return True elif user == self.owner: return True elif self.folder: return self.folder.has_generic_permission(request, permission_type) else: return False
[ "\n Return true if the current user has permission on this\n image. Return the string 'ALL' if the user has all rights.\n " ]
Please provide a description of the function:def decode(self, packet): ssu=packet.retrieve("Complete uuids") found=False for x in ssu: if EDDY_UUID in x: found=True break if not found: return None found=False adv=packet.retrieve("Advertised Data") for x in adv: luuid=x.retrieve("Service Data uuid") for uuid in luuid: if EDDY_UUID == uuid: found=x break if found: break if not found: return None try: top=found.retrieve("Adv Payload")[0] except: return None #Rebuild that part of the structure found.payload.remove(top) #Now decode result={} data=top.val etype = aios.EnumByte("type",self.type.val,{ESType.uid.value:"Eddystone-UID", ESType.url.value:"Eddystone-URL", ESType.tlm.value:"Eddystone-TLM", ESType.eid.value:"Eddystone-EID"}) data=etype.decode(data) found.payload.append(etype) if etype.val== ESType.uid.value: power=aios.IntByte("tx_power") data=power.decode(data) found.payload.append(power) result["tx_power"]=power.val nspace=aios.Itself("namespace") xx=nspace.decode(data[:10]) #According to https://github.com/google/eddystone/tree/master/eddystone-uid data=data[10:] found.payload.append(nspace) result["name space"]=nspace.val nspace=aios.Itself("instance") xx=nspace.decode(data[:6]) #According to https://github.com/google/eddystone/tree/master/eddystone-uid data=data[6:] found.payload.append(nspace) result["instance"]=nspace.val elif etype.val== ESType.url.value: power=aios.IntByte("tx_power") data=power.decode(data) found.payload.append(power) result["tx_power"]=power.val url=aios.EnumByte("type",0,{0x00:"http://www.",0x01:"https://www.",0x02:"http://",0x03:"https://"}) data=url.decode(data) result["url"]=url.strval for x in data: if bytes([x]) == b"\x00": result["url"]+=".com/" elif bytes([x]) == b"\x01": result["url"]+=".org/" elif bytes([x]) == b"\x02": result["url"]+=".edu/" elif bytes([x]) == b"\x03": result["url"]+=".net/" elif bytes([x]) == b"\x04": result["url"]+=".info/" elif bytes([x]) == b"\x05": result["url"]+=".biz/" elif bytes([x]) == b"\x06": result["url"]+=".gov/" elif bytes([x]) == b"\x07": result["url"]+=".com" elif bytes([x]) == b"\x08": result["url"]+=".org" elif bytes([x]) == b"\x09": result["url"]+=".edu" elif bytes([x]) == b"\x10": result["url"]+=".net" elif bytes([x]) == b"\x11": result["url"]+=".info" elif bytes([x]) == b"\x12": result["url"]+=".biz" elif bytes([x]) == b"\x13": result["url"]+=".gov" else: result["url"]+=chr(x) #x.decode("ascii") #Yep ASCII only url=aios.String("url") url.decode(result["url"]) found.payload.append(url) elif etype.val== ESType.tlm.value: myinfo=aios.IntByte("version") data=myinfo.decode(data) found.payload.append(myinfo) myinfo=aios.ShortInt("battery") data=myinfo.decode(data) result["battery"]=myinfo.val found.payload.append(myinfo) myinfo=aios.Float88("temperature") data=myinfo.decode(data) found.payload.append(myinfo) result["temperature"]=myinfo.val myinfo=aios.LongInt("pdu count") data=myinfo.decode(data) found.payload.append(myinfo) result["pdu count"]=myinfo.val myinfo=aios.LongInt("uptime") data=myinfo.decode(data) found.payload.append(myinfo) result["uptime"]=myinfo.val*100 #in msecs return result #elif etype.val== ESType.tlm.eid: else: result["data"]=data xx=Itself("data") xx.decode(data) found.payload.append(xx) rssi=packet.retrieve("rssi") if rssi: result["rssi"]=rssi[-1].val mac=packet.retrieve("peer") if mac: result["mac address"]=mac[-1].val return result
[ "Check a parsed packet and figure out if it is an Eddystone Beacon.\n If it is , return the relevant data as a dictionary.\n\n Return None, it is not an Eddystone Beacon advertising packet" ]
Please provide a description of the function:def get_directories(self, request): queryset = self.folder.media_folder_children.all().order_by(*config.MEDIA_FOLDERS_ORDER_BY.split(",")) paginator = Paginator(queryset, self.objects_per_page) page = request.GET.get('page', None) try: object_list = paginator.page(page) except PageNotAnInteger: if page == "all": object_list = queryset else: object_list = paginator.page(1) except EmptyPage: object_list = paginator.page(paginator.num_pages) return object_list
[ "Return directories\n " ]
Please provide a description of the function:def get_template_data(self, request, *args, **kwargs): '''Add image dimensions''' # little tricky with vertical centering dimension = int(self.get_size().split('x')[0]) data = {} if dimension <= 356: data['image_dimension'] = "row-md-13" if self.get_template_name().name.split("/")[-1] == "directories.html": data['directories'] = self.get_directories(request) return data
[]
Please provide a description of the function:def staff_member(view_func): @functools.wraps(view_func, assigned=available_attrs(view_func)) def dec(request, *args, **kwargs): if request.user.is_staff: return view_func(request, *args, **kwargs) raise PermissionDenied(_("You haven't permissions to do this action.")) return dec
[ "Performs user authentication check.\n\n Similar to Django's `login_required` decorator, except that this throws\n :exc:`~leonardo.exceptions.NotAuthenticated` exception if the user is not\n signed-in.\n " ]
Please provide a description of the function:def _decorate_urlconf(urlpatterns, decorator=require_auth, *args, **kwargs): '''Decorate all urlpatterns by specified decorator''' if isinstance(urlpatterns, (list, tuple)): for pattern in urlpatterns: if getattr(pattern, 'callback', None): pattern._callback = decorator( pattern.callback, *args, **kwargs) if getattr(pattern, 'url_patterns', []): _decorate_urlconf( pattern.url_patterns, decorator, *args, **kwargs) else: if getattr(urlpatterns, 'callback', None): urlpatterns._callback = decorator( urlpatterns.callback, *args, **kwargs)
[]
Please provide a description of the function:def catch_result(task_func): @functools.wraps(task_func, assigned=available_attrs(task_func)) def dec(*args, **kwargs): # inicialize orig_stdout = sys.stdout sys.stdout = content = StringIO() task_response = task_func(*args, **kwargs) # catch sys.stdout = orig_stdout content.seek(0) # propagate to the response task_response['stdout'] = content.read() return task_response return dec
[ "Catch printed result from Celery Task and return it in task response\n " ]
Please provide a description of the function:def compress_monkey_patch(): from compressor.templatetags import compress as compress_tags from compressor import base as compress_base compress_base.Compressor.filter_input = filter_input compress_base.Compressor.output = output compress_base.Compressor.hunks = hunks compress_base.Compressor.precompile = precompile compress_tags.CompressorMixin.render_compressed = render_compressed from django_pyscss import compressor as pyscss_compressor pyscss_compressor.DjangoScssFilter.input = input
[ "patch all compress\n\n we need access to variables from widget scss\n\n for example we have::\n\n /themes/bootswatch/cyborg/_variables\n\n but only if is cyborg active for this reasone we need\n dynamically append import to every scss file\n\n " ]
Please provide a description of the function:def input(self, **kwargs): with_variables = None context = kwargs.get('context', {}) if context.get('leonardo_page', None): try: context['leonardo_page']['theme'] context['leonardo_page']['color_scheme'] except Exception as e: LOG.exception(str(e)) else: with_variables = .format( context['leonardo_page']['theme']['name'], context['leonardo_page']['color_scheme']['name'], self.content) return self.compiler.compile_string( with_variables or self.content, filename=self.filename)
[ "main override which append variables import to all scss content\n ", "\n @import \"/themes/{}/{}/_variables\";\n {}\n " ]
Please provide a description of the function:def hunks(self, forced=False, context=None): enabled = settings.COMPRESS_ENABLED or forced for kind, value, basename, elem in self.split_contents(): precompiled = False attribs = self.parser.elem_attribs(elem) charset = attribs.get("charset", self.charset) options = { 'method': METHOD_INPUT, 'elem': elem, 'kind': kind, 'basename': basename, 'charset': charset, 'context': context } if kind == SOURCE_FILE: options = dict(options, filename=value) value = self.get_filecontent(value, charset) if self.precompiler_mimetypes: precompiled, value = self.precompile(value, **options) if enabled: yield self.filter(value, self.cached_filters, **options) elif precompiled: # since precompiling moves files around, it breaks url() # statements in css files. therefore we run the absolute filter # on precompiled css files even if compression is disabled. if CssAbsoluteFilter in self.cached_filters: value = self.filter(value, [CssAbsoluteFilter], **options) yield self.handle_output(kind, value, forced=True, basename=basename) else: yield self.parser.elem_str(elem)
[ "\n The heart of content parsing, iterates over the\n list of split contents and looks at its kind\n to decide what to do with it. Should yield a\n bunch of precompiled and/or rendered hunks.\n " ]
Please provide a description of the function:def output(self, mode='file', forced=False, context=None): output = '\n'.join(self.filter_input(forced, context=context)) if not output: return '' if settings.COMPRESS_ENABLED or forced: filtered_output = self.filter_output(output) return self.handle_output(mode, filtered_output, forced) return output
[ "\n The general output method, override in subclass if you need to do\n any custom modification. Calls other mode specific methods or simply\n returns the content directly.\n " ]
Please provide a description of the function:def filter_input(self, forced=False, context=None): content = [] for hunk in self.hunks(forced, context=context): content.append(hunk) return content
[ "\n Passes each hunk (file or code) to the 'input' methods\n of the compressor filters.\n " ]
Please provide a description of the function:def precompile(self, content, kind=None, elem=None, filename=None, charset=None, **kwargs): if not kind: return False, content attrs = self.parser.elem_attribs(elem) mimetype = attrs.get("type", None) if mimetype is None: return False, content filter_or_command = self.precompiler_mimetypes.get(mimetype) if filter_or_command is None: if mimetype in ("text/css", "text/javascript"): return False, content raise CompressorError("Couldn't find any precompiler in " "COMPRESS_PRECOMPILERS setting for " "mimetype '%s'." % mimetype) mod_name, cls_name = get_mod_func(filter_or_command) try: mod = import_module(mod_name) except (ImportError, TypeError): filter = CachedCompilerFilter( content=content, filter_type=self.type, filename=filename, charset=charset, command=filter_or_command, mimetype=mimetype) return True, filter.input(**kwargs) try: precompiler_class = getattr(mod, cls_name) except AttributeError: raise FilterDoesNotExist('Could not find "%s".' % filter_or_command) filter = precompiler_class( content, attrs=attrs, filter_type=self.type, charset=charset, filename=filename, **kwargs) return True, filter.input(**kwargs)
[ "\n Processes file using a pre compiler.\n This is the place where files like coffee script are processed.\n " ]
Please provide a description of the function:def decode(self,data): self.val=':'.join("%02x" % x for x in reversed(data[:6])) return data[6:]
[ "Decode the MAC address from a byte array.\n\n This will take the first 6 bytes from data and transform them into a MAC address\n string representation. This will be assigned to the attribute \"val\". It then returns\n the data stream minus the bytes consumed\n\n :param data: The data stream containing the value to decode at its head\n :type data: bytes\n :returns: The datastream minus the bytes consumed\n :rtype: bytes\n " ]
Please provide a description of the function:def retrieve(self,aclass): resu=[] for x in self.payload: try: if isinstance(aclass,str): if x.name == aclass: resu.append(x) else: if isinstance(x,aclass): resu.append(x) resu+=x.retrieve(aclass) except: pass return resu
[ "Look for a specifc class/name in the packet" ]
Please provide a description of the function:def send_scan_request(self): '''Sending LE scan request''' command=HCI_Cmd_LE_Scan_Enable(True,False) self.transport.write(command.encode())
[]
Please provide a description of the function:def stop_scan_request(self): '''Sending LE scan request''' command=HCI_Cmd_LE_Scan_Enable(False,False) self.transport.write(command.encode())
[]
Please provide a description of the function:def thumbnail(parser, token): ''' This template tag supports both syntax for declare thumbanil in template ''' thumb = None if SORL: try: thumb = sorl_thumb(parser, token) except Exception: thumb = False if EASY and not thumb: thumb = easy_thumb(parser, token) return thumb
[]
Please provide a description of the function:def register_widgets(): # special case # register external apps Page.create_content_type( ApplicationWidget, APPLICATIONS=settings.APPLICATION_CHOICES) for _optgroup, _widgets in six.iteritems(settings.WIDGETS): optgroup = _optgroup if _optgroup != 'ungrouped' else None for widget in _widgets: kwargs = {'optgroup': optgroup} # load class from strings if isinstance(widget, six.string_types): try: WidgetCls = get_class_from_string(widget) except: exc_info = sys.exc_info() raise six.reraise(*exc_info) elif isinstance(widget, tuple): try: WidgetCls = get_class_from_string(widget[0]) if len(widget) > 1: kwargs.update(widget[1]) except Exception as e: raise Exception('%s: %s' % (mod, e)) else: WidgetCls = widget Page.create_content_type( WidgetCls, **kwargs)
[ "\n Register all collected widgets from settings\n WIDGETS = [('mymodule.models.MyWidget', {'mykwargs': 'mykwarg'})]\n WIDGETS = ['mymodule.models.MyWidget', MyClass]\n " ]
Please provide a description of the function:def handle_uploaded_file(file, folder=None, is_public=True): '''handle uploaded file to folder match first media type and create media object and returns it file: File object folder: str or Folder isinstance is_public: boolean ''' _folder = None if folder and isinstance(folder, Folder): _folder = folder elif folder: _folder, folder_created = Folder.objects.get_or_create( name=folder) for cls in MEDIA_MODELS: if cls.matches_file_type(file.name): obj, created = cls.objects.get_or_create( original_filename=file.name, file=file, folder=_folder, is_public=is_public) if created: return obj return None
[]
Please provide a description of the function:def handle_uploaded_files(files, folder=None, is_public=True): '''handle uploaded files to folder files: array of File objects or single object folder: str or Folder isinstance is_public: boolean ''' results = [] for f in files: result = handle_uploaded_file(f, folder, is_public) results.append(result) return results
[]
Please provide a description of the function:def serve_protected_file(request, path): path = path.rstrip('/') try: file_obj = File.objects.get(file=path) except File.DoesNotExist: raise Http404('File not found %s' % path) if not file_obj.has_read_permission(request): if settings.DEBUG: raise PermissionDenied else: raise Http404('File not found %s' % path) return server.serve(request, file_obj=file_obj.file, save_as=False)
[ "\n Serve protected files to authenticated users with read permissions.\n " ]
Please provide a description of the function:def serve_protected_thumbnail(request, path): source_path = thumbnail_to_original_filename(path) if not source_path: raise Http404('File not found') try: file_obj = File.objects.get(file=source_path) except File.DoesNotExist: raise Http404('File not found %s' % path) if not file_obj.has_read_permission(request): if settings.DEBUG: raise PermissionDenied else: raise Http404('File not found %s' % path) try: thumbnail = ThumbnailFile(name=path, storage=file_obj.file.thumbnail_storage) return thumbnail_server.serve(request, thumbnail, save_as=False) except Exception: raise Http404('File not found %s' % path)
[ "\n Serve protected thumbnails to authenticated users.\n If the user doesn't have read permissions, redirect to a static image.\n " ]
Please provide a description of the function:def get_app_modules(self, apps): modules = getattr(self, "_modules", []) if not modules: from django.utils.module_loading import module_has_submodule # Try importing a modules from the module package package_string = '.'.join(['leonardo', 'module']) for app in apps: exc = '...' try: # check if is not full app _app = import_module(app) except Exception as e: _app = False exc = e if module_has_submodule( import_module(package_string), app) or _app: if _app: mod = _app else: mod = import_module('.{0}'.format(app), package_string) if mod: modules.append(mod) continue warnings.warn('%s was skipped because %s ' % (app, exc)) self._modules = modules return self._modules
[ "return array of imported leonardo modules for apps\n " ]
Please provide a description of the function:def urlpatterns(self): '''load and decorate urls from all modules then store it as cached property for less loading ''' if not hasattr(self, '_urlspatterns'): urlpatterns = [] # load all urls # support .urls file and urls_conf = 'elephantblog.urls' on default module # decorate all url patterns if is not explicitly excluded for mod in leonardo.modules: # TODO this not work if is_leonardo_module(mod): conf = get_conf_from_module(mod) if module_has_submodule(mod, 'urls'): urls_mod = import_module('.urls', mod.__name__) if hasattr(urls_mod, 'urlpatterns'): # if not public decorate all if conf['public']: urlpatterns += urls_mod.urlpatterns else: _decorate_urlconf(urls_mod.urlpatterns, require_auth) urlpatterns += urls_mod.urlpatterns # avoid circural dependency # TODO use our loaded modules instead this property from django.conf import settings for urls_conf, conf in six.iteritems(getattr(settings, 'MODULE_URLS', {})): # is public ? try: if conf['is_public']: urlpatterns += \ patterns('', url(r'', include(urls_conf)), ) else: _decorate_urlconf( url(r'', include(urls_conf)), require_auth) urlpatterns += patterns('', url(r'', include(urls_conf))) except Exception as e: raise Exception('raised %s during loading %s' % (str(e), urls_conf)) self._urlpatterns = urlpatterns return self._urlpatterns
[]
Please provide a description of the function:def cycle_app_reverse_cache(*args, **kwargs): value = '%07x' % (SystemRandom().randint(0, 0x10000000)) cache.set(APP_REVERSE_CACHE_GENERATION_KEY, value) return value
[ "Does not really empty the cache; instead it adds a random element to the\n cache key generation which guarantees that the cache does not yet contain\n values for all newly generated keys" ]
Please provide a description of the function:def app_reverse(viewname, urlconf=None, args=None, kwargs=None, *vargs, **vkwargs): # First parameter might be a request instead of an urlconf path, so # we'll try to be helpful and extract the current urlconf from it extra_context = getattr(urlconf, '_feincms_extra_context', {}) appconfig = extra_context.get('app_config', {}) urlconf = appconfig.get('urlconf_path', urlconf) appcontent_class = ApplicationWidget._feincms_content_models[0] cache_key = appcontent_class.app_reverse_cache_key(urlconf) url_prefix = cache.get(cache_key) if url_prefix is None: clear_script_prefix() content = appcontent_class.closest_match(urlconf) if content is not None: if urlconf in appcontent_class.ALL_APPS_CONFIG: # We have an overridden URLconf app_config = appcontent_class.ALL_APPS_CONFIG[urlconf] urlconf = app_config['config'].get('urls', urlconf) prefix = content.parent.get_absolute_url() prefix += '/' if prefix[-1] != '/' else '' url_prefix = (urlconf, prefix) cache.set(cache_key, url_prefix, timeout=APP_REVERSE_CACHE_TIMEOUT) if url_prefix: # vargs and vkwargs are used to send through additional parameters # which are uninteresting to us (such as current_app) prefix = get_script_prefix() try: set_script_prefix(url_prefix[1]) return reverse( viewname, url_prefix[0], args=args, kwargs=kwargs, *vargs, **vkwargs) finally: set_script_prefix(prefix) raise NoReverseMatch("Unable to find ApplicationContent for %(app)s" " usually it is due to the fact that you haven't mapped external application %(app)s" % { 'app': urlconf})
[ "\n Reverse URLs from application contents\n Works almost like Django's own reverse() method except that it resolves\n URLs from application contents. The second argument, ``urlconf``, has to\n correspond to the URLconf parameter passed in the ``APPLICATIONS`` list\n to ``Page.create_content_type``::\n app_reverse('mymodel-detail', 'myapp.urls', args=...)\n or\n app_reverse('mymodel-detail', 'myapp.urls', kwargs=...)\n The second argument may also be a request object if you want to reverse\n an URL belonging to the current application content.\n " ]
Please provide a description of the function:def permalink(func): def inner(*args, **kwargs): return app_reverse(*func(*args, **kwargs)) return wraps(func)(inner)
[ "\n Decorator that calls app_reverse()\n Use this instead of standard django.db.models.permalink if you want to\n integrate the model through ApplicationContent. The wrapped function\n must return 4 instead of 3 arguments::\n class MyModel(models.Model):\n @appmodels.permalink\n def get_absolute_url(self):\n return ('myapp.urls', 'model_detail', (), {'slug': self.slug})\n " ]
Please provide a description of the function:def reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None): if not urlconf: urlconf = get_urlconf() resolver = get_resolver(urlconf) args = args or [] kwargs = kwargs or {} prefix = get_script_prefix() if not isinstance(viewname, six.string_types): view = viewname else: parts = viewname.split(':') parts.reverse() view = parts[0] path = parts[1:] resolved_path = [] ns_pattern = '' while path: ns = path.pop() # Lookup the name to see if it could be an app identifier try: app_list = resolver.app_dict[ns] # Yes! Path part matches an app in the current Resolver if current_app and current_app in app_list: # If we are reversing for a particular app, # use that namespace ns = current_app elif ns not in app_list: # The name isn't shared by one of the instances # (i.e., the default) so just pick the first instance # as the default. ns = app_list[0] except KeyError: pass try: extra, resolver = resolver.namespace_dict[ns] resolved_path.append(ns) ns_pattern = ns_pattern + extra except KeyError as key: for urlconf, config in six.iteritems( ApplicationWidget._feincms_content_models[0].ALL_APPS_CONFIG): partials = viewname.split(':') app = partials[0] partials = partials[1:] # check if namespace is same as app name and try resolve if urlconf.split(".")[-1] == app: try: return app_reverse( ':'.join(partials), urlconf, args=args, kwargs=kwargs, current_app=current_app) except NoReverseMatch: pass if resolved_path: raise NoReverseMatch( "%s is not a registered namespace inside '%s'" % (key, ':'.join(resolved_path))) else: raise NoReverseMatch("%s is not a registered namespace" % key) if ns_pattern: resolver = get_ns_resolver(ns_pattern, resolver) return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
[ "monkey patched reverse\n\n path supports easy patching 3rd party urls\n if 3rd party app has namespace for example ``catalogue`` and\n you create FeinCMS plugin with same name as this namespace reverse\n returns url from ApplicationContent !\n\n " ]
Please provide a description of the function:def get_formset(self): if self.widget: queryset = self.widget.dimensions else: queryset = WidgetDimension.objects.none() if self._formset is None: self._formset = self.formset_class( self.request.POST or None, initial=self._get_formset_data(), prefix=self._meta.name, queryset=queryset) return self._formset
[ "Provide the formset corresponding to this DataTable.\n\n Use this to validate the formset and to get the submitted data back.\n " ]
Please provide a description of the function:def add_page_if_missing(request): try: page = Page.objects.for_request(request, best_match=True) return { 'leonardo_page': page, # DEPRECATED 'feincms_page': page, } except Page.DoesNotExist: return {}
[ "\n Returns ``feincms_page`` for request.\n " ]
Please provide a description of the function:def render_in_page(request, template): from leonardo.module.web.models import Page page = request.leonardo_page if hasattr( request, 'leonardo_page') else Page.objects.filter(parent=None).first() if page: try: slug = request.path_info.split("/")[-2:-1][0] except KeyError: slug = None try: body = render_to_string(template, RequestContext(request, { 'request_path': request.path, 'feincms_page': page, 'slug': slug, 'standalone': True})) response = http.HttpResponseNotFound( body, content_type=CONTENT_TYPE) except TemplateDoesNotExist: response = False return response return False
[ "return rendered template in standalone mode or ``False``\n " ]
Please provide a description of the function:def page_not_found(request, template_name='404.html'): response = render_in_page(request, template_name) if response: return response template = Template( '<h1>Not Found</h1>' '<p>The requested URL {{ request_path }} was not found on this server.</p>') body = template.render(RequestContext( request, {'request_path': request.path})) return http.HttpResponseNotFound(body, content_type=CONTENT_TYPE)
[ "\n Default 404 handler.\n\n Templates: :template:`404.html`\n Context:\n request_path\n The path of the requested URL (e.g., '/app/pages/bad_page/')\n " ]
Please provide a description of the function:def server_error(request, template_name='500.html'): response = render_in_page(request, template_name) if response: return response try: template = loader.get_template(template_name) except TemplateDoesNotExist: return http.HttpResponseServerError('<h1>Server Error (500)</h1>', content_type='text/html') return http.HttpResponseServerError(template.render(Context({})))
[ "\n 500 error handler.\n\n Templates: :template:`500.html`\n Context: None\n " ]
Please provide a description of the function:def bad_request(request, template_name='400.html'): response = render_in_page(request, template_name) if response: return response try: template = loader.get_template(template_name) except TemplateDoesNotExist: return http.HttpResponseBadRequest('<h1>Bad Request (400)</h1>', content_type='text/html') return http.HttpResponseBadRequest(template.render(Context({})))
[ "\n 400 error handler.\n\n Templates: :template:`400.html`\n Context: None\n " ]
Please provide a description of the function:def permission_denied(request, template_name='403.html'): response = render_in_page(request, template_name) if response: return response try: template = loader.get_template(template_name) except TemplateDoesNotExist: return http.HttpResponseForbidden('<h1>403 Forbidden</h1>', content_type='text/html') return http.HttpResponseForbidden(template.render(RequestContext(request)))
[ "\n Permission denied (403) handler.\n\n Templates: :template:`403.html`\n Context: None\n\n If the template does not exist, an Http403 response containing the text\n \"403 Forbidden\" (as per RFC 2616) will be returned.\n " ]
Please provide a description of the function:def process_request(self, request): # Activate timezone handling tz = request.session.get('django_timezone') if tz: timezone.activate(tz) # Check for session timeout try: timeout = settings.SESSION_TIMEOUT except AttributeError: timeout = 1800 last_activity = request.session.get('last_activity', None) timestamp = int(time.time()) request.horizon = {'dashboard': None, 'panel': None, 'async_messages': []} if not hasattr(request, "user") or not request.user.is_authenticated(): # proceed no further if the current request is already known # not to be authenticated return None if request.is_ajax(): # if the request is Ajax we do not want to proceed, as clients can # 1) create pages with constant polling, which can create race # conditions when a page navigation occurs # 2) might leave a user seemingly left logged in forever # 3) thrashes db backed session engines with tons of changes return None # If we use cookie-based sessions, check that the cookie size does not # reach the max size accepted by common web browsers. if ( settings.SESSION_ENGINE == 'django.contrib.sessions.backends.signed_cookies' ): max_cookie_size = getattr( settings, 'SESSION_COOKIE_MAX_SIZE', None) session_cookie_name = getattr( settings, 'SESSION_COOKIE_NAME', None) session_key = request.COOKIES.get(session_cookie_name) if max_cookie_size is not None and session_key is not None: cookie_size = sum(( len(key) + len(value) for key, value in six.iteritems(request.COOKIES) )) if cookie_size >= max_cookie_size: LOG.error( 'Total Cookie size for user_id: %(user_id)s is ' '%(cookie_size)sB >= %(max_cookie_size)sB. ' 'You need to configure file-based or database-backed ' 'sessions instead of cookie-based sessions: ' 'http://docs.openstack.org/developer/horizon/topics/' 'deployment.html#session-storage' % { 'user_id': request.session.get( 'user_id', 'Unknown'), 'cookie_size': cookie_size, 'max_cookie_size': max_cookie_size, } ) request.session['last_activity'] = timestamp
[ "Adds data necessary for Horizon to function to the request." ]
Please provide a description of the function:def process_response(self, request, response): if request.is_ajax() and hasattr(request, 'horizon'): queued_msgs = request.horizon['async_messages'] if type(response) == http.HttpResponseRedirect: # Drop our messages back into the session as per usual so they # don't disappear during the redirect. Not that we explicitly # use django's messages methods here. for tag, message, extra_tags in queued_msgs: getattr(django_messages, tag)(request, message, extra_tags) # if response['location'].startswith(settings.LOGOUT_URL): # redirect_response = http.HttpResponse(status=401) # # This header is used for handling the logout in JS # redirect_response['logout'] = True # if self.logout_reason is not None: # utils.add_logout_reason( # request, redirect_response, self.logout_reason) # else: redirect_response = http.HttpResponse() # Use a set while checking if we want a cookie's attributes # copied cookie_keys = set(('max_age', 'expires', 'path', 'domain', 'secure', 'httponly', 'logout_reason')) # Copy cookies from HttpResponseRedirect towards HttpResponse for cookie_name, cookie in six.iteritems(response.cookies): cookie_kwargs = dict(( (key, value) for key, value in six.iteritems(cookie) if key in cookie_keys and value )) redirect_response.set_cookie( cookie_name, cookie.value, **cookie_kwargs) redirect_response['X-Horizon-Location'] = response['location'] upload_url_key = 'X-File-Upload-URL' if upload_url_key in response: self.copy_headers(response, redirect_response, (upload_url_key, 'X-Auth-Token')) return redirect_response if queued_msgs: # TODO(gabriel): When we have an async connection to the # client (e.g. websockets) this should be pushed to the # socket queue rather than being sent via a header. # The header method has notable drawbacks (length limits, # etc.) and is not meant as a long-term solution. response['X-Horizon-Messages'] = json.dumps(queued_msgs) return response
[ "Convert HttpResponseRedirect to HttpResponse if request is via ajax\n to allow ajax request to redirect url\n " ]
Please provide a description of the function:def process_exception(self, request, exception): if isinstance(exception, (exceptions.NotAuthorized, exceptions.NotAuthenticated)): auth_url = settings.LOGIN_URL next_url = None # prevent submiting forms after login and # use http referer if request.method in ("POST", "PUT"): referrer = request.META.get('HTTP_REFERER') if referrer and is_safe_url(referrer, request.get_host()): next_url = referrer if not next_url: next_url = iri_to_uri(request.get_full_path()) if next_url != auth_url: field_name = REDIRECT_FIELD_NAME else: field_name = None login_url = request.build_absolute_uri(auth_url) response = redirect_to_login(next_url, login_url=login_url, redirect_field_name=field_name) if isinstance(exception, exceptions.NotAuthorized): logout_reason = _("Unauthorized. Please try logging in again.") utils.add_logout_reason(request, response, logout_reason) # delete messages, created in get_data() method # since we are going to redirect user to the login page response.delete_cookie('messages') if request.is_ajax(): response_401 = http.HttpResponse(status=401) response_401['X-Horizon-Location'] = response['location'] return response_401 return response # If an internal "NotFound" error gets this far, return a real 404. if isinstance(exception, exceptions.NotFound): raise http.Http404(exception) if isinstance(exception, exceptions.Http302): # TODO(gabriel): Find a way to display an appropriate message to # the user *on* the login form... return shortcuts.redirect(exception.location)
[ "Catches internal Horizon exception classes such as NotAuthorized,\n NotFound and Http302 and handles them gracefully.\n " ]
Please provide a description of the function:def canonical(request, uploaded_at, file_id): filer_file = get_object_or_404(File, pk=file_id, is_public=True) if (uploaded_at != filer_file.uploaded_at.strftime('%s') or not filer_file.file): raise Http404('No %s matches the given query.' % File._meta.object_name) return redirect(filer_file.url)
[ "\n Redirect to the current url of a public file\n " ]
Please provide a description of the function:def check_message(keywords, message): exc_type, exc_value, exc_traceback = sys.exc_info() if set(str(exc_value).split(" ")).issuperset(set(keywords)): exc_value.message = message raise
[ "Checks an exception for given keywords and raises a new ``ActionError``\n with the desired message if the keywords are found. This allows selective\n control over API error messages.\n " ]
Please provide a description of the function:def get_switched_form_field_attrs(self, prefix, input_type, name): attributes = {'class': 'switched', 'data-switch-on': prefix + 'field'} attributes['data-' + prefix + 'field-' + input_type] = name return attributes
[ "Creates attribute dicts for the switchable theme form\n " ]
Please provide a description of the function:def clean_slug(self): slug = self.cleaned_data.get('slug', None) if slug is None or len(slug) == 0 and 'title' in self.cleaned_data: slug = slugify(self.cleaned_data['title']) return slug
[ "slug title if is not provided\n " ]
Please provide a description of the function:def get_widget_from_id(id): res = id.split('-') try: model_cls = apps.get_model(res[0], res[1]) obj = model_cls.objects.get(parent=res[2], id=res[3]) except: obj = None return obj
[ "returns widget object by id\n\n example web-htmltextwidget-2-2\n " ]
Please provide a description of the function:def get_widget_class_from_id(id): res = id.split('-') try: model_cls = apps.get_model(res[1], res[2]) except: model_cls = None return model_cls
[ "returns widget class by id\n\n example web-htmltextwidget-2-2\n " ]
Please provide a description of the function:def get(self, request, *args, **kwargs): self.widget = self.get_widget_or_404() if not self.widget: LOG.warning('Select2 field was not found, check your CACHE') self.term = kwargs.get('term', request.GET.get('term', '')) self.object_list = self.get_queryset() context = self.get_context_data() label_fn = self.widget.label_from_instance if hasattr( self.widget, 'label_from_instance') else smart_text return JsonResponse({ 'results': [ { 'text': label_fn(obj), 'id': obj.pk, } for obj in context['object_list'] ], })
[ "\n Return a :class:`.django.http.JsonResponse`.\n\n PR: https://github.com/applegrew/django-select2/pull/208\n\n Example::\n\n {\n 'results': [\n {\n 'text': \"foo\",\n 'id': 123\n }\n ]\n }\n\n " ]
Please provide a description of the function:def index_queryset(self, using=None): kwargs = {"active": True} # if permissions are enabled then we want only public pages # https://github.com/leonardo-modules/leonardo-module-pagepermissions if hasattr(Page(), 'permissions'): kwargs['permissions__isnull'] = True # https://github.com/leonardo-modules/leonardo-page-search if hasattr(Page(), 'search_exclude'): kwargs['search_exclude'] = False return self.get_model().objects.filter(**kwargs)
[ "Used when the entire index for model is updated." ]
Please provide a description of the function:def frontendediting_request_processor(page, request): if 'frontend_editing' not in request.GET: return response = HttpResponseRedirect(request.path) if request.user.has_module_perms('page'): if 'frontend_editing' in request.GET: try: enable_fe = int(request.GET['frontend_editing']) > 0 except ValueError: enable_fe = False if enable_fe: response.set_cookie(str('frontend_editing'), enable_fe) clear_cache() else: response.delete_cookie(str('frontend_editing')) clear_cache() else: response.delete_cookie(str('frontend_editing')) # Redirect to cleanup URLs return response
[ "\n Sets the frontend editing state in the cookie depending on the\n ``frontend_editing`` GET parameter and the user's permissions.\n " ]
Please provide a description of the function:def clean(self): '''Check to make sure password fields match.''' data = super(SignupForm, self).clean() # basic check for now if 'username' in data: if User.objects.filter( username=data['username'], email=data['email']).exists(): raise validators.ValidationError( _('Username or email exists in database.')) if 'password' in data: if data['password'] != data.get('confirm_password', None): raise validators.ValidationError(_('Passwords do not match.')) else: data.pop('confirm_password') return data
[]
Please provide a description of the function:def get_form(self, request, obj=None, **kwargs): parent_id = request.REQUEST.get('parent_id', None) if parent_id: return FolderForm else: folder_form = super(FolderAdmin, self).get_form( request, obj=None, **kwargs) def folder_form_clean(form_obj): cleaned_data = form_obj.cleaned_data folders_with_same_name = Folder.objects.filter( parent=form_obj.instance.parent, name=cleaned_data['name']) if form_obj.instance.pk: folders_with_same_name = folders_with_same_name.exclude( pk=form_obj.instance.pk) if folders_with_same_name.exists(): raise ValidationError( 'Folder with this name already exists.') return cleaned_data # attach clean to the default form rather than defining a new form # class folder_form.clean = folder_form_clean return folder_form
[ "\n Returns a Form class for use in the admin add view. This is used by\n add_view and change_view.\n " ]
Please provide a description of the function:def save_form(self, request, form, change): r = form.save(commit=False) parent_id = request.REQUEST.get('parent_id', None) if parent_id: parent = Folder.objects.get(id=parent_id) r.parent = parent return r
[ "\n Given a ModelForm return an unsaved instance. ``change`` is True if\n the object is being changed, and False if it's being added.\n " ]
Please provide a description of the function:def response_change(self, request, obj): r = super(FolderAdmin, self).response_change(request, obj) # Code borrowed from django ModelAdmin to determine changelist on the # fly if r['Location']: # it was a successful save if (r['Location'] in ['../'] or r['Location'] == self._get_post_url(obj)): if obj.parent: url = reverse('admin:filer-directory_listing', kwargs={'folder_id': obj.parent.id}) else: url = reverse('admin:filer-directory_listing-root') url = "%s%s%s" % (url, popup_param(request), selectfolder_param(request, "&")) return HttpResponseRedirect(url) else: # this means it probably was a save_and_continue_editing pass return r
[ "\n Overrides the default to be able to forward to the directory listing\n instead of the default change_list_view\n " ]
Please provide a description of the function:def delete_view(self, request, object_id, extra_context=None): parent_folder = None try: obj = self.queryset(request).get(pk=unquote(object_id)) parent_folder = obj.parent except self.model.DoesNotExist: obj = None r = super(FolderAdmin, self).delete_view( request=request, object_id=object_id, extra_context=extra_context) url = r.get("Location", None) if url in ["../../../../", "../../"] or url == self._get_post_url(obj): if parent_folder: url = reverse('admin:filer-directory_listing', kwargs={'folder_id': parent_folder.id}) else: url = reverse('admin:filer-directory_listing-root') url = "%s%s%s" % (url, popup_param(request), selectfolder_param(request, "&")) return HttpResponseRedirect(url) return r
[ "\n Overrides the default to enable redirecting to the directory view after\n deletion of a folder.\n\n we need to fetch the object and find out who the parent is\n before super, because super will delete the object and make it\n impossible to find out the parent folder to redirect to.\n " ]
Please provide a description of the function:def get_actions(self, request): # If self.actions is explicitly set to None that means that we don't # want *any* actions enabled on this page. if self.actions is None: return OrderedDict() actions = [] # Gather actions from the admin site first for (name, func) in self.admin_site.actions: description = getattr( func, 'short_description', name.replace('_', ' ')) actions.append((func, name, description)) # Then gather them from the model admin and all parent classes, # starting with self and working back up. for klass in self.__class__.mro()[::-1]: class_actions = getattr(klass, 'actions', []) # Avoid trying to iterate over None if not class_actions: continue actions.extend(self.get_action(action) for action in class_actions) # get_action might have returned None, so filter any of those out. actions = filter(None, actions) # Convert the actions into an OrderedDict keyed by name. actions = OrderedDict( (name, (func, name, desc)) for func, name, desc in actions ) if 'delete_selected' in actions: del actions['delete_selected'] return actions
[ "\n Return a dictionary mapping the names of all actions for this\n ModelAdmin to a tuple of (callable, name, description) for each action.\n " ]
Please provide a description of the function:def files_set_public_or_private(self, request, set_public, files_queryset, folders_queryset): if not self.has_change_permission(request): raise PermissionDenied if request.method != 'POST': return None check_files_edit_permissions(request, files_queryset) check_folder_edit_permissions(request, folders_queryset) # We define it like that so that we can modify it inside the set_files # function files_count = [0] def set_files(files): for f in files: if f.is_public != set_public: f.is_public = set_public f.save() files_count[0] += 1 def set_folders(folders): for f in folders: set_files(f.files) set_folders(f.children.all()) set_files(files_queryset) set_folders(folders_queryset) if set_public: self.message_user(request, _("Successfully disabled permissions for %(count)d files.") % { "count": files_count[0], }) else: self.message_user(request, _("Successfully enabled permissions for %(count)d files.") % { "count": files_count[0], }) return None
[ "\n Action which enables or disables permissions for selected files and files in selected folders to clipboard (set them private or public).\n " ]
Please provide a description of the function:def extra_context(self): from django.conf import settings return { "site_name": (lambda r: settings.LEONARDO_SITE_NAME if getattr(settings, 'LEONARDO_SITE_NAME', '') != '' else settings.SITE_NAME), "debug": lambda r: settings.TEMPLATE_DEBUG }
[ "Add site_name to context\n " ]
Please provide a description of the function:def get_property(self, key): _key = DJANGO_CONF[key] return getattr(self, _key, CONF_SPEC[_key])
[ "Expect Django Conf property" ]
Please provide a description of the function:def needs_sync(self): affected_attributes = [ 'css_files', 'js_files', 'scss_files', 'widgets'] for attr in affected_attributes: if len(getattr(self, attr)) > 0: return True return False
[ "Indicates whater module needs templates, static etc." ]
Please provide a description of the function:def demo_paths(self): base_path = os.path.join(self.module.__path__[0], 'demo') paths = [] if os.path.isdir(base_path): for item in os.listdir(base_path): # TODO: support examples which is not auto-loaded if not os.path.isdir(os.path.join(base_path, 'examples')): paths.append(os.path.join(base_path, item)) return paths
[ "returns collected demo paths excluding examples\n TODO: call super which returns custom paths in descriptor\n " ]
Please provide a description of the function:def get_attr(self, name, default=None, fail_silently=True): try: return getattr(self, name) except KeyError: extra_context = getattr(self, "extra_context") if name in extra_context: value = extra_context[name] if callable(value): return value(request=None) return default
[ "try extra context\n " ]
Please provide a description of the function:def send_templated_email(subject, template_name, context, recipients, sender=None, bcc=None, fail_silently=True, files=None): c = Context(context) if not sender: sender = settings.DEFAULT_FROM_EMAIL template = loader.get_template(template_name) text_part = strip_tags(template.render(c)) html_part = template.render(c) if type(recipients) == str: if recipients.find(','): recipients = recipients.split(',') elif type(recipients) != list: recipients = [recipients, ] msg = EmailMultiAlternatives(subject, text_part, sender, recipients, bcc=bcc) msg.attach_alternative(html_part, "text/html") if files: if type(files) != list: files = [files, ] for file in files: msg.attach_file(file) return msg.send(fail_silently)
[ "\n send_templated_mail() is a wrapper around Django's e-mail routines that\n allows us to easily send multipart (text/plain & text/html) e-mails using\n templates that are stored in the database. This lets the admin provide\n both a text and a HTML template for each message.\n\n template_name is the slug of the template to use for this message (see\n models.EmailTemplate)\n\n context is a dictionary to be used when rendering the template\n\n recipients can be either a string, eg '[email protected]', or a list of strings.\n\n sender should contain a string, eg 'My Site <[email protected]>'. If you leave it\n blank, it'll use settings.DEFAULT_FROM_EMAIL as a fallback.\n\n bcc is an optional list of addresses that will receive this message as a\n blind carbon copy.\n\n fail_silently is passed to Django's mail routine. Set to 'True' to ignore\n any errors at send time.\n\n files can be a list of file paths to be attached, or it can be left blank.\n eg ('/tmp/file1.txt', '/tmp/image.png')\n\n " ]
Please provide a description of the function:def find_all_templates(pattern='*.html', ignore_private=True): templates = [] template_loaders = flatten_template_loaders(settings.TEMPLATE_LOADERS) for loader_name in template_loaders: module, klass = loader_name.rsplit('.', 1) if loader_name in ( 'django.template.loaders.app_directories.Loader', 'django.template.loaders.filesystem.Loader', ): loader_class = getattr(import_module(module), klass) if getattr(loader_class, '_accepts_engine_in_init', False): loader = loader_class(Engine.get_default()) else: loader = loader_class() for dir in loader.get_template_sources(''): for root, dirnames, filenames in os.walk(dir): for basename in filenames: if ignore_private and basename.startswith("_"): continue filename = os.path.join(root, basename) rel_filename = filename[len(dir)+1:] if fnmatch.fnmatch(filename, pattern) or \ fnmatch.fnmatch(basename, pattern) or \ fnmatch.fnmatch(rel_filename, pattern): templates.append(rel_filename) else: LOGGER.debug('%s is not supported' % loader_name) return sorted(set(templates))
[ "\n Finds all Django templates matching given glob in all TEMPLATE_LOADERS\n\n :param str pattern: `glob <http://docs.python.org/2/library/glob.html>`_\n to match\n\n .. important:: At the moment egg loader is not supported.\n " ]