_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q9800
StoredInstance.invalidate
train
def invalidate(self, callback=True): # type: (bool) -> bool """ Applies the component invalidation. :param callback: If True, call back the component before the invalidation :return: False if the component wasn't valid """ with self._lock...
python
{ "resource": "" }
q9801
StoredInstance.validate
train
def validate(self, safe_callback=True): # type: (bool) -> bool """ Ends the component validation, registering services :param safe_callback: If True, calls the component validation callback :return: True if the component has been validated, else False :raise RuntimeError...
python
{ "resource": "" }
q9802
StoredInstance.__callback
train
def __callback(self, event, *args, **kwargs): # type: (str, *Any, **Any) -> Any """ Calls the registered method in the component for the given event :param event: An event (IPOPO_CALLBACK_VALIDATE, ...) :return: The callback result, or None :raise Exception: Something we...
python
{ "resource": "" }
q9803
StoredInstance.__field_callback
train
def __field_callback(self, field, event, *args, **kwargs): # type: (str, str, *Any, **Any) -> Any """ Calls the registered method in the component for the given field event :param field: A field name :param event: An event (IPOPO_CALLBACK_VALIDATE, ...) :return: The call...
python
{ "resource": "" }
q9804
StoredInstance.safe_callback
train
def safe_callback(self, event, *args, **kwargs): # type: (str, *Any, **Any) -> Any """ Calls the registered method in the component for the given event, ignoring raised exceptions :param event: An event (IPOPO_CALLBACK_VALIDATE, ...) :return: The callback result, or None...
python
{ "resource": "" }
q9805
StoredInstance.__safe_handler_callback
train
def __safe_handler_callback(self, handler, method_name, *args, **kwargs): # type: (Any, str, *Any, **Any) -> Any """ Calls the given method with the given arguments in the given handler. Logs exceptions, but doesn't propagate them. Special arguments can be given in kwargs: ...
python
{ "resource": "" }
q9806
StoredInstance.__safe_handlers_callback
train
def __safe_handlers_callback(self, method_name, *args, **kwargs): # type: (str, *Any, **Any) -> bool """ Calls the given method with the given arguments in all handlers. Logs exceptions, but doesn't propagate them. Methods called in handlers must return None, True or False. ...
python
{ "resource": "" }
q9807
StoredInstance.__set_binding
train
def __set_binding(self, dependency, service, reference): # type: (Any, Any, ServiceReference) -> None """ Injects a service in the component :param dependency: The dependency handler :param service: The injected service :param reference: The reference of the injected ser...
python
{ "resource": "" }
q9808
StoredInstance.__update_binding
train
def __update_binding( self, dependency, service, reference, old_properties, new_value ): # type: (Any, Any, ServiceReference, dict, bool) -> None """ Calls back component binding and field binding methods when the properties of an injected dependency have been updated. ...
python
{ "resource": "" }
q9809
StoredInstance.__unset_binding
train
def __unset_binding(self, dependency, service, reference): # type: (Any, Any, ServiceReference) -> None """ Removes a service from the component :param dependency: The dependency handler :param service: The injected service :param reference: The reference of the injected...
python
{ "resource": "" }
q9810
_parse_boolean
train
def _parse_boolean(value): """ Returns a boolean value corresponding to the given value. :param value: Any value :return: Its boolean value """ if not value: return False try: # Lower string to check known "false" value value = value.lower() return value not...
python
{ "resource": "" }
q9811
_VariableFilterMixIn._find_keys
train
def _find_keys(self): """ Looks for the property keys in the filter string :return: A list of property keys """ formatter = string.Formatter() return [ val[1] for val in formatter.parse(self._original_filter) if val[1] ]
python
{ "resource": "" }
q9812
_VariableFilterMixIn.update_filter
train
def update_filter(self): """ Update the filter according to the new properties :return: True if the filter changed, else False :raise ValueError: The filter is invalid """ # Consider the filter invalid self.valid_filter = False try: # Format ...
python
{ "resource": "" }
q9813
_VariableFilterMixIn.on_property_change
train
def on_property_change(self, name, old_value, new_value): # pylint: disable=W0613 """ A component property has been updated :param name: Name of the property :param old_value: Previous value of the property :param new_value: New value of the property """ ...
python
{ "resource": "" }
q9814
_VariableFilterMixIn._reset
train
def _reset(self): """ Called when the filter has been changed """ with self._lock: # Start listening to services with the new filter self.stop() self.start() for svc_ref in self.get_bindings(): # Check if the current refere...
python
{ "resource": "" }
q9815
EventData.set
train
def set(self, data=None): """ Sets the event """ self.__data = data self.__exception = None self.__event.set()
python
{ "resource": "" }
q9816
EventData.wait
train
def wait(self, timeout=None): """ Waits for the event or for the timeout :param timeout: Wait timeout (in seconds) :return: True if the event as been set, else False """ # The 'or' part is for Python 2.6 result = self.__event.wait(timeout) # pylint: disab...
python
{ "resource": "" }
q9817
FutureResult.__notify
train
def __notify(self): """ Notify the given callback about the result of the execution """ if self.__callback is not None: try: self.__callback( self._done_event.data, self._done_event.exception, self.__...
python
{ "resource": "" }
q9818
FutureResult.set_callback
train
def set_callback(self, method, extra=None): """ Sets a callback method, called once the result has been computed or in case of exception. The callback method must have the following signature: ``callback(result, exception, extra)``. :param method: The method to call bac...
python
{ "resource": "" }
q9819
ThreadPool.start
train
def start(self): """ Starts the thread pool. Does nothing if the pool is already started. """ if not self._done_event.is_set(): # Stop event not set: we're running return # Clear the stop event self._done_event.clear() # Compute the numbe...
python
{ "resource": "" }
q9820
ThreadPool.__start_thread
train
def __start_thread(self): """ Starts a new thread, if possible """ with self.__lock: if self.__nb_threads >= self._max_threads: # Can't create more threads return False if self._done_event.is_set(): # We're stopped:...
python
{ "resource": "" }
q9821
ThreadPool.stop
train
def stop(self): """ Stops the thread pool. Does nothing if the pool is already stopped. """ if self._done_event.is_set(): # Stop event set: we're stopped return # Set the stop event self._done_event.set() with self.__lock: # A...
python
{ "resource": "" }
q9822
ThreadPool.enqueue
train
def enqueue(self, method, *args, **kwargs): """ Queues a task in the pool :param method: Method to call :return: A FutureResult object, to get the result of the task :raise ValueError: Invalid method :raise Full: The task queue is full """ if not hasattr(...
python
{ "resource": "" }
q9823
ThreadPool.clear
train
def clear(self): """ Empties the current queue content. Returns once the queue have been emptied. """ with self.__lock: # Empty the current queue try: while True: self._queue.get_nowait() self._queue....
python
{ "resource": "" }
q9824
ThreadPool.join
train
def join(self, timeout=None): """ Waits for all the tasks to be executed :param timeout: Maximum time to wait (in seconds) :return: True if the queue has been emptied, else False """ if self._queue.empty(): # Nothing to wait for... return True ...
python
{ "resource": "" }
q9825
ThreadPool.__run
train
def __run(self): """ The main loop """ already_cleaned = False try: while not self._done_event.is_set(): try: # Wait for an action (blocking) task = self._queue.get(True, self._timeout) if tas...
python
{ "resource": "" }
q9826
docid
train
def docid(url, encoding='ascii'): """Get DocID from URL. DocID generation depends on bytes of the URL string. So, if non-ascii charactors in the URL, encoding should be considered properly. Args: url (str or bytes): Pre-encoded bytes or string will be encoded with the 'encoding...
python
{ "resource": "" }
q9827
sanitize_html
train
def sanitize_html(value, valid_tags=VALID_TAGS, strip=True): """ Strips unwanted markup out of HTML. """ return bleach.clean(value, tags=list(VALID_TAGS.keys()), attributes=VALID_TAGS, strip=strip)
python
{ "resource": "" }
q9828
deobfuscate_email
train
def deobfuscate_email(text): """ Deobfuscate email addresses in provided text """ text = unescape(text) # Find the "dot" text = _deobfuscate_dot1_re.sub('.', text) text = _deobfuscate_dot2_re.sub(r'\1.\2', text) text = _deobfuscate_dot3_re.sub(r'\1.\2', text) # Find the "at" text...
python
{ "resource": "" }
q9829
simplify_text
train
def simplify_text(text): """ Simplify text to allow comparison. >>> simplify_text("Awesome Coder wanted at Awesome Company") 'awesome coder wanted at awesome company' >>> simplify_text("Awesome Coder, wanted at Awesome Company! ") 'awesome coder wanted at awesome company' >>> simplify_text...
python
{ "resource": "" }
q9830
dropdb
train
def dropdb(): """Drop database tables""" manager.db.engine.echo = True if prompt_bool("Are you sure you want to lose all your data"): manager.db.drop_all() metadata, alembic_version = alembic_table_metadata() alembic_version.drop() manager.db.session.commit()
python
{ "resource": "" }
q9831
createdb
train
def createdb(): """Create database tables from sqlalchemy models""" manager.db.engine.echo = True manager.db.create_all() set_alembic_revision()
python
{ "resource": "" }
q9832
sync_resources
train
def sync_resources(): """Sync the client's resources with the Lastuser server""" print("Syncing resources with Lastuser...") resources = manager.app.lastuser.sync_resources()['results'] for rname, resource in six.iteritems(resources): if resource['status'] == 'error': print("Error f...
python
{ "resource": "" }
q9833
load_config_from_file
train
def load_config_from_file(app, filepath): """Helper function to load config from a specified file""" try: app.config.from_pyfile(filepath) return True except IOError: # TODO: Can we print to sys.stderr in production? Should this go to # logs instead? print("Did not fi...
python
{ "resource": "" }
q9834
IdMixin.id
train
def id(cls): """ Database identity for this model, used for foreign key references from other models """ if cls.__uuid_primary_key__: return immutable(Column(UUIDType(binary=False), default=uuid_.uuid4, primary_key=True, nullable=False)) else: return immut...
python
{ "resource": "" }
q9835
IdMixin.url_id
train
def url_id(cls): """The URL id""" if cls.__uuid_primary_key__: def url_id_func(self): """The URL id, UUID primary key rendered as a hex string""" return self.id.hex def url_id_is(cls): return SqlHexUuidComparator(cls.id) ...
python
{ "resource": "" }
q9836
UrlForMixin.register_view_for
train
def register_view_for(cls, app, action, classview, attr): """ Register a classview and viewhandler for a given app and action """ if 'view_for_endpoints' not in cls.__dict__: cls.view_for_endpoints = {} cls.view_for_endpoints.setdefault(app, {})[action] = (classview, ...
python
{ "resource": "" }
q9837
UrlForMixin.view_for
train
def view_for(self, action='view'): """ Return the classview viewhandler that handles the specified action """ app = current_app._get_current_object() view, attr = self.view_for_endpoints[app][action] return getattr(view(self), attr)
python
{ "resource": "" }
q9838
UrlForMixin.classview_for
train
def classview_for(self, action='view'): """ Return the classview that contains the viewhandler for the specified action """ app = current_app._get_current_object() return self.view_for_endpoints[app][action][0](self)
python
{ "resource": "" }
q9839
BaseNameMixin.name
train
def name(cls): """The URL name of this object, unique across all instances of this model""" if cls.__name_length__ is None: column_type = UnicodeText() else: column_type = Unicode(cls.__name_length__) if cls.__name_blank_allowed__: return Column(column...
python
{ "resource": "" }
q9840
BaseNameMixin.title
train
def title(cls): """The title of this object""" if cls.__title_length__ is None: column_type = UnicodeText() else: column_type = Unicode(cls.__title_length__) return Column(column_type, nullable=False)
python
{ "resource": "" }
q9841
BaseNameMixin.upsert
train
def upsert(cls, name, **fields): """Insert or update an instance""" instance = cls.get(name) if instance: instance._set_fields(fields) else: instance = cls(name=name, **fields) instance = failsafe_add(cls.query.session, instance, name=name) ret...
python
{ "resource": "" }
q9842
BaseScopedNameMixin.get
train
def get(cls, parent, name): """Get an instance matching the parent and name""" return cls.query.filter_by(parent=parent, name=name).one_or_none()
python
{ "resource": "" }
q9843
BaseScopedNameMixin.short_title
train
def short_title(self): """ Generates an abbreviated title by subtracting the parent's title from this instance's title. """ if self.title and self.parent is not None and hasattr(self.parent, 'title') and self.parent.title: if self.title.startswith(self.parent.title): ...
python
{ "resource": "" }
q9844
BaseScopedNameMixin.permissions
train
def permissions(self, actor, inherited=None): """ Permissions for this model, plus permissions inherited from the parent. """ if inherited is not None: return inherited | super(BaseScopedNameMixin, self).permissions(actor) elif self.parent is not None and isinstance(s...
python
{ "resource": "" }
q9845
BaseScopedIdMixin.get
train
def get(cls, parent, url_id): """Get an instance matching the parent and url_id""" return cls.query.filter_by(parent=parent, url_id=url_id).one_or_none()
python
{ "resource": "" }
q9846
BaseScopedIdMixin.make_id
train
def make_id(self): """Create a new URL id that is unique to the parent container""" if self.url_id is None: # Set id only if empty self.url_id = select([func.coalesce(func.max(self.__class__.url_id + 1), 1)], self.__class__.parent == self.parent)
python
{ "resource": "" }
q9847
make_timestamp_columns
train
def make_timestamp_columns(): """Return two columns, created_at and updated_at, with appropriate defaults""" return ( Column('created_at', DateTime, default=func.utcnow(), nullable=False), Column('updated_at', DateTime, default=func.utcnow(), onupdate=func.utcnow(), nullable=False), )
python
{ "resource": "" }
q9848
auto_init_default
train
def auto_init_default(column): """ Set the default value for a column when it's first accessed rather than first committed to the database. """ if isinstance(column, ColumnProperty): default = column.columns[0].default else: default = column.default @event.listens_for(column...
python
{ "resource": "" }
q9849
load_model
train
def load_model(model, attributes=None, parameter=None, kwargs=False, permission=None, addlperms=None, urlcheck=[]): """ Decorator to load a model given a query parameter. Typical usage:: @app.route('/<profile>') @load_model(Profile, {'name': 'profile'}, 'profileob') def pro...
python
{ "resource": "" }
q9850
dict_jsonify
train
def dict_jsonify(param): """Convert the parameter into a dictionary before calling jsonify, if it's not already one""" if not isinstance(param, dict): param = dict(param) return jsonify(param)
python
{ "resource": "" }
q9851
dict_jsonp
train
def dict_jsonp(param): """Convert the parameter into a dictionary before calling jsonp, if it's not already one""" if not isinstance(param, dict): param = dict(param) return jsonp(param)
python
{ "resource": "" }
q9852
cors
train
def cors(origins, methods=['HEAD', 'OPTIONS', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE'], headers=['Accept', 'Accept-Language', 'Content-Language', 'Content-Type', 'X-Requested-With'], max_age=None): """ Adds CORS headers to the decorated view function. :param origins: Allowed origins...
python
{ "resource": "" }
q9853
requires_permission
train
def requires_permission(permission): """ View decorator that requires a certain permission to be present in ``current_auth.permissions`` before the view is allowed to proceed. Aborts with ``403 Forbidden`` if the permission is not present. The decorated view will have an ``is_available`` method tha...
python
{ "resource": "" }
q9854
uuid1mc_from_datetime
train
def uuid1mc_from_datetime(dt): """ Return a UUID1 with a random multicast MAC id and with a timestamp matching the given datetime object or timestamp value. .. warning:: This function does not consider the timezone, and is not guaranteed to return a unique UUID. Use under controlled con...
python
{ "resource": "" }
q9855
uuid2buid
train
def uuid2buid(value): """ Convert a UUID object to a 22-char BUID string >>> u = uuid.UUID('33203dd2-f2ef-422f-aeb0-058d6f5f7089') >>> uuid2buid(u) 'MyA90vLvQi-usAWNb19wiQ' """ if six.PY3: # pragma: no cover return urlsafe_b64encode(value.bytes).decode('utf-8').rstrip('=') else...
python
{ "resource": "" }
q9856
newpin
train
def newpin(digits=4): """ Return a random numeric string with the specified number of digits, default 4. >>> len(newpin()) 4 >>> len(newpin(5)) 5 >>> newpin().isdigit() True """ randnum = randint(0, 10 ** digits) while len(str(randnum)) > digits: randnum = randin...
python
{ "resource": "" }
q9857
make_name
train
def make_name(text, delim=u'-', maxlength=50, checkused=None, counter=2): u""" Generate an ASCII name slug. If a checkused filter is provided, it will be called with the candidate. If it returns True, make_name will add counter numbers starting from 2 until a suitable candidate is found. :param str...
python
{ "resource": "" }
q9858
check_password
train
def check_password(reference, attempt): """ Compare a reference password with the user attempt. >>> check_password('{PLAIN}foo', 'foo') True >>> check_password(u'{PLAIN}bar', 'bar') True >>> check_password(u'{UNKNOWN}baz', 'baz') False >>> check_password(u'no-encoding', u'no-encodin...
python
{ "resource": "" }
q9859
format_currency
train
def format_currency(value, decimals=2): """ Return a number suitably formatted for display as currency, with thousands separated by commas and up to two decimal points. >>> format_currency(1000) '1,000' >>> format_currency(100) '100' >>> format_currency(999.95) '999.95' >>> form...
python
{ "resource": "" }
q9860
md5sum
train
def md5sum(data): """ Return md5sum of data as a 32-character string. >>> md5sum('random text') 'd9b9bec3f4cc5482e7c5ef43143e563a' >>> md5sum(u'random text') 'd9b9bec3f4cc5482e7c5ef43143e563a' >>> len(md5sum('random text')) 32 """ if six.PY3: # pragma: no cover return h...
python
{ "resource": "" }
q9861
midnight_to_utc
train
def midnight_to_utc(dt, timezone=None, naive=False): """ Returns a UTC datetime matching the midnight for the given date or datetime. >>> from datetime import date >>> midnight_to_utc(datetime(2017, 1, 1)) datetime.datetime(2017, 1, 1, 0, 0, tzinfo=<UTC>) >>> midnight_to_utc(pytz.timezone('Asia...
python
{ "resource": "" }
q9862
getbool
train
def getbool(value): """ Returns a boolean from any of a range of values. Returns None for unrecognized values. Numbers other than 0 and 1 are considered unrecognized. >>> getbool(True) True >>> getbool(1) True >>> getbool('1') True >>> getbool('t') True >>> getbool(2...
python
{ "resource": "" }
q9863
unicode_http_header
train
def unicode_http_header(value): r""" Convert an ASCII HTTP header string into a unicode string with the appropriate encoding applied. Expects headers to be RFC 2047 compliant. >>> unicode_http_header('=?iso-8859-1?q?p=F6stal?=') == u'p\xf6stal' True >>> unicode_http_header(b'=?iso-8859-1?q?p=F6...
python
{ "resource": "" }
q9864
get_email_domain
train
def get_email_domain(emailaddr): """ Return the domain component of an email address. Returns None if the provided string cannot be parsed as an email address. >>> get_email_domain('test@example.com') 'example.com' >>> get_email_domain('test+trailing@example.com') 'example.com' >>> get_...
python
{ "resource": "" }
q9865
sorted_timezones
train
def sorted_timezones(): """ Return a list of timezones sorted by offset from UTC. """ def hourmin(delta): if delta.days < 0: hours, remaining = divmod(86400 - delta.seconds, 3600) else: hours, remaining = divmod(delta.seconds, 3600) minutes, remaining = di...
python
{ "resource": "" }
q9866
namespace_from_url
train
def namespace_from_url(url): """ Construct a dotted namespace string from a URL. """ parsed = urlparse(url) if parsed.hostname is None or parsed.hostname in ['localhost', 'localhost.localdomain'] or ( _ipv4_re.search(parsed.hostname)): return None namespace = parsed.hostname...
python
{ "resource": "" }
q9867
base_domain_matches
train
def base_domain_matches(d1, d2): """ Check if two domains have the same base domain, using the Public Suffix List. >>> base_domain_matches('https://hasjob.co', 'hasjob.co') True >>> base_domain_matches('hasgeek.hasjob.co', 'hasjob.co') True >>> base_domain_matches('hasgeek.com', 'hasjob.co'...
python
{ "resource": "" }
q9868
MarkdownColumn
train
def MarkdownColumn(name, deferred=False, group=None, **kwargs): """ Create a composite column that autogenerates HTML from Markdown text, storing data in db columns named with ``_html`` and ``_text`` prefixes. """ return composite(MarkdownComposite, Column(name + '_text', UnicodeText, **kwar...
python
{ "resource": "" }
q9869
VersionedAssets.require
train
def require(self, *namespecs): """Return a bundle of the requested assets and their dependencies.""" blacklist = set([n[1:] for n in namespecs if n.startswith('!')]) not_blacklist = [n for n in namespecs if not n.startswith('!')] return Bundle(*[bundle for name, version, bundle ...
python
{ "resource": "" }
q9870
StateTransitionWrapper._state_invalid
train
def _state_invalid(self): """ If the state is invalid for the transition, return details on what didn't match :return: Tuple of (state manager, current state, label for current state) """ for statemanager, conditions in self.statetransition.transitions.items(): curre...
python
{ "resource": "" }
q9871
StateManager.add_conditional_state
train
def add_conditional_state(self, name, state, validator, class_validator=None, cache_for=None, label=None): """ Add a conditional state that combines an existing state with a validator that must also pass. The validator receives the object on which the property is present as a parameter. ...
python
{ "resource": "" }
q9872
StateManager.requires
train
def requires(self, from_, if_=None, **data): """ Decorates a method that may be called if the given state is currently active. Registers a transition internally, but does not change the state. :param from_: Required state to allow this call (can be a state group) :param if_: Val...
python
{ "resource": "" }
q9873
StateManagerWrapper.current
train
def current(self): """ All states and state groups that are currently active. """ if self.obj is not None: return {name: mstate(self.obj, self.cls) for name, mstate in self.statemanager.states.items() if mstate(self.obj, self.cls)}
python
{ "resource": "" }
q9874
gfm
train
def gfm(text): """ Prepare text for rendering by a regular Markdown processor. """ def indent_code(matchobj): syntax = matchobj.group(1) code = matchobj.group(2) if syntax: result = ' :::' + syntax + '\n' else: result = '' # The last lin...
python
{ "resource": "" }
q9875
markdown
train
def markdown(text, html=False, valid_tags=GFM_TAGS): """ Return Markdown rendered text using GitHub Flavoured Markdown, with HTML escaped and syntax-highlighting enabled. """ if text is None: return None if html: return Markup(sanitize_html(markdown_convert_html(gfm(text)), valid...
python
{ "resource": "" }
q9876
ViewHandlerWrapper.is_available
train
def is_available(self): """Indicates whether this view is available in the current context""" if hasattr(self._viewh.wrapped_func, 'is_available'): return self._viewh.wrapped_func.is_available(self._obj) return True
python
{ "resource": "" }
q9877
get_current_url
train
def get_current_url(): """ Return the current URL including the query string as a relative path. If the app uses subdomains, return an absolute path """ if current_app.config.get('SERVER_NAME') and ( # Check current hostname against server name, ignoring port numbers, if any (split on ':...
python
{ "resource": "" }
q9878
get_next_url
train
def get_next_url(referrer=False, external=False, session=False, default=__marker): """ Get the next URL to redirect to. Don't return external URLs unless explicitly asked for. This is to protect the site from being an unwitting redirector to external URLs. Subdomains are okay, however. This functio...
python
{ "resource": "" }
q9879
annotation_wrapper
train
def annotation_wrapper(annotation, doc=None): """ Defines an annotation, which can be applied to attributes in a database model. """ def decorator(attr): __cache__.setdefault(attr, []).append(annotation) # Also mark the annotation on the object itself. This will # fail if the obj...
python
{ "resource": "" }
q9880
SchemaMeta.build_attributes
train
def build_attributes(cls, attributes, namespace): """Return an attributes dictionary with ValueTokens replaced by a property which returns the config value. """ config_path = attributes.get('config_path') tokens = {} def build_config_key(value_def, config_key): ...
python
{ "resource": "" }
q9881
cache_as_field
train
def cache_as_field(cache_name): """Cache a functions return value as the field 'cache_name'.""" def cache_wrapper(func): @functools.wraps(func) def inner_wrapper(self, *args, **kwargs): value = getattr(self, cache_name, UndefToken) if value != UndefToken: ...
python
{ "resource": "" }
q9882
extract_value
train
def extract_value(proxy): """Given a value proxy type, Retrieve a value from a namespace, raising exception if no value is found, or the value does not validate. """ value = proxy.namespace.get(proxy.config_key, proxy.default) if value is UndefToken: raise errors.ConfigurationError("%s is mi...
python
{ "resource": "" }
q9883
build_reader
train
def build_reader(validator, reader_namespace=config.DEFAULT): """A factory method for creating a custom config reader from a validation function. :param validator: a validation function which acceptance one argument (the configuration value), and returns that value casted to ...
python
{ "resource": "" }
q9884
get_namespaces_from_names
train
def get_namespaces_from_names(name, all_names): """Return a generator which yields namespace objects.""" names = configuration_namespaces.keys() if all_names else [name] for name in names: yield get_namespace(name)
python
{ "resource": "" }
q9885
validate
train
def validate(name=DEFAULT, all_names=False): """Validate all registered keys after loading configuration. Missing values or values which do not pass validation raise :class:`staticconf.errors.ConfigurationError`. By default only validates the `DEFAULT` namespace. :param name: the namespace to vali...
python
{ "resource": "" }
q9886
has_duplicate_keys
train
def has_duplicate_keys(config_data, base_conf, raise_error): """Compare two dictionaries for duplicate keys. if raise_error is True then raise on exception, otherwise log return True.""" duplicate_keys = set(base_conf) & set(config_data) if not duplicate_keys: return msg = "Duplicate keys in...
python
{ "resource": "" }
q9887
build_compare_func
train
def build_compare_func(err_logger=None): """Returns a compare_func that can be passed to MTimeComparator. The returned compare_func first tries os.path.getmtime(filename), then calls err_logger(filename) if that fails. If err_logger is None, then it does nothing. err_logger is always called within the ...
python
{ "resource": "" }
q9888
ConfigNamespace.get_config_dict
train
def get_config_dict(self): """Reconstruct the nested structure of this object's configuration and return it as a dict. """ config_dict = {} for dotted_key, value in self.get_config_values().items(): subkeys = dotted_key.split('.') d = config_dict ...
python
{ "resource": "" }
q9889
ConfigHelp.view_help
train
def view_help(self): """Return a help message describing all the statically configured keys. """ def format_desc(desc): return "%s (Type: %s, Default: %s)\n%s" % ( desc.name, desc.validator.__name__.replace('validate_', ''), ...
python
{ "resource": "" }
q9890
_validate_iterable
train
def _validate_iterable(iterable_type, value): """Convert the iterable to iterable_type, or raise a Configuration exception. """ if isinstance(value, six.string_types): msg = "Invalid iterable of type(%s): %s" raise ValidationError(msg % (type(value), value)) try: return iter...
python
{ "resource": "" }
q9891
build_list_type_validator
train
def build_list_type_validator(item_validator): """Return a function which validates that the value is a list of items which are validated using item_validator. """ def validate_list_of_type(value): return [item_validator(item) for item in validate_list(value)] return validate_list_of_type
python
{ "resource": "" }
q9892
build_map_type_validator
train
def build_map_type_validator(item_validator): """Return a function which validates that the value is a mapping of items. The function should return pairs of items that will be passed to the `dict` constructor. """ def validate_mapping(value): return dict(item_validator(item) for item in vali...
python
{ "resource": "" }
q9893
register_value_proxy
train
def register_value_proxy(namespace, value_proxy, help_text): """Register a value proxy with the namespace, and add the help_text.""" namespace.register_proxy(value_proxy) config.config_help.add( value_proxy.config_key, value_proxy.validator, value_proxy.default, namespace.get_name(), help_te...
python
{ "resource": "" }
q9894
build_getter
train
def build_getter(validator, getter_namespace=None): """Create a getter function for retrieving values from the config cache. Getters will default to the DEFAULT namespace. """ def proxy_register(key_name, default=UndefToken, help=None, namespace=None): name = namespace or getter_namespace...
python
{ "resource": "" }
q9895
ProxyFactory.build
train
def build(self, validator, namespace, config_key, default, help): """Build or retrieve a ValueProxy from the attributes. Proxies are keyed using a repr because default values can be mutable types. """ proxy_attrs = validator, namespace, config_key, default proxy_key = repr(proxy_...
python
{ "resource": "" }
q9896
minimizeSPSA
train
def minimizeSPSA(func, x0, args=(), bounds=None, niter=100, paired=True, a=1.0, alpha=0.602, c=1.0, gamma=0.101, disp=False, callback=None): """ Minimization of an objective function by a simultaneous perturbation stochastic approximation algorithm. This algorithm appr...
python
{ "resource": "" }
q9897
bisect
train
def bisect(func, a, b, xtol=1e-6, errorcontrol=True, testkwargs=dict(), outside='extrapolate', ascending=None, disp=False): """Find root by bysection search. If the function evaluation is noisy then use `errorcontrol=True` for adaptive sampling of the function during the bi...
python
{ "resource": "" }
q9898
AveragedFunction.diffse
train
def diffse(self, x1, x2): """Standard error of the difference between the function values at x1 and x2""" f1, f1se = self(x1) f2, f2se = self(x2) if self.paired: fx1 = np.array(self.cache[tuple(x1)]) fx2 = np.array(self.cache[tuple(x2)]) diffse = np.s...
python
{ "resource": "" }
q9899
alphanum_order
train
def alphanum_order(triples): """ Sort a list of triples by relation name. Embedded integers are sorted numerically, but otherwise the sorting is alphabetic. """ return sorted( triples, key=lambda t: [ int(t) if t.isdigit() else t for t in re.split(r'([0-9...
python
{ "resource": "" }