Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def _initialize_random_state(self, seed=None, shared=True, name=None): if seed is None: # Equivalent to an uncontrolled seed. seed = random.Random().randint(0, 1000000) suffix = '' else: suffix = str(seed) ...
[ "\n Initialization method to be called in the constructor of\n subclasses to initialize the random state correctly.\n\n If seed is None, there is no control over the random stream\n (no reproducibility of the stream).\n\n If shared is True (and not time-dependent), the random stat...
Please provide a description of the function:def _verify_constrained_hash(self): changed_params = dict(self.param.get_param_values(onlychanged=True)) if self.time_dependent and ('name' not in changed_params): self.param.warning("Default object name used to set the seed: " ...
[ "\n Warn if the object name is not explicitly set.\n " ]
Please provide a description of the function:def _hash_and_seed(self): hashval = self._hashfn(self.time_fn(), param.random_seed) self.random_generator.seed(hashval)
[ "\n To be called between blocks of random number generation. A\n 'block' can be an unbounded sequence of random numbers so long\n as the time value (as returned by time_fn) is guaranteed not\n to change within the block. If this condition holds, each\n block of random numbers is t...
Please provide a description of the function:def get_setup_version(reponame): # importing self into setup.py is unorthodox, but param has no # required dependencies outside of python from param.version import Version return Version.setup_version(os.path.dirname(__file__),reponame,archive_commit="$F...
[ "Use autover to get up to date version." ]
Please provide a description of the function:def get_param_info(self, obj, include_super=True): params = dict(obj.param.objects('existing')) if isinstance(obj,type): changed = [] val_dict = dict((k,p.default) for (k,p) in params.items()) self_class = obj ...
[ "\n Get the parameter dictionary, the list of modifed parameters\n and the dictionary or parameter values. If include_super is\n True, parameters are also collected from the super classes.\n " ]
Please provide a description of the function:def param_docstrings(self, info, max_col_len=100, only_changed=False): (params, val_dict, changed) = info contents = [] displayed_params = {} for name, p in params.items(): if only_changed and not (name in changed): ...
[ "\n Build a string to that presents all of the parameter\n docstrings in a clean format (alternating red and blue for\n readability).\n " ]
Please provide a description of the function:def _build_table(self, info, order, max_col_len=40, only_changed=False): info_dict, bounds_dict = {}, {} (params, val_dict, changed) = info col_widths = dict((k,0) for k in order) for name, p in params.items(): if only_c...
[ "\n Collect the information about parameters needed to build a\n properly formatted table and then tabulate it.\n " ]
Please provide a description of the function:def _tabulate(self, info_dict, col_widths, changed, order, bounds_dict): contents, tail = [], [] column_set = set(k for row in info_dict.values() for k in row) columns = [col for col in order if col in column_set] title_row = [] ...
[ "\n Returns the supplied information as a table suitable for\n printing or paging.\n\n info_dict: Dictionary of the parameters name, type and mode.\n col_widths: Dictionary of column widths in characters\n changed: List of parameters modified from their defaults.\n orde...
Please provide a description of the function:def as_unicode(obj): if sys.version_info.major < 3 and isinstance(obj, str): obj = obj.decode('utf-8') return unicode(obj)
[ "\n Safely casts any object to unicode including regular string\n (i.e. bytes) types in python 2.\n " ]
Please provide a description of the function:def is_ordered_dict(d): py3_ordered_dicts = (sys.version_info.major == 3) and (sys.version_info.minor >= 6) vanilla_odicts = (sys.version_info.major > 3) or py3_ordered_dicts return isinstance(d, (OrderedDict))or (vanilla_odicts and isinstance(d, dict))
[ "\n Predicate checking for ordered dictionaries. OrderedDict is always\n ordered, and vanilla Python dictionaries are ordered for Python 3.6+\n " ]
Please provide a description of the function:def hashable(x): if isinstance(x, collections.MutableSequence): return tuple(x) elif isinstance(x, collections.MutableMapping): return tuple([(k,v) for k,v in x.items()]) else: return x
[ "\n Return a hashable version of the given object x, with lists and\n dictionaries converted to tuples. Allows mutable objects to be\n used as a lookup key in cases where the object has not actually\n been mutated. Lookup will fail (appropriately) in cases where some\n part of the object has changed...
Please provide a description of the function:def named_objs(objlist, namesdict=None): objs = OrderedDict() if namesdict is not None: objtoname = {hashable(v): k for k, v in namesdict.items()} for obj in objlist: if namesdict is not None and hashable(obj) in objtoname: k = ...
[ "\n Given a list of objects, returns a dictionary mapping from\n string name for the object to the object itself. Accepts\n an optional name,obj dictionary, which will override any other\n name if that item is present in the dictionary.\n " ]
Please provide a description of the function:def param_union(*parameterizeds, **kwargs): warn = kwargs.pop('warn', True) if len(kwargs): raise TypeError( "param_union() got an unexpected keyword argument '{}'".format( kwargs.popitem()[0])) d = dict() for o in par...
[ "\n Given a set of Parameterized objects, returns a dictionary\n with the union of all param name,value pairs across them.\n If warn is True (default), warns if the same parameter has\n been given multiple values; otherwise uses the last value\n " ]
Please provide a description of the function:def guess_param_types(**kwargs): params = {} for k, v in kwargs.items(): kws = dict(default=v, constant=True) if isinstance(v, Parameter): params[k] = v elif isinstance(v, dt_types): params[k] = Date(**kws) ...
[ "\n Given a set of keyword literals, promote to the appropriate\n parameter type based on some simple heuristics.\n " ]
Please provide a description of the function:def parameterized_class(name, params, bases=Parameterized): if not (isinstance(bases, list) or isinstance(bases, tuple)): bases=[bases] return type(name, tuple(bases), params)
[ "\n Dynamically create a parameterized class with the given name and the\n supplied parameters, inheriting from the specified base(s).\n " ]
Please provide a description of the function:def guess_bounds(params, **overrides): guessed = {} for name, p in params.items(): new_param = copy.copy(p) if isinstance(p, (Integer, Number)): if name in overrides: minv,maxv = overrides[name] else: ...
[ "\n Given a dictionary of Parameter instances, return a corresponding\n set of copies with the bounds appropriately set.\n\n\n If given a set of override keywords, use those numeric tuple bounds.\n " ]
Please provide a description of the function:def concrete_descendents(parentclass): return dict((c.__name__,c) for c in descendents(parentclass) if not _is_abstract(c))
[ "\n Return a dictionary containing all subclasses of the specified\n parentclass, including the parentclass. Only classes that are\n defined in scripts that have been run or modules that have been\n imported are included, so the caller will usually first do ``from\n package import *``.\n\n Only n...
Please provide a description of the function:def abbreviate_paths(pathspec,named_paths): from os.path import commonprefix, dirname, sep prefix = commonprefix([dirname(name)+sep for name in named_paths.keys()]+[pathspec]) return OrderedDict([(name[len(prefix):],path) for name,path in named_paths.items(...
[ "\n Given a dict of (pathname,path) pairs, removes any prefix shared by all pathnames.\n Helps keep menu items short yet unambiguous.\n " ]
Please provide a description of the function:def _initialize_generator(self,gen,obj=None): # CEBALERT: use a dictionary to hold these things. if hasattr(obj,"_Dynamic_time_fn"): gen._Dynamic_time_fn = obj._Dynamic_time_fn gen._Dynamic_last = None # CEB: I'd use None...
[ "\n Add 'last time' and 'last value' attributes to the generator.\n " ]
Please provide a description of the function:def _produce_value(self,gen,force=False): if hasattr(gen,"_Dynamic_time_fn"): time_fn = gen._Dynamic_time_fn else: time_fn = self.time_fn if (time_fn is None) or (not self.time_dependent): value = produce...
[ "\n Return a value from gen.\n\n If there is no time_fn, then a new value will be returned\n (i.e. gen will be asked to produce a new value).\n\n If force is True, or the value of time_fn() is different from\n what it was was last time produce_value was called, a new\n valu...
Please provide a description of the function:def _value_is_dynamic(self,obj,objtype=None): return hasattr(super(Dynamic,self).__get__(obj,objtype),'_Dynamic_last')
[ "\n Return True if the parameter is actually dynamic (i.e. the\n value is being generated).\n " ]
Please provide a description of the function:def _inspect(self,obj,objtype=None): gen=super(Dynamic,self).__get__(obj,objtype) if hasattr(gen,'_Dynamic_last'): return gen._Dynamic_last else: return gen
[ "Return the last generated value for this parameter." ]
Please provide a description of the function:def _force(self,obj,objtype=None): gen=super(Dynamic,self).__get__(obj,objtype) if hasattr(gen,'_Dynamic_last'): return self._produce_value(gen,force=True) else: return gen
[ "Force a new value to be generated, and return it." ]
Please provide a description of the function:def set_in_bounds(self,obj,val): if not callable(val): bounded_val = self.crop_to_bounds(val) else: bounded_val = val super(Number,self).__set__(obj,bounded_val)
[ "\n Set to the given value, but cropped to be within the legal bounds.\n All objects are accepted, and no exceptions will be raised. See\n crop_to_bounds for details on how cropping is done.\n " ]
Please provide a description of the function:def crop_to_bounds(self,val): # Currently, values outside the bounds are silently cropped to # be inside the bounds; it may be appropriate to add a warning # in such cases. if _is_number(val): if self.bounds is None: ...
[ "\n Return the given value cropped to be within the hard bounds\n for this parameter.\n\n If a numeric value is passed in, check it is within the hard\n bounds. If it is larger than the high bound, return the high\n bound. If it's smaller, return the low bound. In either case, the...
Please provide a description of the function:def _validate(self, val): if callable(val): return val if self.allow_None and val is None: return if not _is_number(val): raise ValueError("Parameter '%s' only takes numeric values"%(self.name)) ...
[ "\n Checks that the value is numeric and that it is within the hard\n bounds; if not, an exception is raised.\n " ]
Please provide a description of the function:def get_soft_bounds(self): if self.bounds is None: hl,hu=(None,None) else: hl,hu=self.bounds if self._softbounds is None: sl,su=(None,None) else: sl,su=self._softbounds if sl ...
[ "\n For each soft bound (upper and lower), if there is a defined bound (not equal to None)\n then it is returned, otherwise it defaults to the hard bound. The hard bound could still be None.\n " ]
Please provide a description of the function:def _validate(self, val): if not self.check_on_set: self._ensure_value_is_in_objects(val) return if not (val in self.objects or (self.allow_None and val is None)): # CEBALERT: can be called before __init__ has cal...
[ "\n val must be None or one of the objects in self.objects.\n " ]
Please provide a description of the function:def _ensure_value_is_in_objects(self,val): if not (val in self.objects): self.objects.append(val)
[ "\n Make sure that the provided value is present on the objects list.\n Subclasses can override if they support multiple items on a list,\n to check each item instead.\n " ]
Please provide a description of the function:def _validate(self,val): if isinstance(self.class_, tuple): class_name = ('(%s)' % ', '.join(cl.__name__ for cl in self.class_)) else: class_name = self.class_.__name__ if self.is_instance: if not (isinstan...
[ "val must be None, an instance of self.class_ if self.is_instance=True or a subclass of self_class if self.is_instance=False" ]
Please provide a description of the function:def get_range(self): classes = concrete_descendents(self.class_) d=OrderedDict((name,class_) for name,class_ in classes.items()) if self.allow_None: d['None']=None return d
[ "\n Return the possible types for this parameter's value.\n\n (I.e. return {name: <class>} for all classes that are\n concrete_descendents() of self.class_.)\n\n Only classes from modules that have been imported are added\n (see concrete_descendents()).\n " ]
Please provide a description of the function:def _validate(self, val): if self.allow_None and val is None: return if not isinstance(val, list): raise ValueError("List '%s' must be a list."%(self.name)) if self.bounds is not None: min_length,max_leng...
[ "\n Checks that the list is of the right length and has the right contents.\n Otherwise, an exception is raised.\n " ]
Please provide a description of the function:def _validate(self, val): if self.allow_None and val is None: return if not isinstance(val, dt_types) and not (self.allow_None and val is None): raise ValueError("Date '%s' only takes datetime types."%self.name) if s...
[ "\n Checks that the value is numeric and that it is within the hard\n bounds; if not, an exception is raised.\n " ]
Please provide a description of the function:def _validate(self, val): if self.allow_None and val is None: return super(Range, self)._validate(val) self._checkBounds(val)
[ "\n Checks that the value is numeric and that it is within the hard\n bounds; if not, an exception is raised.\n " ]
Please provide a description of the function:def logging_level(level): level = level.upper() levels = [DEBUG, INFO, WARNING, ERROR, CRITICAL, VERBOSE] level_names = ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL', 'VERBOSE'] if level not in level_names: raise Exception("Level %r not in %r...
[ "\n Temporarily modify param's logging level.\n " ]
Please provide a description of the function:def batch_watch(parameterized, run=True): BATCH_WATCH = parameterized.param._BATCH_WATCH parameterized.param._BATCH_WATCH = True try: yield finally: parameterized.param._BATCH_WATCH = BATCH_WATCH if run and not BATCH_WATCH: ...
[ "\n Context manager to batch watcher events on a parameterized object.\n The context manager will queue any events triggered by setting a\n parameter on the supplied parameterized object and dispatch them\n all at once when the context manager exits. If run=False the\n queued events are not dispatche...
Please provide a description of the function:def descendents(class_): assert isinstance(class_,type) q = [class_] out = [] while len(q): x = q.pop(0) out.insert(0,x) for b in x.__subclasses__(): if b not in q and b not in out: q.append(b) retu...
[ "\n Return a list of the class hierarchy below (and including) the given class.\n\n The list is ordered from least- to most-specific. Can be useful for\n printing the contents of an entire class hierarchy.\n " ]
Please provide a description of the function:def get_all_slots(class_): # A subclass's __slots__ attribute does not contain slots defined # in its superclass (the superclass' __slots__ end up as # attributes of the subclass). all_slots = [] parent_param_classes = [c for c in classlist(class_)[1...
[ "\n Return a list of slot names for slots defined in class_ and its\n superclasses.\n " ]
Please provide a description of the function:def get_occupied_slots(instance): return [slot for slot in get_all_slots(type(instance)) if hasattr(instance,slot)]
[ "\n Return a list of slots for which values have been set.\n\n (While a slot might be defined, if a value for that slot hasn't\n been set, then it's an AttributeError to request the slot's\n value.)\n " ]
Please provide a description of the function:def all_equal(arg1,arg2): if all(hasattr(el, '_infinitely_iterable') for el in [arg1,arg2]): return arg1==arg2 try: return all(a1 == a2 for a1, a2 in zip(arg1, arg2)) except TypeError: return arg1==arg2
[ "\n Return a single boolean for arg1==arg2, even for numpy arrays\n using element-wise comparison.\n\n Uses all(arg1==arg2) for sequences, and arg1==arg2 otherwise.\n\n If both objects have an '_infinitely_iterable' attribute, they are\n not be zipped together and are compared directly instead.\n ...
Please provide a description of the function:def depends(func, *dependencies, **kw): # python3 would allow kw-only args # (i.e. "func,*dependencies,watch=False" rather than **kw and the check below) watch = kw.pop("watch",False) assert len(kw)==0, "@depends accepts only 'watch' kw" # TODO: re...
[ "\n Annotates a Parameterized method to express its dependencies.\n The specified dependencies can be either be Parameters of this\n class, or Parameters of subobjects (Parameterized objects that\n are values of this object's parameters). Dependencies can either\n be on Parameter values, or on other...
Please provide a description of the function:def output(func, *output, **kw): if output: outputs = [] for i, out in enumerate(output): i = i if len(output) > 1 else None if isinstance(out, tuple) and len(out) == 2 and isinstance(out[0], str): outputs.appe...
[ "\n output allows annotating a method on a Parameterized class to\n declare that it returns an output of a specific type. The outputs\n of a Parameterized class can be queried using the\n Parameterized.param.outputs method. By default the output will\n inherit the method name but a custom name can be...
Please provide a description of the function:def as_uninitialized(fn): @wraps(fn) def override_initialization(self_,*args,**kw): parameterized_instance = self_.self original_initialized=parameterized_instance.initialized parameterized_instance.initialized=False fn(parameteri...
[ "\n Decorator: call fn with the parameterized_instance's\n initialization flag set to False, then revert the flag.\n\n (Used to decorate Parameterized methods that must alter\n a constant Parameter.)\n " ]
Please provide a description of the function:def script_repr(val,imports,prefix,settings): return pprint(val,imports,prefix,settings,unknown_value=None, qualify=True,separator="\n")
[ "\n Variant of repr() designed for generating a runnable script.\n\n Instances of types that require special handling can use the\n script_repr_reg dictionary. Using the type as a key, add a\n function that returns a suitable representation of instances of\n that type, and adds the required import st...
Please provide a description of the function:def pprint(val,imports, prefix="\n ", settings=[], unknown_value='<?>', qualify=False, separator=''): # CB: doc prefix & settings or realize they don't need to be # passed around, etc. # JLS: The settings argument is not used anywhere. To be re...
[ "\n (Experimental) Pretty printed representation of a parameterized\n object that may be evaluated with eval.\n\n Similar to repr except introspection of the constructor (__init__)\n ensures a valid and succinct representation is generated.\n\n Only parameters are represented (whether specified as st...
Please provide a description of the function:def print_all_param_defaults(): print("_______________________________________________________________________________") print("") print(" Parameter Default Values") print("") classes = descendents(Parameterized) classes...
[ "Print the default values for all imported Parameters." ]
Please provide a description of the function:def _setup_params(self_,**params): self = self_.param.self ## Deepcopy all 'instantiate=True' parameters # (build a set of names first to avoid redundantly instantiating # a later-overridden parent class's parameter) params_t...
[ "\n Initialize default and keyword parameter values.\n\n First, ensures that all Parameters with 'instantiate=True'\n (typically used for mutable Parameters) are copied directly\n into each object, to ensure that there is an independent copy\n (to avoid suprising aliasing errors)....
Please provide a description of the function:def deprecate(cls, fn): def inner(*args, **kwargs): if cls._disable_stubs: raise AssertionError('Stubs supporting old API disabled') elif cls._disable_stubs is None: pass elif cls._disable_s...
[ "\n Decorator to issue warnings for API moving onto the param\n namespace and to add a docstring directing people to the\n appropriate method.\n " ]
Please provide a description of the function:def print_param_defaults(self_): cls = self_.cls for key,val in cls.__dict__.items(): if isinstance(val,Parameter): print(cls.__name__+'.'+key+ '='+ repr(val.default))
[ "Print the default values of all cls's Parameters." ]
Please provide a description of the function:def set_default(self_,param_name,value): cls = self_.cls setattr(cls,param_name,value)
[ "\n Set the default value of param_name.\n\n Equivalent to setting param_name on the class.\n " ]
Please provide a description of the function:def _add_parameter(self_, param_name,param_obj): # CEBALERT: can't we just do # setattr(cls,param_name,param_obj)? The metaclass's # __setattr__ is actually written to handle that. (Would also # need to do something about the params...
[ "\n Add a new Parameter object into this object's class.\n\n Supposed to result in a Parameter equivalent to one declared\n in the class's source code.\n " ]
Please provide a description of the function:def params(self_, parameter_name=None): if self_.self is not None and self_.self._instance__params: self_.warning('The Parameterized instance has instance ' 'parameters created using new-style param ' ...
[ "\n Return the Parameters of this class as the\n dictionary {name: parameter_object}\n\n Includes Parameters from this class and its\n superclasses.\n " ]
Please provide a description of the function:def set_param(self_, *args,**kwargs): BATCH_WATCH = self_.self_or_cls.param._BATCH_WATCH self_.self_or_cls.param._BATCH_WATCH = True self_or_cls = self_.self_or_cls if args: if len(args) == 2 and not args[0] in kwargs and ...
[ "\n For each param=value keyword argument, sets the corresponding\n parameter of this object or class to the given value.\n\n For backwards compatibility, also accepts\n set_param(\"param\",value) for a single parameter value using\n positional arguments, but the keyword interface...
Please provide a description of the function:def objects(self_, instance=True): cls = self_.cls # CB: we cache the parameters because this method is called often, # and parameters are rarely added (and cannot be deleted) try: pdict = getattr(cls, '_%s__params' % cls....
[ "\n Returns the Parameters of this instance or class\n\n If instance=True and called on a Parameterized instance it\n will create instance parameters for all Parameters defined on\n the class. To force class parameters to be returned use\n instance=False. Since classes avoid creat...
Please provide a description of the function:def trigger(self_, *param_names): events = self_.self_or_cls.param._events watchers = self_.self_or_cls.param._watchers self_.self_or_cls.param._events = [] self_.self_or_cls.param._watchers = [] param_values = dict(self_.get...
[ "\n Trigger watchers for the given set of parameter names. Watchers\n will be triggered whether or not the parameter values have\n actually changed.\n " ]
Please provide a description of the function:def _update_event_type(self_, watcher, event, triggered): if triggered: event_type = 'triggered' else: event_type = 'changed' if watcher.onlychanged else 'set' return Event(what=event.what, name=event.name, obj=event.o...
[ "\n Returns an updated Event object with the type field set appropriately.\n " ]
Please provide a description of the function:def _call_watcher(self_, watcher, event): if self_.self_or_cls.param._TRIGGER: pass elif watcher.onlychanged and (not self_._changed(event)): return if self_.self_or_cls.param._BATCH_WATCH: self_._events.a...
[ "\n Invoke the given the watcher appropriately given a Event object.\n " ]
Please provide a description of the function:def _batch_call_watchers(self_): while self_.self_or_cls.param._events: event_dict = OrderedDict([((event.name, event.what), event) for event in self_.self_or_cls.param._events]) watchers = self_....
[ "\n Batch call a set of watchers based on the parameter value\n settings in kwargs using the queued Event and watcher objects.\n " ]
Please provide a description of the function:def set_dynamic_time_fn(self_,time_fn,sublistattr=None): self_or_cls = self_.self_or_cls self_or_cls._Dynamic_time_fn = time_fn if isinstance(self_or_cls,type): a = (None,self_or_cls) else: a = (self_or_cls,) ...
[ "\n Set time_fn for all Dynamic Parameters of this class or\n instance object that are currently being dynamically\n generated.\n\n Additionally, sets _Dynamic_time_fn=time_fn on this class or\n instance object, so that any future changes to Dynamic\n Parmeters can inherit ...
Please provide a description of the function:def get_param_values(self_,onlychanged=False): self_or_cls = self_.self_or_cls # CEB: we'd actually like to know whether a value has been # explicitly set on the instance, but I'm not sure that's easy # (would need to distinguish inst...
[ "\n Return a list of name,value pairs for all Parameters of this\n object.\n\n When called on an instance with onlychanged set to True, will\n only return values that are not equal to the default value\n (onlychanged has no effect when called on a class).\n " ]
Please provide a description of the function:def force_new_dynamic_value(self_, name): # pylint: disable-msg=E0213 cls_or_slf = self_.self_or_cls param_obj = cls_or_slf.param.objects('existing').get(name) if not param_obj: return getattr(cls_or_slf, name) cls, slf ...
[ "\n Force a new value to be generated for the dynamic attribute\n name, and return it.\n\n If name is not dynamic, its current value is returned\n (i.e. equivalent to getattr(name).\n " ]
Please provide a description of the function:def get_value_generator(self_,name): # pylint: disable-msg=E0213 cls_or_slf = self_.self_or_cls param_obj = cls_or_slf.param.objects('existing').get(name) if not param_obj: value = getattr(cls_or_slf,name) # CompositePar...
[ "\n Return the value or value-generating object of the named\n attribute.\n\n For most parameters, this is simply the parameter's value\n (i.e. the same as getattr()), but Dynamic parameters have\n their value-generating object returned.\n " ]
Please provide a description of the function:def inspect_value(self_,name): # pylint: disable-msg=E0213 cls_or_slf = self_.self_or_cls param_obj = cls_or_slf.param.objects('existing').get(name) if not param_obj: value = getattr(cls_or_slf,name) elif hasattr(param_ob...
[ "\n Return the current value of the named attribute without modifying it.\n\n Same as getattr() except for Dynamic parameters, which have their\n last generated value returned.\n " ]
Please provide a description of the function:def outputs(self_): outputs = {} for cls in classlist(self_.cls): for name in dir(cls): method = getattr(self_.self_or_cls, name) dinfo = getattr(method, '_dinfo', {}) if 'outputs' not in di...
[ "\n Returns a mapping between any declared outputs and a tuple\n of the declared Parameter type, the output method, and the\n index into the output if multiple outputs are returned.\n " ]
Please provide a description of the function:def unwatch(self_,watcher): try: self_._watch('remove',watcher) except: self_.warning('No such watcher {watcher} to remove.'.format(watcher=watcher))
[ "\n Unwatch watchers set either with watch or watch_values.\n " ]
Please provide a description of the function:def defaults(self_): self = self_.self d = {} for param_name,param in self.param.objects('existing').items(): if param.constant: pass elif param.instantiate: self.param._instantiate_para...
[ "\n Return {parameter_name:parameter.default} for all non-constant\n Parameters.\n\n Note that a Parameter for which instantiate==True has its default\n instantiated.\n " ]
Please provide a description of the function:def __db_print(self_,level,msg,*args,**kw): self_or_cls = self_.self_or_cls if get_logger(name=self_or_cls.name).isEnabledFor(level): if dbprint_prefix and callable(dbprint_prefix): msg = dbprint_prefix() + ": " + msg # ...
[ "\n Calls the logger returned by the get_logger() function,\n prepending the result of calling dbprint_prefix() (if any).\n\n See python's logging module for details.\n " ]
Please provide a description of the function:def print_param_values(self_): self = self_.self for name,val in self.param.get_param_values(): print('%s.%s = %s' % (self.name,name,val))
[ "Print the values of all this object's Parameters." ]
Please provide a description of the function:def warning(self_, msg,*args,**kw): if not warnings_as_exceptions: global warning_count warning_count+=1 self_.__db_print(WARNING,msg,*args,**kw) else: raise Exception("Warning: " + msg % args)
[ "\n Print msg merged with args as a warning, unless module variable\n warnings_as_exceptions is True, then raise an Exception\n containing the arguments.\n\n See Python's logging module for details of message formatting.\n " ]
Please provide a description of the function:def message(self_,msg,*args,**kw): self_.__db_print(INFO,msg,*args,**kw)
[ "\n Print msg merged with args as a message.\n\n See Python's logging module for details of message formatting.\n " ]
Please provide a description of the function:def verbose(self_,msg,*args,**kw): self_.__db_print(VERBOSE,msg,*args,**kw)
[ "\n Print msg merged with args as a verbose message.\n\n See Python's logging module for details of message formatting.\n " ]
Please provide a description of the function:def debug(self_,msg,*args,**kw): self_.__db_print(DEBUG,msg,*args,**kw)
[ "\n Print msg merged with args as a debugging statement.\n\n See Python's logging module for details of message formatting.\n " ]
Please provide a description of the function:def __class_docstring_signature(mcs, max_repr_len=15): processed_kws, keyword_groups = set(), [] for cls in reversed(mcs.mro()): keyword_group = [] for (k,v) in sorted(cls.__dict__.items()): if isinstance(v, Pa...
[ "\n Autogenerate a keyword signature in the class docstring for\n all available parameters. This is particularly useful in the\n IPython Notebook as IPython will parse this signature to allow\n tab-completion of keywords.\n\n max_repr_len: Maximum length (in characters) of value r...
Please provide a description of the function:def __param_inheritance(mcs,param_name,param): # get all relevant slots (i.e. slots defined in all # superclasses of this parameter) slots = {} for p_class in classlist(type(param))[1::]: slots.update(dict.fromkeys(p_class...
[ "\n Look for Parameter values in superclasses of this\n Parameterized class.\n\n Ordinarily, when a Python object is instantiated, attributes\n not given values in the constructor will inherit the value\n given in the object's class, or in its superclasses. For\n Parameter...
Please provide a description of the function:def get_param_descriptor(mcs,param_name): classes = classlist(mcs) for c in classes[::-1]: attribute = c.__dict__.get(param_name) if isinstance(attribute,Parameter): return attribute,c return None,None
[ "\n Goes up the class hierarchy (starting from the current class)\n looking for a Parameter class attribute param_name. As soon as\n one is found as a class attribute, that Parameter is returned\n along with the class in which it is declared.\n " ]
Please provide a description of the function:def param_keywords(self): return dict((key, self[key]) for key in self if key not in self.extra_keywords())
[ "\n Return a dictionary containing items from the originally\n supplied dict_ whose names are parameters of the\n overridden object (i.e. not extra keywords/parameters).\n " ]
Please provide a description of the function:def _check_params(self,params): overridden_object_params = list(self._overridden.param) for item in params: if item not in overridden_object_params: self.param.warning("'%s' will be ignored (not a Parameter).",item)
[ "\n Print a warning if params contains something that is not a\n Parameter of the overridden object.\n " ]
Please provide a description of the function:def _extract_extra_keywords(self,params): extra_keywords = {} overridden_object_params = list(self._overridden.param) for name, val in params.items(): if name not in overridden_object_params: extra_keywords[name]=v...
[ "\n Return any items in params that are not also\n parameters of the overridden object.\n " ]
Please provide a description of the function:def instance(self_or_cls,**params): if isinstance (self_or_cls,ParameterizedMetaclass): cls = self_or_cls else: p = params params = dict(self_or_cls.get_param_values()) params.update(p) par...
[ "\n Return an instance of this class, copying parameters from any\n existing instance provided.\n " ]
Please provide a description of the function:def script_repr(self,imports=[],prefix=" "): return self.pprint(imports,prefix,unknown_value='',qualify=True, separator="\n")
[ "\n Same as Parameterized.script_repr, except that X.classname(Y\n is replaced with X.classname.instance(Y\n " ]
Please provide a description of the function:def pprint(self, imports=None, prefix="\n ",unknown_value='<?>', qualify=False, separator=""): r = Parameterized.pprint(self,imports,prefix, unknown_value=unknown_value, qual...
[ "\n Same as Parameterized.pprint, except that X.classname(Y\n is replaced with X.classname.instance(Y\n " ]
Please provide a description of the function:def build_directory( sass_path, css_path, output_style='nested', _root_sass=None, _root_css=None, strip_extension=False, ): if _root_sass is None or _root_css is None: _root_sass = sass_path _root_css = css_path result = {} if not os....
[ "Compiles all Sass/SCSS files in ``path`` to CSS.\n\n :param sass_path: the path of the directory which contains source files\n to compile\n :type sass_path: :class:`str`, :class:`basestring`\n :param css_path: the path of the directory compiled CSS files will go\n :type css_path: :...
Please provide a description of the function:def resolve_filename(self, package_dir, filename): sass_path = os.path.join(package_dir, self.sass_path, filename) if self.strip_extension: filename, _ = os.path.splitext(filename) css_filename = filename + '.css' css_path...
[ "Gets a proper full relative path of Sass source and\n CSS source that will be generated, according to ``package_dir``\n and ``filename``.\n\n :param package_dir: the path of package directory\n :type package_dir: :class:`str`, :class:`basestring`\n :param filename: the filename o...
Please provide a description of the function:def unresolve_filename(self, package_dir, filename): filename, _ = os.path.splitext(filename) if self.strip_extension: for ext in ('.scss', '.sass'): test_path = os.path.join( package_dir, self.sass_pat...
[ "Retrieves the probable source path from the output filename. Pass\n in a .css path to get out a .scss path.\n\n :param package_dir: the path of the package directory\n :type package_dir: :class:`str`\n :param filename: the css filename\n :type filename: :class:`str`\n :re...
Please provide a description of the function:def build(self, package_dir, output_style='nested'): sass_path = os.path.join(package_dir, self.sass_path) css_path = os.path.join(package_dir, self.css_path) css_files = build_directory( sass_path, css_path, output_st...
[ "Builds the Sass/SCSS files in the specified :attr:`sass_path`.\n It finds :attr:`sass_path` and locates :attr:`css_path`\n as relative to the given ``package_dir``.\n\n :param package_dir: the path of package directory\n :type package_dir: :class:`str`, :class:`basestring`\n :par...
Please provide a description of the function:def build_one(self, package_dir, filename, source_map=False): sass_filename, css_filename = self.resolve_filename( package_dir, filename, ) root_path = os.path.join(package_dir, self.sass_path) css_path = os.path.join(pack...
[ "Builds one Sass/SCSS file.\n\n :param package_dir: the path of package directory\n :type package_dir: :class:`str`, :class:`basestring`\n :param filename: the filename of Sass/SCSS source to compile\n :type filename: :class:`str`, :class:`basestring`\n :param source_map: whether ...
Please provide a description of the function:def _validate_importers(importers): # They could have no importers, that's chill if importers is None: return None def _to_importer(priority, func): assert isinstance(priority, int), priority assert callable(func), func retur...
[ "Validates the importers and decorates the callables with our output\n formatter.\n " ]
Please provide a description of the function:def compile(**kwargs): r modes = set() for mode_name in MODES: if mode_name in kwargs: modes.add(mode_name) if not modes: raise TypeError('choose one at least in ' + and_join(MODES)) elif len(modes) > 1: raise TypeError...
[ "There are three modes of parameters :func:`compile()` can take:\n ``string``, ``filename``, and ``dirname``.\n\n The ``string`` parameter is the most basic way to compile Sass.\n It simply takes a string of Sass code, and then returns a compiled\n CSS string.\n\n :param string: Sass source code to c...
Please provide a description of the function:def and_join(strings): last = len(strings) - 1 if last == 0: return strings[0] elif last < 0: return '' iterator = enumerate(strings) return ', '.join('and ' + s if i == last else s for i, s in iterator)
[ "Join the given ``strings`` by commas with last `' and '` conjuction.\n\n >>> and_join(['Korea', 'Japan', 'China', 'Taiwan'])\n 'Korea, Japan, China, and Taiwan'\n\n :param strings: a list of words to join\n :type string: :class:`collections.abc.Sequence`\n :returns: a joined string\n :rtype: :cla...
Please provide a description of the function:def from_lambda(cls, name, lambda_): if PY2: # pragma: no cover a = inspect.getargspec(lambda_) varargs, varkw, defaults, kwonlyargs = ( a.varargs, a.keywords, a.defaults, None, ) else: # pragma: ...
[ "Make a :class:`SassFunction` object from the given ``lambda_``\n function. Since lambda functions don't have their name, it need\n its ``name`` as well. Arguments are automatically inspected.\n\n :param name: the function name\n :type name: :class:`str`\n :param lambda_: the ac...
Please provide a description of the function:def from_named_function(cls, function): if not getattr(function, '__name__', ''): raise TypeError('function must be named') return cls.from_lambda(function.__name__, function)
[ "Make a :class:`SassFunction` object from the named ``function``.\n Function name and arguments are automatically inspected.\n\n :param function: the named function to be called\n :type function: :class:`types.FunctionType`\n :returns: a custom function wrapper of the ``function``\n ...
Please provide a description of the function:def validate_manifests(dist, attr, value): try: Manifest.normalize_manifests(value) except TypeError: raise distutils.errors.DistutilsSetupError( attr + "must be a mapping object like: {'package.name': " "sassutils.distuti...
[ "Verifies that ``value`` is an expected mapping of package to\n :class:`sassutils.builder.Manifest`.\n\n " ]
Please provide a description of the function:def get_package_dir(self, package): path = package.split('.') if not self.package_dir: if path: return os.path.join(*path) return '' tail = [] while path: try: pdir =...
[ "Returns the directory, relative to the top of the source\n distribution, where package ``package`` should be found\n (at least according to the :attr:`package_dir` option, if any).\n\n Copied from :meth:`distutils.command.build_py.get_package_dir()`\n method.\n\n " ]
Please provide a description of the function:def allow_staff_or_superuser(func): is_object_permission = "has_object" in func.__name__ @wraps(func) def func_wrapper(*args, **kwargs): request = args[0] # use second parameter if object permission if is_object_permission: ...
[ "\n This decorator is used to abstract common is_staff and is_superuser functionality\n out of permission checks. It determines which parameter is the request based on name.\n " ]
Please provide a description of the function:def authenticated_users(func): is_object_permission = "has_object" in func.__name__ @wraps(func) def func_wrapper(*args, **kwargs): request = args[0] # use second parameter if object permission if is_object_permission: re...
[ "\n This decorator is used to abstract common authentication checking functionality\n out of permission checks. It determines which parameter is the request based on name.\n " ]
Please provide a description of the function:def filter_queryset(self, request, queryset, view): # Check if this is a list type request if view.lookup_field not in view.kwargs: if not self.action_routing: return self.filter_list_queryset(request, queryset, view) ...
[ "\n This method overrides the standard filter_queryset method.\n This method will check to see if the view calling this is from\n a list type action. This function will also route the filter\n by action type if action_routing is set to True.\n " ]
Please provide a description of the function:def has_permission(self, request, view): if not self.global_permissions: return True serializer_class = view.get_serializer_class() assert serializer_class.Meta.model is not None, ( "global_permissions set to true wi...
[ "\n Overrides the standard function and figures out methods to call for global permissions.\n " ]
Please provide a description of the function:def has_object_permission(self, request, view, obj): if not self.object_permissions: return True serializer_class = view.get_serializer_class() model_class = serializer_class.Meta.model action_method_name = None i...
[ "\n Overrides the standard function and figures out methods to call for object permissions.\n " ]
Please provide a description of the function:def _get_action(self, action): return_action = action if self.partial_update_is_update and action == 'partial_update': return_action = 'update' return return_action
[ "\n Utility function that consolidates actions if necessary.\n " ]
Please provide a description of the function:def _get_error_message(self, model_class, method_name, action_method_name): if action_method_name: return "'{}' does not have '{}' or '{}' defined.".format(model_class, method_name, action_method_name) else: return "'{}' does ...
[ "\n Get assertion error message depending if there are actions permissions methods defined.\n " ]