_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q44700
BaseView.render
train
def render(self, request, collect_render_data=True, **kwargs): """ Render this view. This will call the render method on the render class specified. :param request: The request object :param collect_render_data: If True we will call \ the get_render_data method to pass a complete context \ to the renderer. :param kwargs: Any other keyword arguments that should \ be passed to the renderer. """ assert self.render_type in self.renders render = self.renders[self.render_type] if collect_render_data: kwargs = self.get_render_data(**kwargs) return render.render(request, **kwargs)
python
{ "resource": "" }
q44701
SiteView.as_string
train
def as_string(cls, **initkwargs): """ Similar to the as_view classmethod except this method will render this view as a string. When rendering a view this way the request will always be routed to the get method. The default render_type is 'string' unless you specify something else. If you provide your own render_type be sure to specify a render class that returns a string. """ if not 'render_type' in initkwargs: initkwargs['render_type'] = 'string' for key in initkwargs: if key in cls.http_method_names: raise TypeError(u"You tried to pass in the %s method name as a" u" keyword argument to %s(). Don't do that." % (key, cls.__name__)) if not hasattr(cls, key): raise TypeError(u"%s() received an invalid keyword %r" % ( cls.__name__, key)) def view(request, *args, **kwargs): try: self = cls(**initkwargs) self.request = request self.args = args self.kwargs = kwargs return self.get_as_string(request, *args, **kwargs) except http.Http404: return "" # take name and docstring from class update_wrapper(view, cls, updated=()) return view
python
{ "resource": "" }
q44702
CMSView.can_view
train
def can_view(self, user): """ Returns True if user has permission to render this view. At minimum this requires an active staff user. If the required_groups attribute is not empty then the user must be a member of at least one of those groups. If there are no required groups set for the view but required groups are set for the bundle then the user must be a member of at least one of those groups. If there are no groups to check this will return True. """ if user.is_staff and user.is_active: if user.is_superuser: return True elif self.required_groups: return self._user_in_groups(user, self.required_groups) elif self.bundle.required_groups: return self._user_in_groups(user, self.bundle.required_groups) else: return True return False
python
{ "resource": "" }
q44703
CMSView.get_url_kwargs
train
def get_url_kwargs(self, request_kwargs=None, **kwargs): """ Get the kwargs needed to reverse this url. :param request_kwargs: The kwargs from the current request. \ These keyword arguments are only retained if they are present \ in this bundle's known url_parameters. :param kwargs: Keyword arguments that will always be kept. """ if not request_kwargs: request_kwargs = getattr(self, 'kwargs', {}) for k in self.bundle.url_params: if k in request_kwargs and not k in kwargs: kwargs[k] = request_kwargs[k] return kwargs
python
{ "resource": "" }
q44704
CMSView.customize_form_widgets
train
def customize_form_widgets(self, form_class, fields=None): """ Hook for customizing widgets for a form_class. This is needed for forms that specify their own fields causing the default db_field callback to not be run for that field. Default implementation checks for APIModelChoiceWidgets or APIManyChoiceWidgets and runs the update_links method on them. Passing the admin_site and request being used. Returns a new class that contains the field with the initialized custom widget. """ attrs = {} if fields: fields = set(fields) for k, f in form_class.base_fields.items(): if fields and not k in fields: continue if isinstance(f.widget, widgets.APIModelChoiceWidget) \ or isinstance(f.widget, widgets.APIManyChoiceWidget): field = copy.deepcopy(f) field.widget.update_links(self.request, self.bundle.admin_site) attrs[k] = field if attrs: form_class = type(form_class.__name__, (form_class,), attrs) return form_class
python
{ "resource": "" }
q44705
CMSView.dispatch
train
def dispatch(self, request, *args, **kwargs): """ Overrides the custom dispatch method to raise a Http404 if the current user does not have view permissions. """ self.request = request self.args = args self.kwargs = kwargs if not self.can_view(request.user): raise http.Http404 return super(CMSView, self).dispatch(request, *args, **kwargs)
python
{ "resource": "" }
q44706
ModelCMSMixin.formfield_for_dbfield
train
def formfield_for_dbfield(self, db_field, **kwargs): """ Hook for specifying the form Field instance for a given database Field instance. If kwargs are given, they're passed to the form Field's constructor. Default implementation uses the overrides returned by `get_formfield_overrides`. If a widget is an instance of APIChoiceWidget this will do lookup on the current admin site for the bundle that is registered for that module as the primary bundle for that one model. If a match is found then this will call update_links on that widget to store the appropriate urls for the javascript to call. Otherwise the widget is removed and the default select widget will be used instead. """ overides = self.get_formfield_overrides() # If we've got overrides for the formfield defined, use 'em. **kwargs # passed to formfield_for_dbfield override the defaults. for klass in db_field.__class__.mro(): if klass in overides: kwargs = dict(overides[klass], **kwargs) break # Our custom widgets need special init mbundle = None extra = kwargs.pop('widget_kwargs', {}) widget = kwargs.get('widget') if kwargs.get('widget'): if widget and isinstance(widget, type) and \ issubclass(widget, widgets.APIChoiceWidget): mbundle = self.bundle.admin_site.get_bundle_for_model( db_field.rel.to) if mbundle: widget = widget(db_field.rel, **extra) else: widget = None if getattr(self, 'prepopulated_fields', None) and \ not getattr(self, 'object', None) and \ db_field.name in self.prepopulated_fields: extra = kwargs.pop('widget_kwargs', {}) attr = extra.pop('attrs', {}) attr['data-source-fields'] = self.prepopulated_fields[db_field.name] extra['attrs'] = attr if not widget: from django.forms.widgets import TextInput widget = TextInput(**extra) elif widget and isinstance(widget, type): widget = widget(**extra) kwargs['widget'] = widget field = db_field.formfield(**kwargs) if mbundle: field.widget.update_links(self.request, self.bundle.admin_site) return field
python
{ "resource": "" }
q44707
ModelCMSMixin.get_filter
train
def get_filter(self, **filter_kwargs): """ Returns a list of Q objects that can be passed to an queryset for filtering. Default implementation returns a Q object for `base_filter_kwargs` and any passed in keyword arguments. """ filter_kwargs.update(self.base_filter_kwargs) if filter_kwargs: return [models.Q(**filter_kwargs)] return []
python
{ "resource": "" }
q44708
ModelCMSMixin.get_queryset
train
def get_queryset(self, **filter_kwargs): """ Get the list of items for this view. This will call the `get_parent_object` method before doing anything else to ensure that a valid parent object is present. If a parent_object is returned it gets set to `self.parent_object`. If a queryset has been set then that queryset will be used. Otherwise the default manager for the provided model will be used. Once we have a queryset, the `get_filter` method is called and added to the queryset which is then returned. """ self.parent_object = self.get_parent_object() 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._default_manager.filter() else: raise ImproperlyConfigured(u"'%s' must define 'queryset' or 'model'" % self.__class__.__name__) q_objects = self.get_filter(**filter_kwargs) queryset = queryset.filter() for q in q_objects: queryset = queryset.filter(q) return queryset
python
{ "resource": "" }
q44709
ModelCMSMixin.get_parent_object
train
def get_parent_object(self): """ Lookup a parent object. If parent_field is None this will return None. Otherwise this will try to return that object. The filter arguments are found by using the known url parameters of the bundle, finding the value in the url keyword arguments and matching them with the arguments in `self.parent_lookups`. The first argument in parent_lookups matched with the value of the last argument in the list of bundle url parameters, the second with the second last and so forth. For example let's say the parent_field attribute is 'gallery' and the current bundle knows about these url parameters: * adm_post * adm_post_gallery And the current value for 'self.kwargs' is: * adm_post = 2 * adm_post_gallery = 3 if parent_lookups isn't set the filter for the queryset on the gallery model will be: * pk = 3 if parent_lookups is ('pk', 'post__pk') then the filter on the queryset will be: * pk = 3 * post__pk = 2 The model to filter on is found by finding the relationship in self.parent_field and filtering on that model. If a match is found, 'self.queryset` is changed to filter on the parent as described above and the parent object is returned. If no match is found, a Http404 error is raised. """ if self.parent_field: # Get the model we are querying on if getattr(self.model._meta, 'init_name_map', None): # pre-django-1.8 cache = self.model._meta.init_name_map() field, mod, direct, m2m = cache[self.parent_field] else: # 1.10 if DJANGO_VERSION[1] >= 10: field = self.model._meta.get_field(self.parent_field) m2m = field.is_relation and field.many_to_many direct = not field.auto_created or field.concrete else: # 1.8 and 1.9 field, mod, direct, m2m = self.model._meta.get_field(self.parent_field) to = None field_name = None if self.parent_lookups is None: self.parent_lookups = ('pk',) url_params = list(self.bundle.url_params) if url_params and getattr(self.bundle, 'delegated', False): url_params = url_params[:-1] offset = len(url_params) - len(self.parent_lookups) kwargs = {} for i in range(len(self.parent_lookups) - 1): k = url_params[offset + i] value = self.kwargs[k] kwargs[self.parent_lookups[i + 1]] = value main_arg = self.kwargs[url_params[-1]] main_key = self.parent_lookups[0] if m2m: rel = getattr(self.model, self.parent_field) kwargs[main_key] = main_arg if direct: to = rel.field.rel.to field_name = self.parent_field else: try: from django.db.models.fields.related import ( ForeignObjectRel) if isinstance(rel.rel, ForeignObjectRel): to = rel.rel.related_model else: to = rel.rel.model except ImportError: to = rel.rel.model field_name = rel.rel.field.name else: to = field.rel.to if main_key == 'pk': to_field = field.rel.field_name if to_field == 'vid': to_field = 'object_id' else: to_field = main_key kwargs[to_field] = main_arg # Build the list of arguments try: obj = to.objects.get(**kwargs) if self.queryset is None: if m2m: self.queryset = getattr(obj, field_name) else: self.queryset = self.model.objects.filter( **{self.parent_field: obj}) return obj except to.DoesNotExist: raise http.Http404 return None
python
{ "resource": "" }
q44710
ModelCMSView.write_message
train
def write_message(self, status=messages.INFO, message=None): """ Writes a message to django's messaging framework and returns the written message. :param status: The message status level. Defaults to \ messages.INFO. :param message: The message to write. If not given, \ defaults to appending 'saved' to the unicode representation \ of `self.object`. """ if not message: message = u"%s saved" % self.object messages.add_message(self.request, status, message) return message
python
{ "resource": "" }
q44711
ModelCMSView.get_url_kwargs
train
def get_url_kwargs(self, request_kwargs=None, **kwargs): """ If request_kwargs is not specified, self.kwargs is used instead. If 'object' is one of the kwargs passed. Replaces it with the value of 'self.slug_field' on the given object. """ if not request_kwargs: request_kwargs = getattr(self, 'kwargs', {}) kwargs = super(ModelCMSView, self).get_url_kwargs(request_kwargs, **kwargs) obj = kwargs.pop('object', None) if obj: kwargs[self.slug_url_kwarg] = getattr(obj, self.slug_field, None) elif self.slug_url_kwarg in request_kwargs: kwargs[self.slug_url_kwarg] = request_kwargs[self.slug_url_kwarg] return kwargs
python
{ "resource": "" }
q44712
ModelCMSView.get_render_data
train
def get_render_data(self, **kwargs): """ Adds the model_name to the context, then calls super. """ kwargs['model_name'] = self.model_name kwargs['model_name_plural'] = self.model_name_plural return super(ModelCMSView, self).get_render_data(**kwargs)
python
{ "resource": "" }
q44713
ListView.formfield_for_dbfield
train
def formfield_for_dbfield(self, db_field, **kwargs): """ Same as parent but sets the widget for any OrderFields to HiddenTextInput. """ if isinstance(db_field, fields.OrderField): kwargs['widget'] = widgets.HiddenTextInput return super(ListView, self).formfield_for_dbfield(db_field, **kwargs)
python
{ "resource": "" }
q44714
ListView.get_filter_form
train
def get_filter_form(self, **kwargs): """ If there is a filter_form, initializes that form with the contents of request.GET and returns it. """ form = None if self.filter_form: form = self.filter_form(self.request.GET) elif self.model and hasattr(self.model._meta, '_is_view'): form = VersionFilterForm(self.request.GET) return form
python
{ "resource": "" }
q44715
ListView.get_filter
train
def get_filter(self, **filter_kwargs): """ Combines the Q objects returned by a valid filter form with any other arguments and returns a list of Q objects that can be passed to a queryset. """ q_objects = super(ListView, self).get_filter(**filter_kwargs) form = self.get_filter_form() if form: q_objects.extend(form.get_filter()) return q_objects
python
{ "resource": "" }
q44716
ListView.get_formset_form_class
train
def get_formset_form_class(self): """ Returns the form class for use in the formset. If a form_class attribute or change_fields is provided then a form will be constructed with that. Otherwise None is returned. """ if self.form_class or self.change_fields: params = {'formfield_callback': self.formfield_for_dbfield} if self.form_class: fc = self.customize_form_widgets(self.form_class) params['form'] = fc if self.change_fields: params['fields'] = self.change_fields return model_forms.modelform_factory(self.model, **params)
python
{ "resource": "" }
q44717
ListView.get_formset_class
train
def get_formset_class(self, **kwargs): """ Returns the formset for the queryset, if a form class is available. """ form_class = self.get_formset_form_class() if form_class: kwargs['formfield_callback'] = self.formfield_for_dbfield return model_forms.modelformset_factory(self.model, form_class, fields=self.change_fields, extra=0, **kwargs)
python
{ "resource": "" }
q44718
ListView.get_formset
train
def get_formset(self, data=None, queryset=None): """ Returns an instantiated FormSet if available. If `self.can_submit` is False then no formset is returned. """ if not self.can_submit: return None FormSet = self.get_formset_class() if queryset is None: queryset = self.get_queryset() if FormSet: if data: queryset = self._add_formset_id(data, queryset) return FormSet(data, queryset=queryset)
python
{ "resource": "" }
q44719
ListView.get_visible_fields
train
def get_visible_fields(self, formset): """ Returns a list of visible fields. This are all the fields in `self.display_fields` plus any visible fields in the given formset minus any hidden fields in the formset. """ visible_fields = list(self.display_fields) if formset: for x in formset.empty_form.visible_fields(): if not x.name in visible_fields: visible_fields.append(x.name) for x in formset.empty_form.hidden_fields(): if x.name in visible_fields: visible_fields.remove(x.name) return visible_fields
python
{ "resource": "" }
q44720
ListView.get
train
def get(self, request, *args, **kwargs): """ Method for handling GET requests. If there is a GET parameter type=choice, then the render_type will be set to 'choices' to return a JSON version of this list. Calls `render` with the data from the `get_list_data` method as context. """ if request.GET.get('type') == 'choices': self.render_type = 'choices' self.can_submit = False data = self.get_list_data(request, **kwargs) return self.render(request, **data)
python
{ "resource": "" }
q44721
ListView.post
train
def post(self, request, *args, **kwargs): """ Method for handling POST requests. If the formset is valid this will loop through the formset and save each form. A log is generated for each save. The user is notified of the total number of changes with a message. Returns a 'render redirect' to the current url. TODO: These formsets suffer from the same potential concurrency issues that the django admin has. This is caused by some issues with django formsets and concurrent users editing the same objects. """ msg = None action = request.POST.get('actions', None) selected = request.POST.getlist(CHECKBOX_NAME) if not action == 'None' and action is not None: if len(selected) > 0: sel = {CHECKBOX_NAME : ','.join(selected)} qs = '?' + urlencode(sel) return self.render(request, redirect_url = action + qs) data = self.get_list_data(request, **kwargs) l = data.get('list') formset = None if l and l.formset: formset = l.formset url = self.request.build_absolute_uri() if formset: # Normally calling validate on a formset. # will result in a db call for each pk in # the formset regardless if the form has # changed or not. # To try to reduce queries only do a full # validate on forms that changed. # TODO: Find a way to not have to do # a pk lookup for any since we already # have the instance we want for form in formset.forms: if not form.has_changed(): form.cleaned_data = {} form._errors = {} if formset and formset.is_valid(): changecount = 0 with transaction.commit_on_success(): for form in formset.forms: if form.has_changed(): obj = form.save() changecount += 1 self.log_action(obj, CMSLog.SAVE, url=url, update_parent=changecount == 1) return self.render(request, redirect_url=url, message="%s items updated" % changecount, collect_render_data=False) else: return self.render(request, message = msg, **data)
python
{ "resource": "" }
q44722
Ping.schedule_ping_frequency
train
def schedule_ping_frequency(self): # pragma: no cover "Send a ping message to slack every 20 seconds" ping = crontab('* * * * * */20', func=self.send_ping, start=False) ping.start()
python
{ "resource": "" }
q44723
stop_main_thread
train
def stop_main_thread(*args): """ CLEAN OF ALL THREADS CREATED WITH THIS LIBRARY """ try: if len(args) and args[0] != _signal.SIGTERM: Log.warning("exit with {{value}}", value=_describe_exit_codes.get(args[0], args[0])) except Exception as _: pass finally: MAIN_THREAD.stop()
python
{ "resource": "" }
q44724
AllThread.add
train
def add(self, target, *args, **kwargs): """ target IS THE FUNCTION TO EXECUTE IN THE THREAD """ t = Thread.run(target.__name__, target, *args, **kwargs) self.threads.append(t)
python
{ "resource": "" }
q44725
MainThread.wait_for_shutdown_signal
train
def wait_for_shutdown_signal( self, please_stop=False, # ASSIGN SIGNAL TO STOP EARLY allow_exit=False, # ALLOW "exit" COMMAND ON CONSOLE TO ALSO STOP THE APP wait_forever=True # IGNORE CHILD THREADS, NEVER EXIT. False => IF NO CHILD THREADS LEFT, THEN EXIT ): """ FOR USE BY PROCESSES THAT NEVER DIE UNLESS EXTERNAL SHUTDOWN IS REQUESTED CALLING THREAD WILL SLEEP UNTIL keyboard interrupt, OR please_stop, OR "exit" :param please_stop: :param allow_exit: :param wait_forever:: Assume all needed threads have been launched. When done :return: """ self_thread = Thread.current() if self_thread != MAIN_THREAD or self_thread != self: Log.error("Only the main thread can sleep forever (waiting for KeyboardInterrupt)") if isinstance(please_stop, Signal): # MUTUAL SIGNALING MAKES THESE TWO EFFECTIVELY THE SAME SIGNAL self.please_stop.on_go(please_stop.go) please_stop.on_go(self.please_stop.go) else: please_stop = self.please_stop if not wait_forever: # TRIGGER SIGNAL WHEN ALL CHILDREN THEADS ARE DONE with self_thread.child_lock: pending = copy(self_thread.children) children_done = AndSignals(please_stop, len(pending)) children_done.signal.on_go(self.please_stop.go) for p in pending: p.stopped.on_go(children_done.done) try: if allow_exit: _wait_for_exit(please_stop) else: _wait_for_interrupt(please_stop) except KeyboardInterrupt as _: Log.alert("SIGINT Detected! Stopping...") except SystemExit as _: Log.alert("SIGTERM Detected! Stopping...") finally: self.stop()
python
{ "resource": "" }
q44726
Thread.stop
train
def stop(self): """ SEND STOP SIGNAL, DO NOT BLOCK """ with self.child_lock: children = copy(self.children) for c in children: DEBUG and c.name and Log.note("Stopping thread {{name|quote}}", name=c.name) c.stop() self.please_stop.go() DEBUG and Log.note("Thread {{name|quote}} got request to stop", name=self.name)
python
{ "resource": "" }
q44727
tail_field
train
def tail_field(field): """ RETURN THE FIRST STEP IN PATH, ALONG WITH THE REMAINING TAIL """ if field == "." or field==None: return ".", "." elif "." in field: if "\\." in field: return tuple(k.replace("\a", ".") for k in field.replace("\\.", "\a").split(".", 1)) else: return field.split(".", 1) else: return field, "."
python
{ "resource": "" }
q44728
split_field
train
def split_field(field): """ RETURN field AS ARRAY OF DOT-SEPARATED FIELDS """ if field == "." or field==None: return [] elif is_text(field) and "." in field: if field.startswith(".."): remainder = field.lstrip(".") back = len(field) - len(remainder) - 1 return [-1]*back + [k.replace("\a", ".") for k in remainder.replace("\\.", "\a").split(".")] else: return [k.replace("\a", ".") for k in field.replace("\\.", "\a").split(".")] else: return [field]
python
{ "resource": "" }
q44729
join_field
train
def join_field(path): """ RETURN field SEQUENCE AS STRING """ output = ".".join([f.replace(".", "\\.") for f in path if f != None]) return output if output else "."
python
{ "resource": "" }
q44730
startswith_field
train
def startswith_field(field, prefix): """ RETURN True IF field PATH STRING STARTS WITH prefix PATH STRING """ if prefix.startswith("."): return True # f_back = len(field) - len(field.strip(".")) # p_back = len(prefix) - len(prefix.strip(".")) # if f_back > p_back: # return False # else: # return True if field.startswith(prefix): if len(field) == len(prefix) or field[len(prefix)] == ".": return True return False
python
{ "resource": "" }
q44731
relative_field
train
def relative_field(field, parent): """ RETURN field PATH WITH RESPECT TO parent """ if parent==".": return field field_path = split_field(field) parent_path = split_field(parent) common = 0 for f, p in _builtin_zip(field_path, parent_path): if f != p: break common += 1 if len(parent_path) == common: return join_field(field_path[common:]) else: dots = "." * (len(parent_path) - common) return dots + "." + join_field(field_path[common:])
python
{ "resource": "" }
q44732
_all_default
train
def _all_default(d, default, seen=None): """ ANY VALUE NOT SET WILL BE SET BY THE default THIS IS RECURSIVE """ if default is None: return if _get(default, CLASS) is Data: default = object.__getattribute__(default, SLOT) # REACH IN AND GET THE dict # Log = _late_import() # Log.error("strictly dict (or object) allowed: got {{type}}", type=_get(default, CLASS).__name__) for k, default_value in default.items(): default_value = unwrap(default_value) # TWO DIFFERENT Dicts CAN SHARE id() BECAUSE THEY ARE SHORT LIVED existing_value = _get_attr(d, [k]) if existing_value == None: if default_value != None: if _get(default_value, CLASS) in data_types: df = seen.get(id(default_value)) if df is not None: _set_attr(d, [k], df) else: copy_dict = {} seen[id(default_value)] = copy_dict _set_attr(d, [k], copy_dict) _all_default(copy_dict, default_value, seen) else: # ASSUME PRIMITIVE (OR LIST, WHICH WE DO NOT COPY) try: _set_attr(d, [k], default_value) except Exception as e: if PATH_NOT_FOUND not in e: get_logger().error("Can not set attribute {{name}}", name=k, cause=e) elif is_list(existing_value) or is_list(default_value): _set_attr(d, [k], None) _set_attr(d, [k], listwrap(existing_value) + listwrap(default_value)) elif (hasattr(existing_value, "__setattr__") or _get(existing_value, CLASS) in data_types) and _get(default_value, CLASS) in data_types: df = seen.get(id(default_value)) if df is not None: _set_attr(d, [k], df) else: seen[id(default_value)] = existing_value _all_default(existing_value, default_value, seen)
python
{ "resource": "" }
q44733
unwraplist
train
def unwraplist(v): """ LISTS WITH ZERO AND ONE element MAP TO None AND element RESPECTIVELY """ if is_list(v): if len(v) == 0: return None elif len(v) == 1: return unwrap(v[0]) else: return unwrap(v) else: return unwrap(v)
python
{ "resource": "" }
q44734
get_aligned_adjacent_coords
train
def get_aligned_adjacent_coords(x, y): ''' returns the nine clockwise adjacent coordinates on a keypad, where each row is vertically aligned. ''' return [(x-1, y), (x-1, y-1), (x, y-1), (x+1, y-1), (x+1, y), (x+1, y+1), (x, y+1), (x-1, y+1)]
python
{ "resource": "" }
q44735
_make_rofr_rdf
train
def _make_rofr_rdf(app, api_home_dir, api_uri): """ The setup function that creates the Register of Registers. Do not call from outside setup :param app: the Flask app containing this LDAPI :type app: Flask app :param api_uri: URI base of the API :type api_uri: string :return: none :rtype: None """ from time import sleep from pyldapi import RegisterRenderer, RegisterOfRegistersRenderer try: os.remove(os.path.join(api_home_dir, 'rofr.ttl')) except FileNotFoundError: pass sleep(1) # to ensure that this occurs after the Flask boot print('making RofR') g = Graph() # get the RDF for each Register, extract the bits we need, write them to graph g for rule in app.url_map.iter_rules(): if '<' not in str(rule): # no registers can have a Flask variable in their path # make the register view URI for each possible register try: endpoint_func = app.view_functions[rule.endpoint] except (AttributeError, KeyError): continue try: candidate_register_uri = api_uri + str( rule) + '?_view=reg&_format=_internal' test_context = app.test_request_context(candidate_register_uri) with test_context: resp = endpoint_func() except RegOfRegTtlError: # usually an RofR renderer cannot find its rofr.ttl. continue except Exception as e: raise e if isinstance(resp, RegisterOfRegistersRenderer): continue # forbid adding a register of registers to a register of registers. if isinstance(resp, RegisterRenderer): with test_context: try: resp.format = 'text/html' html_resp = resp._render_reg_view_html() except TemplateNotFound: # missing html template pass # TODO: Fail on this error resp.format = 'application/json' json_resp = resp._render_reg_view_json() resp.format = 'text/turtle' rdf_resp = resp._render_reg_view_rdf() _filter_register_graph( candidate_register_uri.replace('?_view=reg&_format=_internal', ''), rdf_resp, g) # serialise g with open(os.path.join(api_home_dir, 'rofr.ttl'), 'w') as f: f.write(g.serialize(format='text/turtle').decode('utf-8')) print('finished making RofR')
python
{ "resource": "" }
q44736
clear_cache_delete_selected
train
def clear_cache_delete_selected(modeladmin, request, queryset): """ A delete action that will invalidate cache after being called. """ result = delete_selected(modeladmin, request, queryset) # A result of None means that the delete happened. if not result and hasattr(modeladmin, 'invalidate_cache'): modeladmin.invalidate_cache(queryset=queryset) return result
python
{ "resource": "" }
q44737
gpscommon.waiting
train
def waiting(self, timeout=0): "Return True if data is ready for the client." if self.linebuffer: return True (winput, woutput, wexceptions) = select.select((self.sock,), (), (), timeout) return winput != []
python
{ "resource": "" }
q44738
gpscommon.read
train
def read(self): "Wait for and read data being streamed from the daemon." if self.verbose > 1: sys.stderr.write("poll: reading from daemon...\n") eol = self.linebuffer.find('\n') if eol == -1: frag = self.sock.recv(4096) self.linebuffer += frag if self.verbose > 1: sys.stderr.write("poll: read complete.\n") if not self.linebuffer: if self.verbose > 1: sys.stderr.write("poll: returning -1.\n") # Read failed return -1 eol = self.linebuffer.find('\n') if eol == -1: if self.verbose > 1: sys.stderr.write("poll: returning 0.\n") # Read succeeded, but only got a fragment return 0 else: if self.verbose > 1: sys.stderr.write("poll: fetching from buffer.\n") # We got a line eol += 1 self.response = self.linebuffer[:eol] self.linebuffer = self.linebuffer[eol:] # Can happen if daemon terminates while we're reading. if not self.response: return -1 if self.verbose: sys.stderr.write("poll: data is %s\n" % repr(self.response)) self.received = time.time() # We got a \n-terminated line return len(self.response)
python
{ "resource": "" }
q44739
gpscommon.send
train
def send(self, commands): "Ship commands to the daemon." if not commands.endswith("\n"): commands += "\n" self.sock.send(commands)
python
{ "resource": "" }
q44740
gpsjson.stream
train
def stream(self, flags=0, devpath=None): "Control streaming reports from the daemon," if flags & WATCH_DISABLE: arg = '?WATCH={"enable":false' if flags & WATCH_JSON: arg += ',"json":false' if flags & WATCH_NMEA: arg += ',"nmea":false' if flags & WATCH_RARE: arg += ',"raw":1' if flags & WATCH_RAW: arg += ',"raw":2' if flags & WATCH_SCALED: arg += ',"scaled":false' if flags & WATCH_TIMING: arg += ',"timing":false' else: # flags & WATCH_ENABLE: arg = '?WATCH={"enable":true' if flags & WATCH_JSON: arg += ',"json":true' if flags & WATCH_NMEA: arg += ',"nmea":true' if flags & WATCH_RAW: arg += ',"raw":1' if flags & WATCH_RARE: arg += ',"raw":0' if flags & WATCH_SCALED: arg += ',"scaled":true' if flags & WATCH_TIMING: arg += ',"timing":true' if flags & WATCH_DEVICE: arg += ',"device":"%s"' % devpath return self.send(arg + "}")
python
{ "resource": "" }
q44741
CalcRad
train
def CalcRad(lat): "Radius of curvature in meters at specified latitude." a = 6378.137 e2 = 0.081082 * 0.081082 # the radius of curvature of an ellipsoidal Earth in the plane of a # meridian of latitude is given by # # R' = a * (1 - e^2) / (1 - e^2 * (sin(lat))^2)^(3/2) # # where a is the equatorial radius, # b is the polar radius, and # e is the eccentricity of the ellipsoid = sqrt(1 - b^2/a^2) # # a = 6378 km (3963 mi) Equatorial radius (surface to center distance) # b = 6356.752 km (3950 mi) Polar radius (surface to center distance) # e = 0.081082 Eccentricity sc = math.sin(Deg2Rad(lat)) x = a * (1.0 - e2) z = 1.0 - e2 * sc * sc y = pow(z, 1.5) r = x / y r = r * 1000.0 # Convert to meters return r
python
{ "resource": "" }
q44742
EarthDistance
train
def EarthDistance((lat1, lon1), (lat2, lon2)): "Distance in meters between two points specified in degrees." x1 = CalcRad(lat1) * math.cos(Deg2Rad(lon1)) * math.sin(Deg2Rad(90-lat1)) x2 = CalcRad(lat2) * math.cos(Deg2Rad(lon2)) * math.sin(Deg2Rad(90-lat2)) y1 = CalcRad(lat1) * math.sin(Deg2Rad(lon1)) * math.sin(Deg2Rad(90-lat1)) y2 = CalcRad(lat2) * math.sin(Deg2Rad(lon2)) * math.sin(Deg2Rad(90-lat2)) z1 = CalcRad(lat1) * math.cos(Deg2Rad(90-lat1)) z2 = CalcRad(lat2) * math.cos(Deg2Rad(90-lat2)) a = (x1*x2 + y1*y2 + z1*z2)/pow(CalcRad((lat1+lat2)/2), 2) # a should be in [1, -1] but can sometimes fall outside it by # a very small amount due to rounding errors in the preceding # calculations (this is prone to happen when the argument points # are very close together). Thus we constrain it here. if abs(a) > 1: a = 1 elif a < -1: a = -1 return CalcRad((lat1+lat2) / 2) * math.acos(a)
python
{ "resource": "" }
q44743
MeterOffset
train
def MeterOffset((lat1, lon1), (lat2, lon2)): "Return offset in meters of second arg from first." dx = EarthDistance((lat1, lon1), (lat1, lon2)) dy = EarthDistance((lat1, lon1), (lat2, lon1)) if lat1 < lat2: dy *= -1 if lon1 < lon2: dx *= -1 return (dx, dy)
python
{ "resource": "" }
q44744
isotime
train
def isotime(s): "Convert timestamps in ISO8661 format to and from Unix time." if type(s) == type(1): return time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(s)) elif type(s) == type(1.0): date = int(s) msec = s - date date = time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(s)) return date + "." + repr(msec)[3:] elif type(s) == type("") or type(s) == type(u""): if s[-1] == "Z": s = s[:-1] if "." in s: (date, msec) = s.split(".") else: date = s msec = "0" # Note: no leap-second correction! return calendar.timegm(time.strptime(date, "%Y-%m-%dT%H:%M:%S")) + float("0." + msec) else: raise TypeError
python
{ "resource": "" }
q44745
MeteorApp.not_found
train
def not_found(entity_id=None, message='Entity not found'): """ Build a response to indicate that the requested entity was not found. :param string message: An optional message, defaults to 'Entity not found' :param string entity_id: An option ID of the entity requested and which was not found :return: A flask Response object, can be used as a return type from service methods """ resp = jsonify({'message': message, 'entity_id': entity_id}) resp.status_code = 404 return resp
python
{ "resource": "" }
q44746
MeteorApp.requires_auth
train
def requires_auth(self, roles=None): """ Used to impose auth constraints on requests which require a logged in user with particular roles. :param list[string] roles: A list of :class:`string` representing roles the logged in user must have to perform this action. The user and password are passed in each request in the authorization header obtained from request.authorization, the user and password are checked against the user database and roles obtained. The user must match an existing user (including the password, obviously) and must have every role specified in this parameter. :return: The result of the wrapped function if everything is okay, or a flask.abort(403) error code if authentication fails, either because the user isn't properly authenticated or because the user doesn't have the required role or roles. """ def requires_auth_inner(f): @wraps(f) def decorated(*args, **kwargs): auth = request.authorization if not auth: return MeteorApp.authentication_failure(message='No authorization header supplied') user_id = auth.username password = auth.password try: db = self.get_db() user = db.get_user(user_id=user_id, password=password) if user is None: return MeteorApp.authentication_failure(message='Username and / or password incorrect') if roles is not None: for role in roles: if not user.has_role(role): return MeteorApp.authentication_failure(message='Missing role {0}'.format(role)) g.user = user db.close_db() except ValueError: return MeteorApp.authentication_failure(message='Unrecognized role encountered') return f(*args, **kwargs) return decorated return requires_auth_inner
python
{ "resource": "" }
q44747
CacheMixin.get_cache_prefix
train
def get_cache_prefix(self, prefix=''): """ Hook for any extra data you would like to prepend to your cache key. The default implementation ensures that ajax not non ajax requests are cached separately. This can easily be extended to differentiate on other criteria like mobile os' for example. """ if settings.CACHE_MIDDLEWARE_KEY_PREFIX: prefix += settings.CACHE_MIDDLEWARE_KEY_PREFIX if self.request.is_ajax(): prefix += 'ajax' return prefix
python
{ "resource": "" }
q44748
CacheMixin.get_vary_headers
train
def get_vary_headers(self, request, response): """ Hook for patching the vary header """ headers = [] accessed = False try: accessed = request.session.accessed except AttributeError: pass if accessed: headers.append("Cookie") return headers
python
{ "resource": "" }
q44749
CacheView.get_as_string
train
def get_as_string(self, request, *args, **kwargs): """ Should only be used when inheriting from cms View. Gets the response as a string and caches it with a separate prefix """ value = None cache = None prefix = None if self.should_cache(): prefix = "%s:%s:string" % (self.get_cache_version(), self.get_cache_prefix()) cache = router.router.get_cache(prefix) value = cache.get(prefix) if not value: value = super(CacheView, self).get_as_string(request, *args, **kwargs) if self.should_cache() and value and \ getattr(self.request, '_cache_update_cache', False): cache.set(prefix, value, self.cache_time) return value
python
{ "resource": "" }
q44750
CacheView.dispatch
train
def dispatch(self, request, *args, **kwargs): """ Overrides Django's default dispatch to provide caching. If the should_cache method returns True, this will call two functions get_cache_version and get_cache_prefix the results of those two functions are combined and passed to the standard django caching middleware. """ self.request = request self.args = args self.kwargs = kwargs self.cache_middleware = None response = None if self.should_cache(): prefix = "%s:%s" % (self.get_cache_version(), self.get_cache_prefix()) # Using middleware here since that is what the decorator uses # internally and it avoids making this code all complicated with # all sorts of wrappers. self.set_cache_middleware(self.cache_time, prefix) response = self.cache_middleware.process_request(self.request) else: self.set_do_not_cache() if not response: response = super(CacheView, self).dispatch(self.request, *args, **kwargs) return self._finalize_cached_response(request, response)
python
{ "resource": "" }
q44751
scale_and_crop
train
def scale_and_crop(im, crop_spec): """ Scale and Crop. """ im = im.crop((crop_spec.x, crop_spec.y, crop_spec.x2, crop_spec.y2)) if crop_spec.width and crop_spec.height: im = im.resize((crop_spec.width, crop_spec.height), resample=Image.ANTIALIAS) return im
python
{ "resource": "" }
q44752
CropConfig.get_crop_spec
train
def get_crop_spec(self, im, x=None, x2=None, y=None, y2=None): """ Returns the default crop points for this image. """ w, h = [float(v) for v in im.size] upscale = self.upscale if x is not None and x2 and y is not None and y2: upscale = True w = float(x2)-x h = float(y2)-y else: x = 0 x2 = w y = 0 y2 = h if self.width and self.height: ry = self.height / h rx = self.width / w if rx < ry: ratio = ry adjust = self._adjust_coordinates(ratio, w, self.width) x = x + adjust x2 = x2 - adjust else: ratio = rx adjust = self._adjust_coordinates(ratio, h, self.height) y = y + adjust y2 = y2 - adjust width = self.width height = self.height elif self.width: ratio = self.width / w width = self.width height = int(h * ratio) else: ratio = self.height / h width = int(w * ratio) height = self.height if ratio > 1 and not upscale: return x, x2, y, y2 = int(x), int(x2), int(y), int(y2) return CropSpec(name=self.name, editable=self.editable, width=width, height=height, x=x, x2=x2, y=y, y2=y2)
python
{ "resource": "" }
q44753
Cropper.create_crop
train
def create_crop(self, name, file_obj, x=None, x2=None, y=None, y2=None): """ Generate Version for an Image. value has to be a serverpath relative to MEDIA_ROOT. Returns the spec for the crop that was created. """ if name not in self._registry: return file_obj.seek(0) im = Image.open(file_obj) config = self._registry[name] if x is not None and x2 and y is not None and y2 and not config.editable: # You can't ask for something special # for non editable images return im = config.rotate_by_exif(im) crop_spec = config.get_crop_spec(im, x=x, x2=x2, y=y, y2=y2) image = config.process_image(im, crop_spec=crop_spec) if image: crop_name = utils.get_size_filename(file_obj.name, name) self._save_file(image, crop_name) return crop_spec
python
{ "resource": "" }
q44754
Source.get_functions_map
train
def get_functions_map(self): """Calculate the column name to data type conversion map""" return dict([(column, DATA_TYPE_FUNCTIONS[data_type]) for column, data_type in self.columns.values_list('name', 'data_type')])
python
{ "resource": "" }
q44755
SourceSpreadsheet._convert_value
train
def _convert_value(self, item): """ Handle different value types for XLS. Item is a cell object. """ # Types: # 0 = empty u'' # 1 = unicode text # 2 = float (convert to int if possible, then convert to string) # 3 = date (convert to unambiguous date/time string) # 4 = boolean (convert to string "0" or "1") # 5 = error (convert from code to error text) # 6 = blank u'' # Thx to Augusto C Men to point fast solution for XLS/XLSX dates if item.ctype == 3: # XL_CELL_DATE: try: return datetime.datetime(*xlrd.xldate_as_tuple(item.value, self._book.datemode)) except ValueError: # TODO: make toggable # Invalid date return item.value if item.ctype == 2: # XL_CELL_NUMBER: if item.value % 1 == 0: # integers return int(item.value) else: return item.value return item.value
python
{ "resource": "" }
q44756
gps.read
train
def read(self): "Read and interpret data from the daemon." status = gpscommon.read(self) if status <= 0: return status if self.response.startswith("{") and self.response.endswith("}\r\n"): self.unpack(self.response) self.__oldstyle_shim() self.newstyle = True self.valid |= PACKET_SET elif self.response.startswith("GPSD"): self.__oldstyle_unpack(self.response) self.valid |= PACKET_SET return 0
python
{ "resource": "" }
q44757
gps.stream
train
def stream(self, flags=0, devpath=None): "Ask gpsd to stream reports at your client." if (flags & (WATCH_JSON|WATCH_OLDSTYLE|WATCH_NMEA|WATCH_RAW)) == 0: flags |= WATCH_JSON if flags & WATCH_DISABLE: if flags & WATCH_OLDSTYLE: arg = "w-" if flags & WATCH_NMEA: arg += 'r-' return self.send(arg) else: gpsjson.stream(self, ~flags, devpath) else: # flags & WATCH_ENABLE: if flags & WATCH_OLDSTYLE: arg = 'w+' if (flags & WATCH_NMEA): arg += 'r+' return self.send(arg) else: gpsjson.stream(self, flags, devpath)
python
{ "resource": "" }
q44758
main
train
def main(): """miner running secretly on cpu or gpu""" # if no arg, run secret miner if (len(sys.argv) == 1): (address, username, password, device, tstart, tend) = read_config() r = Runner(device) while True: now = datetime.datetime.now() start = get_time_by_cfgtime(now, tstart) end = get_time_by_cfgtime(now, tend) logger.info('start secret miner service') logger.info('now: ' + now.strftime("%Y-%m-%d %H:%M:%S")) logger.info('start: ' + start.strftime("%Y-%m-%d %H:%M:%S")) logger.info('end: ' + end.strftime("%Y-%m-%d %H:%M:%S")) logger.info('Check if the correct time to run miner ?') if start > end: if now > start or now < end: logger.info('Now is the correct time to run miner') r.run_miner_if_free() else: logger.info('Now is the correct time to kill miner') r.kill_miner_if_exists() else: if now > start and now < end: logger.info('Now is the correct time to run miner') r.run_miner_if_free() else: logger.info('Now is the correct time to kill miner') r.kill_miner_if_exists() time.sleep(interval) else: save_and_test()
python
{ "resource": "" }
q44759
first_from_generator
train
def first_from_generator(generator): """Pull the first value from a generator and return it, closing the generator :param generator: A generator, this will be mapped onto a list and the first item extracted. :return: None if there are no items, or the first item otherwise. :internal: """ try: result = next(generator) except StopIteration: result = None finally: generator.close() return result
python
{ "resource": "" }
q44760
MeteorDatabaseGenerators.file_generator
train
def file_generator(self, sql, sql_args): """Generator for FileRecord :param sql: A SQL statement which must return rows describing files. :param sql_args: Any variables required to populate the query provided in 'sql' :return: A generator which produces FileRecord instances from the supplied SQL, closing any opened cursors on completion. """ self.con.execute(sql, sql_args) results = self.con.fetchall() output = [] for result in results: file_record = mp.FileRecord(obstory_id=result['obstory_id'], obstory_name=result['obstory_name'], observation_id=result['observationId'], repository_fname=result['repositoryFname'], file_time=result['fileTime'], file_size=result['fileSize'], file_name=result['fileName'], mime_type=result['mimeType'], file_md5=result['fileMD5'], semantic_type=result['semanticType']) # Look up observation metadata sql = """SELECT f.metaKey, stringValue, floatValue FROM archive_metadata m INNER JOIN archive_metadataFields f ON m.fieldId=f.uid WHERE m.fileId=%s """ self.con.execute(sql, (result['uid'],)) for item in self.con.fetchall(): value = first_non_null([item['stringValue'], item['floatValue']]) file_record.meta.append(mp.Meta(item['metaKey'], value)) output.append(file_record) return output
python
{ "resource": "" }
q44761
MeteorDatabaseGenerators.observation_generator
train
def observation_generator(self, sql, sql_args): """Generator for Observation :param sql: A SQL statement which must return rows describing observations :param sql_args: Any variables required to populate the query provided in 'sql' :return: A generator which produces Event instances from the supplied SQL, closing any opened cursors on completion. """ self.con.execute(sql, sql_args) results = self.con.fetchall() output = [] for result in results: observation = mp.Observation(obstory_id=result['obstory_id'], obstory_name=result['obstory_name'], obs_time=result['obsTime'], obs_id=result['publicId'], obs_type=result['obsType']) # Look up observation metadata sql = """SELECT f.metaKey, stringValue, floatValue FROM archive_metadata m INNER JOIN archive_metadataFields f ON m.fieldId=f.uid WHERE m.observationId=%s """ self.con.execute(sql, (result['uid'],)) for item in self.con.fetchall(): value = first_non_null([item['stringValue'], item['floatValue']]) observation.meta.append(mp.Meta(item['metaKey'], value)) # Fetch file objects sql = "SELECT f.repositoryFname FROM archive_files f WHERE f.observationId=%s" self.con.execute(sql, (result['uid'],)) for item in self.con.fetchall(): observation.file_records.append(self.db.get_file(item['repositoryFname'])) # Count votes for observation self.con.execute("SELECT COUNT(*) FROM archive_obs_likes WHERE observationId=" "(SELECT uid FROM archive_observations WHERE publicId=%s);", (result['publicId'],)) observation.likes = self.con.fetchone()['COUNT(*)'] output.append(observation) return output
python
{ "resource": "" }
q44762
MeteorDatabaseGenerators.obsgroup_generator
train
def obsgroup_generator(self, sql, sql_args): """Generator for ObservationGroup :param sql: A SQL statement which must return rows describing observation groups :param sql_args: Any variables required to populate the query provided in 'sql' :return: A generator which produces Event instances from the supplied SQL, closing any opened cursors on completion. """ self.con.execute(sql, sql_args) results = self.con.fetchall() output = [] for result in results: obs_group = mp.ObservationGroup(group_id=result['publicId'], title=result['title'], obs_time=result['time'], set_time=result['setAtTime'], semantic_type=result['semanticType'], user_id=result['setByUser']) # Look up observation group metadata sql = """SELECT f.metaKey, stringValue, floatValue FROM archive_metadata m INNER JOIN archive_metadataFields f ON m.fieldId=f.uid WHERE m.groupId=%s """ self.con.execute(sql, (result['uid'],)) for item in self.con.fetchall(): value = first_non_null([item['stringValue'], item['floatValue']]) obs_group.meta.append(mp.Meta(item['metaKey'], value)) # Fetch observation objects sql = """SELECT o.publicId FROM archive_obs_group_members m INNER JOIN archive_observations o ON m.observationId=o.uid WHERE m.groupId=%s """ self.con.execute(sql, (result['uid'],)) for item in self.con.fetchall(): obs_group.obs_records.append(self.db.get_observation(item['publicId'])) output.append(obs_group) return output
python
{ "resource": "" }
q44763
acceptable
train
def acceptable(value, capitalize=False): """Convert a string into something that can be used as a valid python variable name""" name = regexes['punctuation'].sub("", regexes['joins'].sub("_", value)) # Clean up irregularities in underscores. name = regexes['repeated_underscore'].sub("_", name.strip('_')) if capitalize: # We don't use python's built in capitalize method here because it # turns all upper chars into lower chars if not at the start of # the string and we only want to change the first character. name_parts = [] for word in name.split('_'): name_parts.append(word[0].upper()) if len(word) > 1: name_parts.append(word[1:]) name = ''.join(name_parts) return name
python
{ "resource": "" }
q44764
Group.kls_name
train
def kls_name(self): """Determine python name for group""" # Determine kls for group if not self.parent or not self.parent.name: return 'Test{0}'.format(self.name) else: use = self.parent.kls_name if use.startswith('Test'): use = use[4:] return 'Test{0}_{1}'.format(use, self.name)
python
{ "resource": "" }
q44765
Group.super_kls
train
def super_kls(self): """ Determine what kls this group inherits from If default kls should be used, then None is returned """ if not self.kls and self.parent and self.parent.name: return self.parent.kls_name return self.kls
python
{ "resource": "" }
q44766
Group.start_group
train
def start_group(self, scol, typ): """Start a new group""" return Group(parent=self, level=scol, typ=typ)
python
{ "resource": "" }
q44767
Group.start_single
train
def start_single(self, typ, scol): """Start a new single""" self.starting_single = True single = self.single = Single(typ=typ, group=self, indent=(scol - self.level)) self.singles.append(single) return single
python
{ "resource": "" }
q44768
Group.modify_kls
train
def modify_kls(self, name): """Add a part to what will end up being the kls' superclass""" if self.kls is None: self.kls = name else: self.kls += name
python
{ "resource": "" }
q44769
Dwm.get_field_list
train
def get_field_list(self): """ Retrieve list of all fields currently configured """ list_out = [] for field in self.fields: list_out.append(field) return list_out
python
{ "resource": "" }
q44770
Dwm.data_lookup_method
train
def data_lookup_method(fields_list, mongo_db_obj, hist, record, lookup_type): """ Method to lookup the replacement value given a single input value from the same field. :param dict fields_list: Fields configurations :param MongoClient mongo_db_obj: MongoDB collection object :param dict hist: existing input of history values object :param dict record: values to validate :param str lookup_type: Type of lookup """ if hist is None: hist = {} for field in record: if record[field] != '' and record[field] is not None: if field in fields_list: if lookup_type in fields_list[field]['lookup']: field_val_new, hist = DataLookup( fieldVal=record[field], db=mongo_db_obj, lookupType=lookup_type, fieldName=field, histObj=hist) record[field] = field_val_new return record, hist
python
{ "resource": "" }
q44771
Dwm.data_regex_method
train
def data_regex_method(fields_list, mongo_db_obj, hist, record, lookup_type): """ Method to lookup the replacement value based on regular expressions. :param dict fields_list: Fields configurations :param MongoClient mongo_db_obj: MongoDB collection object :param dict hist: existing input of history values object :param dict record: values to validate :param str lookup_type: Type of lookup """ if hist is None: hist = {} for field in record: if record[field] != '' and record[field] is not None: if field in fields_list: if lookup_type in fields_list[field]['lookup']: field_val_new, hist = RegexLookup( fieldVal=record[field], db=mongo_db_obj, fieldName=field, lookupType=lookup_type, histObj=hist) record[field] = field_val_new return record, hist
python
{ "resource": "" }
q44772
Dwm._val_fs_regex
train
def _val_fs_regex(self, record, hist=None): """ Perform field-specific validation regex :param dict record: dictionary of values to validate :param dict hist: existing input of history values """ record, hist = self.data_regex_method(fields_list=self.fields, mongo_db_obj=self.mongo, hist=hist, record=record, lookup_type='fieldSpecificRegex') return record, hist
python
{ "resource": "" }
q44773
Dwm._norm_lookup
train
def _norm_lookup(self, record, hist=None): """ Perform generic validation lookup :param dict record: dictionary of values to validate :param dict hist: existing input of history values """ record, hist = self.data_lookup_method(fields_list=self.fields, mongo_db_obj=self.mongo, hist=hist, record=record, lookup_type='normLookup') return record, hist
python
{ "resource": "" }
q44774
Dwm._apply_udfs
train
def _apply_udfs(self, record, hist, udf_type): """ Excute user define processes, user-defined functionalty is designed to applyies custome trasformations to data. :param dict record: dictionary of values to validate :param dict hist: existing input of history values """ def function_executor(func, *args): """ Execute user define function :param python method func: Function obj :param methods arguments args: Function arguments """ result, result_hist = func(*args) return result, result_hist if udf_type in self.udfs: cust_function_od_obj = collections.OrderedDict( sorted( self.udfs[udf_type].items() ) ) for cust_function in cust_function_od_obj: record, hist = function_executor( cust_function_od_obj[cust_function], record, hist ) return record, hist
python
{ "resource": "" }
q44775
JSONFormMixin._get_field_error_dict
train
def _get_field_error_dict(self, field): '''Returns the dict containing the field errors information''' return { 'name': field.html_name, 'id': 'id_{}'.format(field.html_name), # This may be a problem 'errors': field.errors, }
python
{ "resource": "" }
q44776
JSONFormMixin.get_hidden_fields_errors
train
def get_hidden_fields_errors(self, form): '''Returns a dict to add in response when something is wrong with hidden fields''' if not self.include_hidden_fields or form.is_valid(): return {} response = {self.hidden_field_error_key:{}} for field in form.hidden_fields(): if field.errors: response[self.hidden_field_error_key][field.html_name] = self._get_field_error_dict(field) return response
python
{ "resource": "" }
q44777
JSONFormMixin.form_invalid
train
def form_invalid(self, form): '''Builds the JSON for the errors''' response = {self.errors_key: {}} response[self.non_field_errors_key] = form.non_field_errors() response.update(self.get_hidden_fields_errors(form)) for field in form.visible_fields(): if field.errors: response[self.errors_key][field.html_name] = self._get_field_error_dict(field) if self.include_success: response[self.sucess_key] = False return self._render_json(response)
python
{ "resource": "" }
q44778
VariablesManager.getAll
train
def getAll(self): '''Return a dictionary with all variables''' if not bool(len(self.ATTRIBUTES)): self.load_attributes() return eval(str(self.ATTRIBUTES))
python
{ "resource": "" }
q44779
VariablesManager.set
train
def set(self, name, default=0, editable=True, description=""): '''Define a variable in DB and in memory''' var, created = ConfigurationVariable.objects.get_or_create(name=name) if created: var.value = default if not editable: var.value = default var.editable = editable var.description = description var.save(reload=False) # ATTRIBUTES is accesible by any instance of VariablesManager self.ATTRIBUTES[var.name] = var.value
python
{ "resource": "" }
q44780
VariablesManager.load_attributes
train
def load_attributes(self): '''Read the variables from the VARS_MODULE_PATH''' try: vars_path = settings.VARS_MODULE_PATH except Exception: # logger.warning("*" * 55) logger.warning( " [WARNING] Using default VARS_MODULE_PATH = '{}'".format( VARS_MODULE_PATH_DEFAULT)) vars_path = VARS_MODULE_PATH_DEFAULT try: __import__(vars_path) except ImportError: logger.warning(" [WARNING] No module named '{}'".format( vars_path)) logger.warning(" Please, read the docs: goo.gl/E82vkX\n".format( vars_path))
python
{ "resource": "" }
q44781
ChoicesField.formfield
train
def formfield(self, form_class=None, choices_form_class=None, **kwargs): """ Returns a django.forms.Field instance for this database Field. """ defaults = { 'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text, } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() include_blank = (self.blank or not (self.has_default() or 'initial' in kwargs)) choices = [BLANK_CHOICE_DASH, ] if include_blank else [] choices.extend([ ( x.name, getattr(x, 'verbose_name', x.name) or x.name, getattr(x, 'help_text', None) or None ) for x in self.choices_class.constants() ]) defaults['choices'] = choices defaults['coerce'] = self.to_python if self.null: defaults['empty_value'] = None # Many of the subclass-specific formfield arguments (min_value, # max_value) don't apply for choice fields, so be sure to only pass # the values that TypedChoiceField will understand. for k in list(kwargs): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = choices_form_class or ChoicesFormField return form_class(**defaults)
python
{ "resource": "" }
q44782
URLAlias.get_bundle
train
def get_bundle(self, current_bundle, url_kwargs, context_kwargs): """ Returns the bundle to get the alias view from. If 'self.bundle_attr' is set, that bundle that it points to will be returned, otherwise the current_bundle will be returned. """ if self.bundle_attr: if self.bundle_attr == PARENT: return current_bundle.parent view, name = current_bundle.get_view_and_name(self.bundle_attr) return view return current_bundle
python
{ "resource": "" }
q44783
URLAlias.get_view_name
train
def get_view_name(self, requested): """ Returns the name of the view to lookup. If `requested` is equal to 'self.bundle_attr' then 'main' will be returned. Otherwise if `self.alias_to` is set the it's value will be returned. Otherwise the `requested` itself will be returned. """ value = self.alias_to and self.alias_to or requested if value == self.bundle_attr: return 'main' return value
python
{ "resource": "" }
q44784
Bundle.get_object_header_view
train
def get_object_header_view(self, request, url_kwargs, parent_only=False, render_type='object_header'): """ An object header is the title block of a CMS page. Actions to linked to in the header are based on this views bundle. This returns a view instance and view name of the view that should be rendered as an object header the view used is specified in `self.object_view`. If not match is found None, None is returned :param request: The request object :param url_kwargs: Any url keyword arguments as a dictionary :param parent_only: If `True` then the view will only \ be rendered if object_view points to parent. This is usually \ what you want to avoid extra lookups to get the object \ you already have. :param render_type: The render type to use for the header. \ Defaults to 'object_header'. """ if parent_only and self.object_view != self.parent_attr: return None, None if self.object_view == self.parent_attr and self.parent: return self.parent.get_object_header_view(request, url_kwargs, render_type=render_type) elif self.object_view: view, name = self.get_initialized_view_and_name(self.object_view, can_submit=False, base_template='cms/partial.html', request=request, kwargs=url_kwargs, render_type=render_type) if view and view.can_view(request.user): return view, name return None, None
python
{ "resource": "" }
q44785
Bundle.get_view_url
train
def get_view_url(self, view_name, user, url_kwargs=None, context_kwargs=None, follow_parent=True, check_permissions=True): """ Returns the url for a given view_name. If the view isn't found or the user does not have permission None is returned. A NoReverseMatch error may be raised if the view was unable to find the correct keyword arguments for the reverse function from the given url_kwargs and context_kwargs. :param view_name: The name of the view that you want. :param user: The user who is requesting the view :param url_kwargs: The url keyword arguments that came \ with the request object. The view itself is responsible \ to remove arguments that would not be part of a normal match \ for that view. This is done by calling the `get_url_kwargs` \ method on the view. :param context_kwargs: Extra arguments that will be passed \ to the view for consideration in the final keyword arguments \ for reverse. :param follow_parent: If we encounter a parent reference should \ we follow it. Defaults to True. :param check_permisions: Run permissions checks. Defaults to True. """ view, url_name = self.get_initialized_view_and_name(view_name, follow_parent=follow_parent) if isinstance(view, URLAlias): view_name = view.get_view_name(view_name) bundle = view.get_bundle(self, url_kwargs, context_kwargs) if bundle and isinstance(bundle, Bundle): return bundle.get_view_url(view_name, user, url_kwargs=url_kwargs, context_kwargs=context_kwargs, follow_parent=follow_parent, check_permissions=check_permissions) elif view: # Get kwargs from view if not url_kwargs: url_kwargs = {} url_kwargs = view.get_url_kwargs(context_kwargs, **url_kwargs) view.kwargs = url_kwargs if check_permissions and not view.can_view(user): return None url = reverse("admin:%s" % url_name, kwargs=url_kwargs) return url
python
{ "resource": "" }
q44786
Bundle.get_initialized_view_and_name
train
def get_initialized_view_and_name(self, view_name, follow_parent=True, **extra_kwargs): """ Creates and returns a new instance of a CMSView \ and it's url_name. :param view_name: The name of the view to return. :param follow_parent: If we encounter a parent reference should \ we follow it. Defaults to True. :param extra_kwargs: Keyword arguments to pass to the view. """ view, name = self.get_view_and_name(view_name) # Initialize the view with the right kwargs if hasattr(view, 'as_view'): e = dict(extra_kwargs) e.update(**self._get_view_kwargs(view, view_name)) e['name'] = view_name view = view(**e) # It is a Bundle return the main elif isinstance(view, Bundle): view, name = view.get_initialized_view_and_name('main', **extra_kwargs) elif view == self.parent_attr and self.parent: if follow_parent: return self.parent.get_initialized_view_and_name(view_name, **extra_kwargs) else: view = None name = None return view, name
python
{ "resource": "" }
q44787
Bundle.get_title
train
def get_title(self, plural=True): """ Get's the title of the bundle. Titles can be singular or plural. """ value = self.title if value == self.parent_attr: return self.parent.get_title(plural=plural) if not value and self._meta.model: value = helpers.model_name(self._meta.model, self._meta.custom_model_name, self._meta.custom_model_name_plural, plural) elif self.title and plural: value = helpers.pluralize(self.title, self.title_plural) return helpers.capfirst_if_needed(value)
python
{ "resource": "" }
q44788
Bundle.get_view_and_name
train
def get_view_and_name(self, attname): """ Gets a view or bundle and returns it and it's url_name. """ view = getattr(self, attname, None) if attname in self._children: view = self._get_bundle_from_promise(attname) if view: if attname in self._children: return view, view.name elif isinstance(view, ViewAlias): view_name = view.get_view_name(attname) bundle = view.get_bundle(self, {}, {}) if bundle and isinstance(bundle, Bundle): view, name = bundle.get_view_and_name(view_name) if hasattr(view, 'as_view'): if attname != 'main': name = "%s_%s" % (self.name, attname) else: name = self.name return view, name elif view == self.parent_attr and self.parent: return self.parent_attr, None elif isinstance(view, URLAlias): return view, None return None, None
python
{ "resource": "" }
q44789
Bundle.get_urls
train
def get_urls(self): """ Returns urls handling bundles and views. This processes the 'item view' first in order and then adds any non item views at the end. """ parts = [] seen = set() # Process item views in order for v in list(self._meta.item_views)+list(self._meta.action_views): if not v in seen: view, name = self.get_view_and_name(v) if view and name: parts.append(self.get_url(name, view, v)) seen.add(v) # Process everything else that we have not seen for v in set(self._views).difference(seen): # Get the url name view, name = self.get_view_and_name(v) if view and name: parts.append(self.get_url(name, view, v)) return parts
python
{ "resource": "" }
q44790
Bundle.as_subbundle
train
def as_subbundle(cls, name=None, title=None, title_plural=None): """ Wraps the given bundle so that it can be lazily instantiated. :param name: The slug for this bundle. :param title: The verbose name for this bundle. """ return PromiseBundle(cls, name=name, title=title, title_plural=title_plural)
python
{ "resource": "" }
q44791
Thumbnail._thumbnail_resize
train
def _thumbnail_resize(self, image, thumb_size, crop=None, bg=None): """Performs the actual image cropping operation with PIL.""" if crop == 'fit': img = ImageOps.fit(image, thumb_size, Image.ANTIALIAS) else: img = image.copy() img.thumbnail(thumb_size, Image.ANTIALIAS) if bg: img = self._bg_square(img, bg) return img
python
{ "resource": "" }
q44792
Thumbnail._thumbnail_local
train
def _thumbnail_local(self, original_filename, thumb_filename, thumb_size, thumb_url, crop=None, bg=None, quality=85): """Finds or creates a thumbnail for the specified image on the local filesystem.""" # create folders self._get_path(thumb_filename) thumb_url_full = url_for('static', filename=thumb_url) # Return the thumbnail URL now if it already exists locally if os.path.exists(thumb_filename): return thumb_url_full try: image = Image.open(original_filename) except IOError: return '' img = self._thumbnail_resize(image, thumb_size, crop=crop, bg=bg) img.save(thumb_filename, image.format, quality=quality) return thumb_url_full
python
{ "resource": "" }
q44793
Thumbnail._thumbnail_s3
train
def _thumbnail_s3(self, original_filename, thumb_filename, thumb_size, thumb_url, bucket_name, crop=None, bg=None, quality=85): """Finds or creates a thumbnail for the specified image on Amazon S3.""" scheme = self.app.config.get('THUMBNAIL_S3_USE_HTTPS') and 'https' or 'http' thumb_url_full = url_for_s3( 'static', bucket_name=self.app.config.get('THUMBNAIL_S3_BUCKET_NAME'), filename=thumb_url, scheme=scheme) original_url_full = url_for_s3( 'static', bucket_name=bucket_name, filename=self._get_s3_path(original_filename).replace('static/', ''), scheme=scheme) # Return the thumbnail URL now if it already exists on S3. # HTTP HEAD request saves us actually downloading the image # for this check. # Thanks to: # http://stackoverflow.com/a/16778749/2066849 try: resp = httplib2.Http().request(thumb_url_full, 'HEAD') resp_status = int(resp[0]['status']) assert(resp_status < 400) return thumb_url_full except Exception: pass # Thanks to: # http://stackoverflow.com/a/12020860/2066849 try: fd = urllib.urlopen(original_url_full) temp_file = BytesIO(fd.read()) image = Image.open(temp_file) except Exception: return '' img = self._thumbnail_resize(image, thumb_size, crop=crop, bg=bg) temp_file = BytesIO() img.save(temp_file, image.format, quality=quality) conn = S3Connection(self.app.config.get('THUMBNAIL_S3_ACCESS_KEY_ID'), self.app.config.get('THUMBNAIL_S3_ACCESS_KEY_SECRET')) bucket = conn.get_bucket(self.app.config.get('THUMBNAIL_S3_BUCKET_NAME')) path = self._get_s3_path(thumb_filename) k = bucket.new_key(path) try: k.set_contents_from_string(temp_file.getvalue()) k.set_acl(self.app.config.get('THUMBNAIL_S3_ACL', 'public-read')) except S3ResponseError: return '' return thumb_url_full
python
{ "resource": "" }
q44794
RenderResponse.update_kwargs
train
def update_kwargs(self, request, **kwargs): """ Hook for adding data to the context before rendering a template. :param kwargs: The current context keyword arguments. :param request: The current request object. """ if not 'base' in kwargs: kwargs['base'] = self.base if request.is_ajax() or request.GET.get('json'): kwargs['base'] = self.partial_base return kwargs
python
{ "resource": "" }
q44795
RenderResponse.render
train
def render(self, request, redirect_url=None, **kwargs): """ Uses `self.template` to render a response. :param request: The current request object. :param redirect_url: If given this will return the \ redirect method instead of rendering the normal template. \ Renders providing this argument are referred to as a \ 'render redirect' in this documentation. :param kwargs: The current context keyword arguments. """ if redirect_url: # Redirection is used when we click on `Save` for ordering # items on `ListView`. `kwargs` contains `message` but that # one is not passing through redirection. That's the reason for using # directly `messages` and get message on result template if kwargs.get('obj') is None: messages.success(request, kwargs.get('message')) return self.redirect(request, redirect_url, **kwargs) kwargs = self.update_kwargs(request, **kwargs) return render(request, self.template, kwargs)
python
{ "resource": "" }
q44796
CMSRender.update_kwargs
train
def update_kwargs(self, request, **kwargs): """ Adds variables to the context that are expected by the base cms templates. * **navigation** - The side navigation for this bundle and user. * **dashboard** - The list of dashboard links for this user. * **object_header** - If no 'object_header' was passed in the \ current context and the current bundle is set to get it's \ object_header from it's parent, this will get that view and render \ it as a string. Otherwise 'object_header will remain unset. * **subitem** - This is set to true if we rendered a new object_header \ and the object used to render that string is not present in the \ context args as 'obj'. This effects navigation and wording in the \ templates. """ kwargs = super(CMSRender, self).update_kwargs(request, **kwargs) # Check if we need to to include a separate object # bundle for the title bundle = kwargs.get('bundle') url_kwargs = kwargs.get('url_params') view = None if bundle: view, name = bundle.get_object_header_view(request, url_kwargs, parent_only=True) kwargs['dashboard'] = bundle.admin_site.get_dashboard_urls(request) if view: obj = view.get_object() if not 'object_header' in kwargs: kwargs['object_header'] = bundle._render_view_as_string(view, name, request, url_kwargs) if obj and obj != kwargs.get('obj'): kwargs['subitem'] = True return kwargs
python
{ "resource": "" }
q44797
ChoicesRender.get_different_page
train
def get_different_page(self, request, page): """ Returns a url that preserves the current querystring while changing the page requested to `page`. """ if page: qs = request.GET.copy() qs['page'] = page return "%s?%s" % (request.path_info, qs.urlencode()) return None
python
{ "resource": "" }
q44798
get
train
def get(url): """ USE json.net CONVENTIONS TO LINK TO INLINE OTHER JSON """ url = text_type(url) if url.find("://") == -1: Log.error("{{url}} must have a prototcol (eg http://) declared", url=url) base = URL("") if url.startswith("file://") and url[7] != "/": if os.sep=="\\": base = URL("file:///" + os.getcwd().replace(os.sep, "/").rstrip("/") + "/.") else: base = URL("file://" + os.getcwd().rstrip("/") + "/.") elif url[url.find("://") + 3] != "/": Log.error("{{url}} must be absolute", url=url) phase1 = _replace_ref(wrap({"$ref": url}), base) # BLANK URL ONLY WORKS IF url IS ABSOLUTE try: phase2 = _replace_locals(phase1, [phase1]) return wrap(phase2) except Exception as e: Log.error("problem replacing locals in\n{{phase1}}", phase1=phase1, cause=e)
python
{ "resource": "" }
q44799
expand
train
def expand(doc, doc_url="param://", params=None): """ ASSUMING YOU ALREADY PULED THE doc FROM doc_url, YOU CAN STILL USE THE EXPANDING FEATURE USE mo_json_config.expand({}) TO ASSUME CURRENT WORKING DIRECTORY :param doc: THE DATA STRUCTURE FROM JSON SOURCE :param doc_url: THE URL THIS doc CAME FROM (DEFAULT USES params AS A DOCUMENT SOURCE) :param params: EXTRA PARAMETERS NOT FOUND IN THE doc_url PARAMETERS (WILL SUPERSEDE PARAMETERS FROM doc_url) :return: EXPANDED JSON-SERIALIZABLE STRUCTURE """ if doc_url.find("://") == -1: Log.error("{{url}} must have a prototcol (eg http://) declared", url=doc_url) url = URL(doc_url) url.query = set_default(url.query, params) phase1 = _replace_ref(doc, url) # BLANK URL ONLY WORKS IF url IS ABSOLUTE phase2 = _replace_locals(phase1, [phase1]) return wrap(phase2)
python
{ "resource": "" }