_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: if self.state != StoredInstance.VALID: # Instance is not running... return False # Change the state self.state = StoredInstance.INVALID # Call the handlers self.__safe_handlers_callback("pre_invalidate") # Call the component if callback: # pylint: disable=W0212 self.__safe_validation_callback( constants.IPOPO_CALLBACK_INVALIDATE ) # Trigger an "Invalidated" event self._ipopo_service._fire_ipopo_event( constants.IPopoEvent.INVALIDATED, self.factory_name, self.name, ) # Call the handlers self.__safe_handlers_callback("post_invalidate") return True
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: You try to awake a dead component """ with self._lock: if self.state in ( StoredInstance.VALID, StoredInstance.VALIDATING, StoredInstance.ERRONEOUS, ): # No work to do (yet) return False if self.state == StoredInstance.KILLED: raise RuntimeError("{0}: Zombies !".format(self.name)) # Clear the error trace self.error_trace = None # Call the handlers self.__safe_handlers_callback("pre_validate") if safe_callback: # Safe call back needed and not yet passed self.state = StoredInstance.VALIDATING # Call @ValidateComponent first, then @Validate if not self.__safe_validation_callback( constants.IPOPO_CALLBACK_VALIDATE ): # Stop there if the callback failed self.state = StoredInstance.VALID self.invalidate(True) # Consider the component has erroneous self.state = StoredInstance.ERRONEOUS return False # All good self.state = StoredInstance.VALID # Call the handlers self.__safe_handlers_callback("post_validate") # We may have caused a framework error, so check if iPOPO is active if self._ipopo_service is not None: # pylint: disable=W0212 # Trigger the iPOPO event (after the service _registration) self._ipopo_service._fire_ipopo_event( constants.IPopoEvent.VALIDATED, self.factory_name, self.name ) return True
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 went wrong """ comp_callback = self.context.get_callback(event) if not comp_callback: # No registered callback return True # Call it result = comp_callback(self.instance, *args, **kwargs) if result is None: # Special case, if the call back returns nothing return True return result
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 callback result, or None :raise Exception: Something went wrong """ # Get the field callback info cb_info = self.context.get_field_callback(field, event) if not cb_info: # No registered callback return True # Extract information callback, if_valid = cb_info if if_valid and self.state != StoredInstance.VALID: # Don't call the method if the component state isn't satisfying return True # Call it result = callback(self.instance, field, *args, **kwargs) if result is None: # Special case, if the call back returns nothing return True return result
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 """ if self.state == StoredInstance.KILLED: # Invalid state return None try: return self.__callback(event, *args, **kwargs) except FrameworkException as ex: # Important error self._logger.exception( "Critical error calling back %s: %s", self.name, ex ) # Kill the component self._ipopo_service.kill(self.name) if ex.needs_stop: # Framework must be stopped... self._logger.error( "%s said that the Framework must be stopped.", self.name ) self.bundle_context.get_framework().stop() return False except: self._logger.exception( "Component '%s': error calling callback method for event %s", self.name, event, ) return False
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: * 'none_as_true': If set to True and the method returned None or doesn't exist, the result is considered as True. If set to False, None result is kept as is. Default is False. * 'only_boolean': If True, the result can only be True or False, else the result is the value returned by the method. Default is False. :param handler: The handler to call :param method_name: The name of the method to call :param args: List of arguments for the method to call :param kwargs: Dictionary of arguments for the method to call and to control the call :return: The method result, or None on error """ if handler is None or method_name is None: return None # Behavior flags only_boolean = kwargs.pop("only_boolean", False) none_as_true = kwargs.pop("none_as_true", False) # Get the method for each handler try: method = getattr(handler, method_name) except AttributeError: # Method not found result = None else: try: # Call it result = method(*args, **kwargs) except Exception as ex: # No result result = None # Log error self._logger.exception( "Error calling handler '%s': %s", handler, ex ) if result is None and none_as_true: # Consider None (nothing returned) as True result = True if only_boolean: # Convert to a boolean result return bool(result) return result
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. Special parameters can be given in kwargs: * 'exception_as_error': if it is set to True and an exception is raised by a handler, then this method will return False. By default, this flag is set to False and exceptions are ignored. * 'break_on_false': if it set to True, the loop calling the handler will stop after an handler returned False. By default, this flag is set to False, and all handlers are called. :param method_name: Name of the method to call :param args: List of arguments for the method to call :param kwargs: Dictionary of arguments for the method to call and the behavior of the call :return: True if all handlers returned True (or None), else False """ if self.state == StoredInstance.KILLED: # Nothing to do return False # Behavior flags exception_as_error = kwargs.pop("exception_as_error", False) break_on_false = kwargs.pop("break_on_false", False) result = True for handler in self.get_handlers(): # Get the method for each handler try: method = getattr(handler, method_name) except AttributeError: # Ignore missing methods pass else: try: # Call it res = method(*args, **kwargs) if res is not None and not res: # Ignore 'None' results result = False except Exception as ex: # Log errors self._logger.exception( "Error calling handler '%s': %s", handler, ex ) # We can consider exceptions as errors or ignore them result = result and not exception_as_error if not handler and break_on_false: # The loop can stop here break return result
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 service """ # Set the value setattr(self.instance, dependency.get_field(), dependency.get_value()) # Call the component back self.safe_callback(constants.IPOPO_CALLBACK_BIND, service, reference) self.__safe_field_callback( dependency.get_field(), constants.IPOPO_CALLBACK_BIND_FIELD, service, reference, )
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. :param dependency: The dependency handler :param service: The injected service :param reference: The reference of the injected service :param old_properties: Previous properties of the dependency :param new_value: If True, inject the new value of the handler """ if new_value: # Set the value setattr( self.instance, dependency.get_field(), dependency.get_value() ) # Call the component back self.__safe_field_callback( dependency.get_field(), constants.IPOPO_CALLBACK_UPDATE_FIELD, service, reference, old_properties, ) self.safe_callback( constants.IPOPO_CALLBACK_UPDATE, service, reference, old_properties )
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 service """ # Call the component back self.__safe_field_callback( dependency.get_field(), constants.IPOPO_CALLBACK_UNBIND_FIELD, service, reference, ) self.safe_callback(constants.IPOPO_CALLBACK_UNBIND, service, reference) # Update the injected field setattr(self.instance, dependency.get_field(), dependency.get_value()) # Unget the service self.bundle_context.unget_service(reference)
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 in ("none", "0", "false", "no") except AttributeError: # Not a string, but has a value return True
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 the new filter filter_str = self._original_filter.format( **self._component_context.properties ) except KeyError as ex: # An entry is missing: abandon logging.warning("Missing filter value: %s", ex) raise ValueError("Missing filter value") try: # Parse the new LDAP filter new_filter = ldapfilter.get_ldap_filter(filter_str) except (TypeError, ValueError) as ex: logging.warning("Error parsing filter: %s", ex) raise ValueError("Error parsing filter") # The filter is valid self.valid_filter = True # Compare to the "old" one if new_filter != self.requirement.filter: # Replace the requirement filter self.requirement.filter = new_filter return True # Same filter return False
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 """ if name in self._keys: try: if self.update_filter(): # This is a key for the filter and the filter has changed # => Force the handler to update its dependency self._reset() except ValueError: # Invalid filter: clear all references, this will invalidate # the component for svc_ref in self.get_bindings(): self.on_service_departure(svc_ref)
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 reference matches the filter if not self.requirement.filter.matches( svc_ref.get_properties() ): # Not the case: emulate a service departure # The instance life cycle will be updated as well self.on_service_departure(svc_ref)
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: disable=E0702 # Pylint seems to miss the "is None" check below if self.__exception is None: return result else: raise self.__exception
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.__extra, ) except Exception as ex: self._logger.exception("Error calling back method: %s", ex)
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 back in the end of the execution :param extra: Extra parameter to be given to the callback method """ self.__callback = method self.__extra = extra if self._done_event.is_set(): # The execution has already finished self.__notify()
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 number of threads to start to handle pending tasks nb_pending_tasks = self._queue.qsize() if nb_pending_tasks > self._max_threads: nb_threads = self._max_threads nb_pending_tasks = self._max_threads elif nb_pending_tasks < self._min_threads: nb_threads = self._min_threads else: nb_threads = nb_pending_tasks # Create the threads for _ in range(nb_pending_tasks): self.__nb_pending_task += 1 self.__start_thread() for _ in range(nb_threads - nb_pending_tasks): self.__start_thread()
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: do nothing return False # Prepare thread and start it name = "{0}-{1}".format(self._logger.name, self._thread_id) self._thread_id += 1 thread = threading.Thread(target=self.__run, name=name) thread.daemon = True try: self.__nb_threads += 1 thread.start() self._threads.append(thread) return True except (RuntimeError, OSError): self.__nb_threads -= 1 return False
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: # Add something in the queue (to unlock the join()) try: for _ in self._threads: self._queue.put(self._done_event, True, self._timeout) except queue.Full: # There is already something in the queue pass # Copy the list of threads to wait for threads = self._threads[:] # Join threads outside the lock for thread in threads: while thread.is_alive(): # Wait 3 seconds thread.join(3) if thread.is_alive(): # Thread is still alive: something might be wrong self._logger.warning( "Thread %s is still alive...", thread.name ) # Clear storage del self._threads[:] self.clear()
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(method, "__call__"): raise ValueError( "{0} has no __call__ member.".format(method.__name__) ) # Prepare the future result object future = FutureResult(self._logger) # Use a lock, as we might be "resetting" the queue with self.__lock: # Add the task to the queue self._queue.put((method, args, kwargs, future), True, self._timeout) self.__nb_pending_task += 1 if self.__nb_pending_task > self.__nb_threads: # All threads are taken: start a new one self.__start_thread() return future
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.task_done() except queue.Empty: # Queue is now empty pass # Wait for the tasks currently executed self.join()
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 elif timeout is None: # Use the original join self._queue.join() return True else: # Wait for the condition with self._queue.all_tasks_done: self._queue.all_tasks_done.wait(timeout) return not bool(self._queue.unfinished_tasks)
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 task is self._done_event: # Stop event in the queue: get out self._queue.task_done() return except queue.Empty: # Nothing to do yet pass else: with self.__lock: self.__nb_active_threads += 1 # Extract elements method, args, kwargs, future = task try: # Call the method future.execute(method, args, kwargs) except Exception as ex: self._logger.exception( "Error executing %s: %s", method.__name__, ex ) finally: # Mark the action as executed self._queue.task_done() # Thread is not active anymore with self.__lock: self.__nb_pending_task -= 1 self.__nb_active_threads -= 1 # Clean up thread if necessary with self.__lock: extra_threads = self.__nb_threads - self.__nb_active_threads if ( self.__nb_threads > self._min_threads and extra_threads > self._queue.qsize() ): # No more work for this thread # if there are more non active_thread than task # and we're above the minimum number of threads: # stop this one self.__nb_threads -= 1 # To avoid a race condition: decrease the number of # threads here and mark it as already accounted for already_cleaned = True return finally: # Always clean up with self.__lock: # Thread stops: clean up references try: self._threads.remove(threading.current_thread()) except ValueError: pass if not already_cleaned: self.__nb_threads -= 1
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' argument. encoding (str, optional): Defaults to 'ascii'. Used to encode url argument if it is not pre-encoded into bytes. Returns: DocID: The DocID object. Examples: >>> from os_docid import docid >>> docid('http://www.google.com/') 1d5920f4b44b27a8-ed646a3334ca891f-ff90821feeb2b02a33a6f9fc8e5f3fcd >>> docid('1d5920f4b44b27a8-ed646a3334ca891f-ff90821feeb2b02a33a6f9fc8e5f3fcd') 1d5920f4b44b27a8-ed646a3334ca891f-ff90821feeb2b02a33a6f9fc8e5f3fcd >>> docid('1d5920f4b44b27a8ed646a3334ca891fff90821feeb2b02a33a6f9fc8e5f3fcd') 1d5920f4b44b27a8-ed646a3334ca891f-ff90821feeb2b02a33a6f9fc8e5f3fcd >>> docid('abc') NotImplementedError: Not supported data format """ if not isinstance(url, bytes): url = url.encode(encoding) parser = _URL_PARSER idx = 0 for _c in url: if _c not in _HEX: if not (_c == _SYM_MINUS and (idx == _DOMAINID_LENGTH or idx == _HOSTID_LENGTH + 1)): return parser.parse(url, idx) idx += 1 if idx > 4: break _l = len(url) if _l == _DOCID_LENGTH: parser = _DOCID_PARSER elif _l == _READABLE_DOCID_LENGTH \ and url[_DOMAINID_LENGTH] == _SYM_MINUS \ and url[_HOSTID_LENGTH + 1] == _SYM_MINUS: parser = _R_DOCID_PARSER else: parser = _PARSER return parser.parse(url, idx)
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 = _deobfuscate_at1_re.sub('@', text) text = _deobfuscate_at2_re.sub(r'\1@\2', text) text = _deobfuscate_at3_re.sub(r'\1@\2', text) return 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(u"Awesome Coder, wanted at Awesome Company! ") == 'awesome coder wanted at awesome company' True """ if isinstance(text, six.text_type): if six.PY3: # pragma: no cover text = text.translate(text.maketrans("", "", string.punctuation)).lower() else: # pragma: no cover text = six.text_type(text.encode('utf-8').translate(string.maketrans("", ""), string.punctuation).lower(), 'utf-8') else: text = text.translate(string.maketrans("", ""), string.punctuation).lower() return " ".join(text.split())
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 for %s: %s" % (rname, resource['error'])) else: print("Resource %s %s..." % (rname, resource['status'])) for aname, action in six.iteritems(resource['actions']): if action['status'] == 'error': print("\tError for %s/%s: %s" % (rname, aname, action['error'])) else: print("\tAction %s/%s %s..." % (rname, aname, resource['status'])) print("Resources synced...")
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 find settings file %s for additional settings, skipping it" % filepath, file=sys.stderr) return False
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 immutable(Column(Integer, primary_key=True, nullable=False))
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) url_id_func.__name__ = 'url_id' url_id_property = hybrid_property(url_id_func) url_id_property = url_id_property.comparator(url_id_is) return url_id_property else: def url_id_func(self): """The URL id, integer primary key rendered as a string""" return six.text_type(self.id) def url_id_expression(cls): """The URL id, integer primary key""" return cls.id url_id_func.__name__ = 'url_id' url_id_property = hybrid_property(url_id_func) url_id_property = url_id_property.expression(url_id_expression) return url_id_property
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, attr)
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_type, nullable=False, unique=True) else: return Column(column_type, CheckConstraint("name <> ''"), nullable=False, unique=True)
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) return instance
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): short = self.title[len(self.parent.title):].strip() match = _punctuation_re.match(short) if match: short = short[match.end():].strip() if short: return short return self.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(self.parent, PermissionMixin): return self.parent.permissions(actor) | super(BaseScopedNameMixin, self).permissions(actor) else: return super(BaseScopedNameMixin, self).permissions(actor)
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, 'init_scalar', retval=True, propagate=True) def init_scalar(target, value, dict_): # A subclass may override the column and not provide a default. Watch out for that. if default: if default.is_callable: value = default.arg(None) elif default.is_scalar: value = default.arg else: raise NotImplementedError("Can't invoke pre-default for a SQL-level column default") dict_[column.key] = value return value
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 profile_view(profileob): # 'profileob' is now a Profile model instance. The load_model decorator replaced this: # profileob = Profile.query.filter_by(name=profile).first_or_404() return "Hello, %s" % profileob.name Using the same name for request and parameter makes code easier to understand:: @app.route('/<profile>') @load_model(Profile, {'name': 'profile'}, 'profile') def profile_view(profile): return "Hello, %s" % profile.name ``load_model`` aborts with a 404 if no instance is found. :param model: The SQLAlchemy model to query. Must contain a ``query`` object (which is the default with Flask-SQLAlchemy) :param attributes: A dict of attributes (from the URL request) that will be used to query for the object. For each key:value pair, the key is the name of the column on the model and the value is the name of the request parameter that contains the data :param parameter: The name of the parameter to the decorated function via which the result is passed. Usually the same as the attribute. If the parameter name is prefixed with 'g.', the parameter is also made available as g.<parameter> :param kwargs: If True, the original request parameters are passed to the decorated function as a ``kwargs`` parameter :param permission: If present, ``load_model`` calls the :meth:`~coaster.sqlalchemy.PermissionMixin.permissions` method of the retrieved object with ``current_auth.actor`` as a parameter. If ``permission`` is not present in the result, ``load_model`` aborts with a 403. The permission may be a string or a list of strings, in which case access is allowed if any of the listed permissions are available :param addlperms: Iterable or callable that returns an iterable containing additional permissions available to the user, apart from those granted by the models. In an app that uses Lastuser for authentication, passing ``lastuser.permissions`` will pass through permissions granted via Lastuser :param list urlcheck: If an attribute in this list has been used to load an object, but the value of the attribute in the loaded object does not match the request argument, issue a redirect to the corrected URL. This is useful for attributes like ``url_id_name`` and ``url_name_suuid`` where the ``name`` component may change """ return load_models((model, attributes, parameter), kwargs=kwargs, permission=permission, addlperms=addlperms, urlcheck=urlcheck)
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 (see below) :param methods: A list of allowed HTTP methods :param headers: A list of allowed HTTP headers :param max_age: Duration in seconds for which the CORS response may be cached The :obj:`origins` parameter may be one of: 1. A callable that receives the origin as a parameter. 2. A list of origins. 3. ``*``, indicating that this resource is accessible by any origin. Example use:: from flask import Flask, Response from coaster.views import cors app = Flask(__name__) @app.route('/any') @cors('*') def any_origin(): return Response() @app.route('/static', methods=['GET', 'POST']) @cors(['https://hasgeek.com'], methods=['GET'], headers=['Content-Type', 'X-Requested-With'], max_age=3600) def static_list(): return Response() def check_origin(origin): # check if origin should be allowed return True @app.route('/callable') @cors(check_origin) def callable_function(): return Response() """ def inner(f): @wraps(f) def wrapper(*args, **kwargs): origin = request.headers.get('Origin') if request.method not in methods: abort(405) if origins == '*': pass elif is_collection(origins) and origin in origins: pass elif callable(origins) and origins(origin): pass else: abort(403) if request.method == 'OPTIONS': # pre-flight request resp = Response() else: result = f(*args, **kwargs) resp = make_response(result) if not isinstance(result, (Response, WerkzeugResponse, current_app.response_class)) else result resp.headers['Access-Control-Allow-Origin'] = origin if origin else '' resp.headers['Access-Control-Allow-Methods'] = ', '.join(methods) resp.headers['Access-Control-Allow-Headers'] = ', '.join(headers) if max_age: resp.headers['Access-Control-Max-Age'] = str(max_age) # Add 'Origin' to the Vary header since response will vary by origin if 'Vary' in resp.headers: vary_values = [item.strip() for item in resp.headers['Vary'].split(',')] if 'Origin' not in vary_values: vary_values.append('Origin') resp.headers['Vary'] = ', '.join(vary_values) else: resp.headers['Vary'] = 'Origin' return resp return wrapper return inner
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 that can be called to perform the same test. :param permission: Permission that is required. If a collection type is provided, any one permission must be available """ def inner(f): def is_available_here(): if not hasattr(current_auth, 'permissions'): return False elif is_collection(permission): return bool(current_auth.permissions.intersection(permission)) else: return permission in current_auth.permissions def is_available(context=None): result = is_available_here() if result and hasattr(f, 'is_available'): # We passed, but we're wrapping another test, so ask there as well return f.is_available(context) return result @wraps(f) def wrapper(*args, **kwargs): add_auth_attribute('login_required', True) if not is_available_here(): abort(403) return f(*args, **kwargs) wrapper.requires_permission = permission wrapper.is_available = is_available return wrapper return inner
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 conditions only. >>> dt = datetime.now() >>> u1 = uuid1mc() >>> u2 = uuid1mc_from_datetime(dt) >>> # Both timestamps should be very close to each other but not an exact match >>> u1.time > u2.time True >>> u1.time - u2.time < 5000 True >>> d2 = datetime.fromtimestamp((u2.time - 0x01b21dd213814000) * 100 / 1e9) >>> d2 == dt True """ fields = list(uuid1mc().fields) if isinstance(dt, datetime): timeval = time.mktime(dt.timetuple()) + dt.microsecond / 1e6 else: # Assume we got an actual timestamp timeval = dt # The following code is borrowed from the UUID module source: nanoseconds = int(timeval * 1e9) # 0x01b21dd213814000 is the number of 100-ns intervals between the # UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00. timestamp = int(nanoseconds // 100) + 0x01b21dd213814000 time_low = timestamp & 0xffffffff time_mid = (timestamp >> 32) & 0xffff time_hi_version = (timestamp >> 48) & 0x0fff fields[0] = time_low fields[1] = time_mid fields[2] = time_hi_version return uuid.UUID(fields=tuple(fields))
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: return six.text_type(urlsafe_b64encode(value.bytes).rstrip('='))
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 = randint(0, 10 ** digits) return (u'%%0%dd' % digits) % randnum
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 string delim: Delimiter between words, default '-' :param int maxlength: Maximum length of name, default 50 :param checkused: Function to check if a generated name is available for use :param int counter: Starting position for name counter >>> make_name('This is a title') 'this-is-a-title' >>> make_name('Invalid URL/slug here') 'invalid-url-slug-here' >>> make_name('this.that') 'this-that' >>> make_name('this:that') 'this-that' >>> make_name("How 'bout this?") 'how-bout-this' >>> make_name(u"How’s that?") 'hows-that' >>> make_name(u'K & D') 'k-d' >>> make_name('billion+ pageviews') 'billion-pageviews' >>> make_name(u'हिन्दी slug!') 'hindii-slug' >>> make_name(u'Your webapps should talk not just in English, but in español, Kiswahili, 廣州話 and অসমীয়া too.', maxlength=250) u'your-webapps-should-talk-not-just-in-english-but-in-espanol-kiswahili-guang-zhou-hua-and-asmiiyaa-too' >>> make_name(u'__name__', delim=u'_') 'name' >>> make_name(u'how_about_this', delim=u'_') 'how_about_this' >>> make_name(u'and-that', delim=u'_') 'and_that' >>> make_name(u'Umlauts in Mötörhead') 'umlauts-in-motorhead' >>> make_name('Candidate', checkused=lambda c: c in ['candidate']) 'candidate2' >>> make_name('Candidate', checkused=lambda c: c in ['candidate'], counter=1) 'candidate1' >>> make_name('Candidate', checkused=lambda c: c in ['candidate', 'candidate1', 'candidate2'], counter=1) 'candidate3' >>> make_name('Long title, but snipped', maxlength=20) 'long-title-but-snipp' >>> len(make_name('Long title, but snipped', maxlength=20)) 20 >>> make_name('Long candidate', maxlength=10, checkused=lambda c: c in ['long-candi', 'long-cand1']) 'long-cand2' >>> make_name(u'Lǝnkǝran') 'lankaran' >>> make_name(u'example@example.com') 'example-example-com' >>> make_name('trailing-delimiter', maxlength=10) 'trailing-d' >>> make_name('trailing-delimiter', maxlength=9) 'trailing' >>> make_name('''test this ... newline''') 'test-this-newline' >>> make_name(u"testing an emoji😁") u'testing-an-emoji' >>> make_name('''testing\\t\\nmore\\r\\nslashes''') 'testing-more-slashes' >>> make_name('What if a HTML <tag/>') 'what-if-a-html-tag' >>> make_name('These are equivalent to \\x01 through \\x1A') 'these-are-equivalent-to-through' """ name = text.replace('@', delim) name = unidecode(name).replace('@', 'a') # We don't know why unidecode uses '@' for 'a'-like chars name = six.text_type(delim.join([_strip_re.sub('', x) for x in _punctuation_re.split(name.lower()) if x != ''])) if isinstance(text, six.text_type): # Unidecode returns str. Restore to a unicode string if original was unicode name = six.text_type(name) candidate = name[:maxlength] if candidate.endswith(delim): candidate = candidate[:-1] if checkused is None: return candidate existing = checkused(candidate) while existing: candidate = name[:maxlength - len(str(counter))] + str(counter) counter += 1 existing = checkused(candidate) return candidate
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-encoding') False >>> check_password(u'{SSHA}q/uVU8r15k/9QhRi92CWUwMJu2DM6TUSpp25', u're-foo') True >>> check_password(u'{BCRYPT}$2b$12$NfKivgz7njR3/rWZ56EsDe7..PPum.fcmFLbdkbP.chtMTcS1s01C', 'foo') True """ if reference.startswith(u'{PLAIN}'): if reference[7:] == attempt: return True elif reference.startswith(u'{SSHA}'): # In python3 b64decode takes inputtype as bytes as opposed to str in python 2, and returns # binascii.Error as opposed to TypeError if six.PY3: # pragma: no cover try: if isinstance(reference, six.text_type): ref = b64decode(reference[6:].encode('utf-8')) else: ref = b64decode(reference[6:]) except binascii.Error: return False # Not Base64 else: # pragma: no cover try: ref = b64decode(reference[6:]) except TypeError: return False # Not Base64 if isinstance(attempt, six.text_type): attempt = attempt.encode('utf-8') salt = ref[20:] b64_encoded = b64encode(hashlib.sha1(attempt + salt).digest() + salt) if six.PY3: # pragma: no cover # type(b64_encoded) is bytes and can't be compared with type(reference) which is str compare = six.text_type('{SSHA}%s' % b64_encoded.decode('utf-8') if type(b64_encoded) is bytes else b64_encoded) else: # pragma: no cover compare = six.text_type('{SSHA}%s' % b64_encoded) return compare == reference elif reference.startswith(u'{BCRYPT}'): # bcrypt.hashpw() accepts either a unicode encoded string or the basic string (python 2) if isinstance(attempt, six.text_type) or isinstance(reference, six.text_type): attempt = attempt.encode('utf-8') reference = reference.encode('utf-8') if six.PY3: # pragma: no cover return bcrypt.hashpw(attempt, reference[8:]) == reference[8:] else: # pragma: no cover return bcrypt.hashpw( attempt.encode('utf-8') if isinstance(attempt, six.text_type) else attempt, str(reference[8:])) == reference[8:] return False
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' >>> format_currency(99.95) '99.95' >>> format_currency(100000) '100,000' >>> format_currency(1000.00) '1,000' >>> format_currency(1000.41) '1,000.41' >>> format_currency(23.21, decimals=3) '23.210' >>> format_currency(1000, decimals=3) '1,000' >>> format_currency(123456789.123456789) '123,456,789.12' """ number, decimal = ((u'%%.%df' % decimals) % value).split(u'.') parts = [] while len(number) > 3: part, number = number[-3:], number[:-3] parts.append(part) parts.append(number) parts.reverse() if int(decimal) == 0: return u','.join(parts) else: return u','.join(parts) + u'.' + decimal
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 hashlib.md5(data.encode('utf-8')).hexdigest() else: # pragma: no cover return hashlib.md5(data).hexdigest()
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/Kolkata').localize(datetime(2017, 1, 1))) datetime.datetime(2016, 12, 31, 18, 30, tzinfo=<UTC>) >>> midnight_to_utc(datetime(2017, 1, 1), naive=True) datetime.datetime(2017, 1, 1, 0, 0) >>> midnight_to_utc(pytz.timezone('Asia/Kolkata').localize(datetime(2017, 1, 1)), naive=True) datetime.datetime(2016, 12, 31, 18, 30) >>> midnight_to_utc(date(2017, 1, 1)) datetime.datetime(2017, 1, 1, 0, 0, tzinfo=<UTC>) >>> midnight_to_utc(date(2017, 1, 1), naive=True) datetime.datetime(2017, 1, 1, 0, 0) >>> midnight_to_utc(date(2017, 1, 1), timezone='Asia/Kolkata') datetime.datetime(2016, 12, 31, 18, 30, tzinfo=<UTC>) >>> midnight_to_utc(datetime(2017, 1, 1), timezone='Asia/Kolkata') datetime.datetime(2016, 12, 31, 18, 30, tzinfo=<UTC>) >>> midnight_to_utc(pytz.timezone('Asia/Kolkata').localize(datetime(2017, 1, 1)), timezone='UTC') datetime.datetime(2017, 1, 1, 0, 0, tzinfo=<UTC>) """ if timezone: if isinstance(timezone, six.string_types): tz = pytz.timezone(timezone) else: tz = timezone elif isinstance(dt, datetime) and dt.tzinfo: tz = dt.tzinfo else: tz = pytz.UTC utc_dt = tz.localize(datetime.combine(dt, datetime.min.time())).astimezone(pytz.UTC) if naive: return utc_dt.replace(tzinfo=None) return utc_dt
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) >>> getbool(0) False >>> getbool(False) False >>> getbool('n') False """ value = str(value).lower() if value in ['1', 't', 'true', 'y', 'yes']: return True elif value in ['0', 'f', 'false', 'n', 'no']: return False return None
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=F6stal?=') == u'p\xf6stal' True >>> unicode_http_header('p\xf6stal') == u'p\xf6stal' True """ if six.PY3: # pragma: no cover # email.header.decode_header expects strings, not bytes. Your input data may be in bytes. # Since these bytes are almost always ASCII, calling `.decode()` on it without specifying # a charset should work fine. if isinstance(value, six.binary_type): value = value.decode() return u''.join([six.text_type(s, e or 'iso-8859-1') if not isinstance(s, six.text_type) else s for s, e in decode_header(value)])
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_email_domain('Example Address <test@example.com>') 'example.com' >>> get_email_domain('foobar') >>> get_email_domain('foo@bar@baz') 'bar' >>> get_email_domain('foobar@') >>> get_email_domain('@foobar') """ realname, address = email.utils.parseaddr(emailaddr) try: username, domain = address.split('@') if not username: return None return domain or None except ValueError: return None
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 = divmod(remaining, 60) return hours, minutes now = datetime.utcnow() # Make a list of country code mappings timezone_country = {} for countrycode in pytz.country_timezones: for timezone in pytz.country_timezones[countrycode]: timezone_country[timezone] = countrycode # Make a list of timezones, discarding the US/* and Canada/* zones since they aren't reliable for # DST, and discarding UTC and GMT since timezones in that zone have their own names timezones = [(pytz.timezone(tzname).utcoffset(now, is_dst=False), tzname) for tzname in pytz.common_timezones if not tzname.startswith('US/') and not tzname.startswith('Canada/') and tzname not in ('GMT', 'UTC')] # Sort timezones by offset from UTC and their human-readable name presorted = [(delta, '%s%s - %s%s (%s)' % ( (delta.days < 0 and '-') or (delta.days == 0 and delta.seconds == 0 and ' ') or '+', '%02d:%02d' % hourmin(delta), (pytz.country_names[timezone_country[name]] + ': ') if name in timezone_country else '', name.replace('_', ' '), pytz.timezone(name).tzname(now, is_dst=False)), name) for delta, name in timezones] presorted.sort() # Return a list of (timezone, label) with the timezone offset included in the label. return [(name, label) for (delta, label, name) in presorted]
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.split('.') namespace.reverse() if namespace and not namespace[0]: namespace.pop(0) if namespace and namespace[-1] == 'www': namespace.pop(-1) return type(url)('.'.join(namespace))
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') False >>> base_domain_matches('static.hasgeek.co.in', 'hasgeek.com') False >>> base_domain_matches('static.hasgeek.co.in', 'hasgeek.co.in') True >>> base_domain_matches('example@example.com', 'example.com') True """ r1 = tldextract.extract(d1) r2 = tldextract.extract(d2) # r1 and r2 contain subdomain, domain and suffix. # We want to confirm that domain and suffix match. return r1.domain == r2.domain and r1.suffix == r2.suffix
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, **kwargs), Column(name + '_html', UnicodeText, **kwargs), deferred=deferred, group=group or name )
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 in self._require_recursive(*not_blacklist) if name not in blacklist])
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(): current_state = getattr(self.obj, statemanager.propname) if conditions['from'] is None: state_valid = True else: mstate = conditions['from'].get(current_state) state_valid = mstate and mstate(self.obj) if state_valid and conditions['if']: state_valid = all(v(self.obj) for v in conditions['if']) if not state_valid: return statemanager, current_state, statemanager.lenum.get(current_state)
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. :param str name: Name of the new state :param ManagedState state: Existing state that this is based on :param validator: Function that will be called with the host object as a parameter :param class_validator: Function that will be called when the state is queried on the class instead of the instance. Falls back to ``validator`` if not specified. Receives the class as the parameter :param cache_for: Integer or function that indicates how long ``validator``'s result can be cached (not applicable to ``class_validator``). ``None`` implies no cache, ``0`` implies indefinite cache (until invalidated by a transition) and any other integer is the number of seconds for which to cache the assertion :param label: Label for this state (string or 2-tuple) TODO: `cache_for`'s implementation is currently pending a test case demonstrating how it will be used. """ # We'll accept a ManagedState with grouped values, but not a ManagedStateGroup if not isinstance(state, ManagedState): raise TypeError("Not a managed state: %s" % repr(state)) elif state.statemanager != self: raise ValueError("State %s is not associated with this state manager" % repr(state)) if isinstance(label, tuple) and len(label) == 2: label = NameTitle(*label) self._add_state_internal(name, state.value, label=label, validator=validator, class_validator=class_validator, cache_for=cache_for)
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_: Validator(s) that, given the object, must all return True for the call to proceed :param data: Additional metadata, stored on the `StateTransition` object as a :attr:`data` attribute """ return self.transition(from_, None, if_, **data)
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 line will be blank since it had the closing "```". Discard it # when indenting the lines. return result + '\n'.join([' ' + line for line in code.split('\n')[:-1]]) use_crlf = text.find('\r') != -1 if use_crlf: text = text.replace('\r\n', '\n') # Render GitHub-style ```code blocks``` into Markdown-style 4-space indented blocks text = CODEPATTERN_RE.sub(indent_code, text) text, code_blocks = remove_pre_blocks(text) text, inline_blocks = remove_inline_code_blocks(text) # Prevent foo_bar_baz from ending up with an italic word in the middle. def italic_callback(matchobj): s = matchobj.group(0) # don't mess with URLs: if 'http:' in s or 'https:' in s: return s return s.replace('_', r'\_') # fix italics for code blocks text = ITALICSPATTERN_RE.sub(italic_callback, text) # linkify naked URLs # wrap the URL in brackets: http://foo -> [http://foo](http://foo) text = NAKEDURL_RE.sub(r'\1[\2](\2)\3', text) # In very clear cases, let newlines become <br /> tags. def newline_callback(matchobj): if len(matchobj.group(1)) == 1: return matchobj.group(0).rstrip() + ' \n' else: return matchobj.group(0) text = NEWLINE_RE.sub(newline_callback, text) # now restore removed code blocks removed_blocks = code_blocks + inline_blocks for removed_block in removed_blocks: text = text.replace('{placeholder}', removed_block, 1) if use_crlf: text = text.replace('\n', '\r\n') return text
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_tags=valid_tags)) else: return Markup(markdown_convert_text(gfm(text)))
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 ':') request.environ['HTTP_HOST'].split(':', 1)[0] != current_app.config['SERVER_NAME'].split(':', 1)[0]): return request.url url = url_for(request.endpoint, **request.view_args) query = request.query_string if query: return url + '?' + query.decode() else: return url
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 function looks for a ``next`` parameter in the request or in the session (depending on whether parameter ``session`` is True). If no ``next`` is present, it checks the referrer (if enabled), and finally returns either the provided default (which can be any value including ``None``) or the script root (typically ``/``). """ if session: next_url = request_session.pop('next', None) or request.args.get('next', '') else: next_url = request.args.get('next', '') if next_url and not external: next_url = __clean_external_url(next_url) if next_url: return next_url if default is __marker: usedefault = False else: usedefault = True if referrer and request.referrer: if external: return request.referrer else: return __clean_external_url(request.referrer) or (default if usedefault else __index_url()) else: return default if usedefault else __index_url()
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 object has a restrictive __slots__, but it's # required for some objects like Column because SQLAlchemy copies # them in subclasses, changing their hash and making them # undiscoverable via the cache. try: if not hasattr(attr, '_coaster_annotations'): setattr(attr, '_coaster_annotations', []) attr._coaster_annotations.append(annotation) except AttributeError: pass return attr decorator.__name__ = decorator.name = annotation decorator.__doc__ = doc return decorator
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): key = value_def.config_key or config_key return '%s.%s' % (config_path, key) if config_path else key def build_token(name, value_def): config_key = build_config_key(value_def, name) value_token = ValueToken.from_definition( value_def, namespace, config_key) getters.register_value_proxy(namespace, value_token, value_def.help) tokens[name] = value_token return name, build_property(value_token) def build_attr(name, attribute): if not isinstance(attribute, ValueTypeDefinition): return name, attribute return build_token(name, attribute) attributes = dict(build_attr(*item) for item in six.iteritems(attributes)) attributes['_tokens'] = tokens return attributes
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: return value ret = func(self, *args, **kwargs) setattr(self, cache_name, ret) return ret return inner_wrapper return cache_wrapper
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 missing value for: %s" % (proxy.namespace, proxy.config_key)) try: return proxy.validator(value) except errors.ValidationError as e: raise errors.ConfigurationError("%s failed to validate %s: %s" % (proxy.namespace, proxy.config_key, e))
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 the appropriate type. :param reader_namespace: the default namespace to use. Defaults to `DEFAULT`. """ def reader(config_key, default=UndefToken, namespace=None): config_namespace = config.get_namespace(namespace or reader_namespace) return validator(_read_config(config_key, config_namespace, default)) return reader
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 validate :type name: string :param all_names: if True validates all namespaces and ignores `name` :type all_names: boolean """ for namespace in get_namespaces_from_names(name, all_names): all(value_proxy.get_value() for value_proxy in namespace.get_value_proxies())
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 config: %s" % duplicate_keys if raise_error: raise errors.ConfigurationError(msg) log.info(msg) return True
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 context of an OSError raised by os.path.getmtime(filename). Information on this error can be retrieved by calling sys.exc_info inside of err_logger.""" def compare_func(filename): try: return os.path.getmtime(filename) except OSError: if err_logger is not None: err_logger(filename) return -1 return compare_func
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 for key in subkeys: d = d.setdefault(key, value if key == subkeys[-1] else {}) return 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_', ''), desc.default, desc.help or '') def format_namespace(key, desc_list): return "\nNamespace: %s\n%s" % ( key, '\n'.join(sorted(format_desc(desc) for desc in desc_list))) def namespace_cmp(item): name, _ = item return chr(0) if name == DEFAULT else name return '\n'.join(format_namespace(*desc) for desc in sorted(six.iteritems(self.descriptions), key=namespace_cmp))
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 iterable_type(value) except TypeError: raise ValidationError("Invalid iterable: %s" % (value))
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 validate_list(value)) return validate_mapping
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_text)
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 or config.DEFAULT namespace = config.get_namespace(name) return proxy_factory.build(validator, namespace, key_name, default, help) return proxy_register
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_attrs) if proxy_key in self.proxies: return self.proxies[proxy_key] value_proxy = proxy.ValueProxy(*proxy_attrs) register_value_proxy(namespace, value_proxy, help) return self.proxies.setdefault(proxy_key, value_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 approximates the gradient of the function by finite differences along stochastic directions Deltak. The elements of Deltak are drawn from +- 1 with probability one half. The gradient is approximated from the symmetric difference f(xk + ck*Deltak) - f(xk - ck*Deltak), where the evaluation step size ck is scaled according ck = c/(k+1)**gamma. The algorithm takes a step of size ak = a/(0.01*niter+k+1)**alpha along the negative gradient. See Spall, IEEE, 1998, 34, 817-823 for guidelines about how to choose the algorithm's parameters (a, alpha, c, gamma). Parameters ---------- func: callable objective function to be minimized: called as `func(x, *args)`, if `paired=True`, then called with keyword argument `seed` additionally x0: array-like initial guess for parameters args: tuple extra arguments to be supplied to func bounds: array-like bounds on the variables niter: int number of iterations after which to terminate the algorithm paired: boolean calculate gradient for same random seeds a: float scaling parameter for step size alpha: float scaling exponent for step size c: float scaling parameter for evaluation step size gamma: float scaling exponent for evaluation step size disp: boolean whether to output status updates during the optimization callback: callable called after each iteration, as callback(xk), where xk are the current parameters Returns ------- `scipy.optimize.OptimizeResult` object """ A = 0.01 * niter if bounds is not None: bounds = np.asarray(bounds) project = lambda x: np.clip(x, bounds[:, 0], bounds[:, 1]) if args is not None: # freeze function arguments def funcf(x, **kwargs): return func(x, *args, **kwargs) N = len(x0) x = x0 for k in range(niter): ak = a/(k+1.0+A)**alpha ck = c/(k+1.0)**gamma Deltak = np.random.choice([-1, 1], size=N) fkwargs = dict() if paired: fkwargs['seed'] = np.random.randint(0, np.iinfo(np.uint32).max) if bounds is None: grad = (funcf(x + ck*Deltak, **fkwargs) - funcf(x - ck*Deltak, **fkwargs)) / (2*ck*Deltak) x -= ak*grad else: # ensure evaluation points are feasible xplus = project(x + ck*Deltak) xminus = project(x - ck*Deltak) grad = (funcf(xplus, **fkwargs) - funcf(xminus, **fkwargs)) / (xplus-xminus) x = project(x - ak*grad) # print 100 status updates if disp=True if disp and (k % (niter//100)) == 0: print(x) if callback is not None: callback(x) message = 'terminated after reaching max number of iterations' return OptimizeResult(fun=funcf(x), x=x, nit=niter, nfev=2*niter, message=message, success=True)
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 bisection search. Parameters ---------- func: callable Function of which the root should be found. If `errorcontrol=True` then the function should be derived from `AverageBase`. a, b: float initial interval xtol: float target tolerance for interval size errorcontrol: boolean if true, assume that function is derived from `AverageBase`. testkwargs: only for `errorcontrol=True` see `AverageBase.test0` outside: ['extrapolate', 'raise'] How to handle the case where f(a) and f(b) have same sign, i.e. where the root lies outside of the interval. If 'raise' throws a `BisectException`. ascending: allow passing in directly whether function is ascending or not if ascending=True then it is assumed without check that f(a) < 0 and f(b) > 0 if ascending=False then it is assumed without check that f(a) > 0 and f(b) < 0 Returns ------- float, root of function """ search = True # check whether function is ascending or not if ascending is None: if errorcontrol: testkwargs.update(dict(type_='smaller', force=True)) fa = func.test0(a, **testkwargs) fb = func.test0(b, **testkwargs) else: fa = func(a) < 0 fb = func(b) < 0 if fa and not fb: ascending = True elif fb and not fa: ascending = False else: if disp: print('Warning: func(a) and func(b) do not have opposing signs -> no search done') if outside == 'raise': raise BisectException() search = False # refine interval until it has reached size xtol, except if root outside while (b-a > xtol) and search: mid = (a+b)/2.0 if ascending: if ((not errorcontrol) and (func(mid) < 0)) or \ (errorcontrol and func.test0(mid, **testkwargs)): a = mid else: b = mid else: if ((not errorcontrol) and (func(mid) < 0)) or \ (errorcontrol and func.test0(mid, **testkwargs)): b = mid else: a = mid if disp: print('bisect bounds', a, b) # interpolate linearly to get zero if errorcontrol: ya, yb = func(a)[0], func(b)[0] else: ya, yb = func(a), func(b) m = (yb-ya) / (b-a) res = a-ya/m if disp: print('bisect final value', res) return res
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.std(fx1-fx2, ddof=1)/self.N**.5 return diffse else: return (f1se**2 + f2se**2)**.5
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]+)', t.relation or '') ] )
python
{ "resource": "" }