Search is not available for this dataset
text
stringlengths
75
104k
def find_unknown_references_hook(config): """Hook to find/raise errors for references to unknown configurables.""" additional_msg_fmt = " In binding for '{}'." for (scope, selector), param_bindings in six.iteritems(config): for param_name, param_value in six.iteritems(param_bindings): for maybe_unknown ...
def matching_selectors(self, partial_selector): """Retrieves all selectors matching `partial_selector`. For instance, if "one.a.b" and "two.a.b" are stored in a `SelectorMap`, both `matching_selectors('b')` and `matching_selectors('a.b')` will return them. In the event that `partial_selector` exactly ...
def get_match(self, partial_selector, default=None): """Gets a (single) value matching `partial_selector`. If the partial_selector exactly matches a complete selector, the value associated with the complete selector is returned. Args: partial_selector: The partial selector to find values for. ...
def get_all_matches(self, partial_selector): """Returns all values matching `partial_selector` as a list.""" matching_selectors = self.matching_selectors(partial_selector) return [self._selector_map[selector] for selector in matching_selectors]
def minimal_selector(self, complete_selector): """Returns the minimal selector that uniquely matches `complete_selector`. Args: complete_selector: A complete selector stored in the map. Returns: A partial selector that unambiguously matches `complete_selector`. Raises: KeyError: If ...
def sp_search_query(query): """Translate a Mopidy search query to a Spotify search query""" result = [] for (field, values) in query.items(): field = SEARCH_FIELD_MAP.get(field, field) if field is None: continue for value in values: if field == 'year': ...
def _parse_retry_after(self, response): """Parse Retry-After header from response if it is set.""" value = response.headers.get('Retry-After') if not value: seconds = 0 elif re.match(r'^\s*[0-9]+\s*$', value): seconds = int(value) else: date_t...
def validate_value(self, value): """ Validate new property value before setting it. value -- New value """ if 'readOnly' in self.metadata and self.metadata['readOnly']: raise PropertyError('Read-only property') try: validate(value, self.metadata)...
def as_property_description(self): """ Get the property description. Returns a dictionary describing the property. """ description = deepcopy(self.metadata) if 'links' not in description: description['links'] = [] description['links'].append( ...
def set_value(self, value): """ Set the current value of the property. value -- the value to set """ self.validate_value(value) self.value.set(value)
def get_thing(self, idx): """ Get the thing at the given index. idx -- the index """ try: idx = int(idx) except ValueError: return None if idx < 0 or idx >= len(self.things): return None return self.things[idx]
def initialize(self, things, hosts): """ Initialize the handler. things -- list of Things managed by this server hosts -- list of allowed hostnames """ self.things = things self.hosts = hosts
def set_default_headers(self, *args, **kwargs): """Set the default headers for all requests.""" self.set_header('Access-Control-Allow-Origin', '*') self.set_header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept') self.set_header('A...
def get(self): """ Handle a GET request. property_name -- the name of the property from the URL path """ self.set_header('Content-Type', 'application/json') ws_href = '{}://{}'.format( 'wss' if self.request.protocol == 'https' else 'ws', self.requ...
def prepare(self): """Validate Host header.""" host = self.request.headers.get('Host', None) if host is not None and host in self.hosts: return raise tornado.web.HTTPError(403)
def get(self, thing_id='0'): """ Handle a GET request, including websocket requests. thing_id -- ID of the thing this request is for """ self.thing = self.get_thing(thing_id) if self.thing is None: self.set_status(404) self.finish() re...
def on_message(self, message): """ Handle an incoming message. message -- message to handle """ try: message = json.loads(message) except ValueError: try: self.write_message(json.dumps({ 'messageType': 'error', ...
def get(self, thing_id='0', property_name=None): """ Handle a GET request. thing_id -- ID of the thing this request is for property_name -- the name of the property from the URL path """ thing = self.get_thing(thing_id) if thing is None: self.set_stat...
def put(self, thing_id='0', property_name=None): """ Handle a PUT request. thing_id -- ID of the thing this request is for property_name -- the name of the property from the URL path """ thing = self.get_thing(thing_id) if thing is None: self.set_stat...
def post(self, thing_id='0'): """ Handle a POST request. thing_id -- ID of the thing this request is for """ thing = self.get_thing(thing_id) if thing is None: self.set_status(404) return try: message = json.loads(self.request...
def get(self, thing_id='0', action_name=None, action_id=None): """ Handle a GET request. thing_id -- ID of the thing this request is for action_name -- name of the action from the URL path action_id -- the action ID from the URL path """ thing = self.get_thing(th...
def put(self, thing_id='0', action_name=None, action_id=None): """ Handle a PUT request. TODO: this is not yet defined in the spec thing_id -- ID of the thing this request is for action_name -- name of the action from the URL path action_id -- the action ID from the URL...
def delete(self, thing_id='0', action_name=None, action_id=None): """ Handle a DELETE request. thing_id -- ID of the thing this request is for action_name -- name of the action from the URL path action_id -- the action ID from the URL path """ thing = self.get_th...
def get(self, thing_id='0'): """ Handle a GET request. thing_id -- ID of the thing this request is for """ thing = self.get_thing(thing_id) if thing is None: self.set_status(404) return self.set_header('Content-Type', 'application/json') ...
def start(self): """Start listening for incoming connections.""" self.service_info = ServiceInfo( '_webthing._tcp.local.', '{}._webthing._tcp.local.'.format(self.name), address=socket.inet_aton(get_ip()), port=self.port, properties={ ...
def stop(self): """Stop listening.""" self.zeroconf.unregister_service(self.service_info) self.zeroconf.close() self.server.stop()
def as_action_description(self): """ Get the action description. Returns a dictionary describing the action. """ description = { self.name: { 'href': self.href_prefix + self.href, 'timeRequested': self.time_requested, '...
def start(self): """Start performing the action.""" self.status = 'pending' self.thing.action_notify(self) self.perform_action() self.finish()
def finish(self): """Finish performing the action.""" self.status = 'completed' self.time_completed = timestamp() self.thing.action_notify(self)
def as_event_description(self): """ Get the event description. Returns a dictionary describing the event. """ description = { self.name: { 'timestamp': self.time, }, } if self.data is not None: description[self...
def get_ip(): """ Get the default local IP address. From: https://stackoverflow.com/a/28950776 """ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: s.connect(('10.255.255.255', 1)) ip = s.getsockname()[0] except (socket.error, IndexError): ip = '127.0.0.1' ...
def get_addresses(): """ Get all IP addresses. Returns list of addresses. """ addresses = set() for iface in ifaddr.get_adapters(): for addr in iface.ips: # Filter out link-local addresses. if addr.is_IPv4: ip = addr.ip if not ip...
def set(self, value): """ Set a new value for this thing. value -- value to set """ if self.value_forwarder is not None: self.value_forwarder(value) self.notify_of_external_update(value)
def notify_of_external_update(self, value): """ Notify observers of a new value. value -- new value """ if value is not None and value != self.last_value: self.last_value = value self.emit('update', value)
def as_thing_description(self): """ Return the thing state as a Thing Description. Returns the state as a dictionary. """ thing = { 'name': self.name, 'href': self.href_prefix if self.href_prefix else '/', '@context': self.context, ...
def set_href_prefix(self, prefix): """ Set the prefix of any hrefs associated with this thing. prefix -- the prefix """ self.href_prefix = prefix for property_ in self.properties.values(): property_.set_href_prefix(prefix) for action_name in self.ac...
def get_property_descriptions(self): """ Get the thing's properties as a dictionary. Returns the properties as a dictionary, i.e. name -> description. """ return {k: v.as_property_description() for k, v in self.properties.items()}
def get_action_descriptions(self, action_name=None): """ Get the thing's actions as an array. action_name -- Optional action name to get descriptions for Returns the action descriptions. """ descriptions = [] if action_name is None: for name in self...
def get_event_descriptions(self, event_name=None): """ Get the thing's events as an array. event_name -- Optional event name to get descriptions for Returns the event descriptions. """ if event_name is None: return [e.as_event_description() for e in self.eve...
def add_property(self, property_): """ Add a property to this thing. property_ -- property to add """ property_.set_href_prefix(self.href_prefix) self.properties[property_.name] = property_
def remove_property(self, property_): """ Remove a property from this thing. property_ -- property to remove """ if property_.name in self.properties: del self.properties[property_.name]
def get_property(self, property_name): """ Get a property's value. property_name -- the property to get the value of Returns the properties value, if found, else None. """ prop = self.find_property(property_name) if prop: return prop.get_value() ...
def get_properties(self): """ Get a mapping of all properties and their values. Returns a dictionary of property_name -> value. """ return {prop.get_name(): prop.get_value() for prop in self.properties.values()}
def set_property(self, property_name, value): """ Set a property value. property_name -- name of the property to set value -- value to set """ prop = self.find_property(property_name) if not prop: return prop.set_value(value)
def get_action(self, action_name, action_id): """ Get an action. action_name -- name of the action action_id -- ID of the action Returns the requested action if found, else None. """ if action_name not in self.actions: return None for action...
def add_event(self, event): """ Add a new event and notify subscribers. event -- the event that occurred """ self.events.append(event) self.event_notify(event)
def add_available_event(self, name, metadata): """ Add an available event. name -- name of the event metadata -- event metadata, i.e. type, description, etc., as a dict """ if metadata is None: metadata = {} self.available_events[name] = { ...
def perform_action(self, action_name, input_=None): """ Perform an action on the thing. action_name -- name of the action input_ -- any action inputs Returns the action that was created. """ if action_name not in self.available_actions: return None ...
def remove_action(self, action_name, action_id): """ Remove an existing action. action_name -- name of the action action_id -- ID of the action Returns a boolean indicating the presence of the action. """ action = self.get_action(action_name, action_id) ...
def add_available_action(self, name, metadata, cls): """ Add an available action. name -- name of the action metadata -- action metadata, i.e. type, description, etc., as a dict cls -- class to instantiate for this action """ if metadata is None: meta...
def remove_subscriber(self, ws): """ Remove a websocket subscriber. ws -- the websocket """ if ws in self.subscribers: self.subscribers.remove(ws) for name in self.available_events: self.remove_event_subscriber(name, ws)
def add_event_subscriber(self, name, ws): """ Add a new websocket subscriber to an event. name -- name of the event ws -- the websocket """ if name in self.available_events: self.available_events[name]['subscribers'].add(ws)
def remove_event_subscriber(self, name, ws): """ Remove a websocket subscriber from an event. name -- name of the event ws -- the websocket """ if name in self.available_events and \ ws in self.available_events[name]['subscribers']: self.avail...
def property_notify(self, property_): """ Notify all subscribers of a property change. property_ -- the property that changed """ message = json.dumps({ 'messageType': 'propertyStatus', 'data': { property_.name: property_.get_value(), ...
def action_notify(self, action): """ Notify all subscribers of an action status change. action -- the action whose status changed """ message = json.dumps({ 'messageType': 'actionStatus', 'data': action.as_action_description(), }) for sub...
def event_notify(self, event): """ Notify all subscribers of an event. event -- the event that occurred """ if event.name not in self.available_events: return message = json.dumps({ 'messageType': 'event', 'data': event.as_event_descr...
def annotate(self, **annotations): """Custom version of the standard annotate function that allows using field names as annotated fields. Normally, the annotate function doesn't allow you to use the name of an existing field on the model as the alias name. This version of the fu...
def update(self, **fields): """Updates all rows that match the filter.""" # build up the query to execute self._for_write = True if django.VERSION >= (2, 0): query = self.query.chain(UpdateQuery) else: query = self.query.clone(UpdateQuery) query._...
def on_conflict(self, fields: List[Union[str, Tuple[str]]], action, index_predicate: str=None): """Sets the action to take when conflicts arise when attempting to insert/create a new row. Arguments: fields: The fields the conflicts can occur in. action: ...
def bulk_insert(self, rows, return_model=False): """Creates multiple new records in the database. This allows specifying custom conflict behavior using .on_conflict(). If no special behavior was specified, this uses the normal Django create(..) Arguments: rows: ...
def insert(self, **fields): """Creates a new record in the database. This allows specifying custom conflict behavior using .on_conflict(). If no special behavior was specified, this uses the normal Django create(..) Arguments: fields: The fields of the row t...
def insert_and_get(self, **fields): """Creates a new record in the database and then gets the entire row. This allows specifying custom conflict behavior using .on_conflict(). If no special behavior was specified, this uses the normal Django create(..) Arguments: fi...
def upsert(self, conflict_target: List, fields: Dict, index_predicate: str=None) -> int: """Creates a new record or updates the existing one with the specified data. Arguments: conflict_target: Fields to pass into the ON CONFLICT clause. fields: ...
def upsert_and_get(self, conflict_target: List, fields: Dict, index_predicate: str=None): """Creates a new record or updates the existing one with the specified data and then gets the row. Arguments: conflict_target: Fields to pass into the ON CONFLICT clause. ...
def bulk_upsert(self, conflict_target: List, rows: List[Dict], index_predicate: str=None): """Creates a set of new records or updates the existing ones with the specified data. Arguments: conflict_target: Fields to pass into the ON CONFLICT clause. rows:...
def _build_insert_compiler(self, rows: List[Dict]): """Builds the SQL compiler for a insert query. Arguments: rows: A list of dictionaries, where each entry describes a record to insert. Returns: The SQL compiler for the insert. "...
def _is_magical_field(self, model_instance, field, is_insert: bool): """Verifies whether this field is gonna modify something on its own. "Magical" means that a field modifies the field value during the pre_save. Arguments: model_instance: The model ...
def _get_upsert_fields(self, kwargs): """Gets the fields to use in an upsert. This some nice magic. We'll split the fields into a group of "insert fields" and "update fields": INSERT INTO bla ("val1", "val2") ON CONFLICT DO UPDATE SET val1 = EXCLUDED.val1 ^^^^...
def on_conflict(self, fields: List[Union[str, Tuple[str]]], action, index_predicate: str=None): """Sets the action to take when conflicts arise when attempting to insert/create a new row. Arguments: fields: The fields the conflicts can occur in. action: ...
def upsert(self, conflict_target: List, fields: Dict, index_predicate: str=None) -> int: """Creates a new record or updates the existing one with the specified data. Arguments: conflict_target: Fields to pass into the ON CONFLICT clause. fields: ...
def upsert_and_get(self, conflict_target: List, fields: Dict, index_predicate: str=None): """Creates a new record or updates the existing one with the specified data and then gets the row. Arguments: conflict_target: Fields to pass into the ON CONFLICT clause. ...
def bulk_upsert(self, conflict_target: List, rows: List[Dict], index_predicate: str=None): """Creates a set of new records or updates the existing ones with the specified data. Arguments: conflict_target: Fields to pass into the ON CONFLICT clause. index...
def _on_model_save(sender, **kwargs): """When a model gets created or updated.""" created, instance = kwargs['created'], kwargs['instance'] if created: signals.create.send(sender, pk=instance.pk) else: signals.update.send(sender, pk=instance.pk)
def _on_model_delete(sender, **kwargs): """When a model gets deleted.""" instance = kwargs['instance'] signals.delete.send(sender, pk=instance.pk)
def IsNotNone(*fields, default=None): """Selects whichever field is not None, in the specified order. Arguments: fields: The fields to attempt to get a value from, in order. default: The value to return in case all values are None. Returns: A Ca...
def resolve_expression(self, *args, **kwargs): """Resolves expressions inside the dictionary.""" result = dict() for key, value in self.value.items(): if hasattr(value, 'resolve_expression'): result[key] = value.resolve_expression( *args, **kwargs...
def as_sql(self, compiler, connection): """Compiles the HStore value into SQL. Compiles expressions contained in the values of HStore entries as well. Given a dictionary like: dict(key1='val1', key2='val2') The resulting SQL will be: hstore(hstore('ke...
def as_sql(self, compiler, connection): """Compiles this expression into SQL.""" qn = compiler.quote_name_unless_alias return "%s.%s->'%s'" % (qn(self.alias), qn(self.target.column), self.hstore_key), []
def relabeled_clone(self, relabels): """Gets a re-labeled clone of this expression.""" return self.__class__( relabels.get(self.alias, self.alias), self.target, self.hstore_key, self.output_field )
def resolve_expression(self, *args, **kwargs) -> HStoreColumn: """Resolves the expression into a :see:HStoreColumn expression.""" original_expression = super().resolve_expression(*args, **kwargs) expression = HStoreColumn( original_expression.alias, original_expression.t...
def as_sql(self, compiler, connection): """Compiles this expression into SQL.""" sql, params = super().as_sql(compiler, connection) return 'EXTRACT(epoch FROM {})'.format(sql), params
def rename_annotations(self, annotations) -> None: """Renames the aliases for the specified annotations: .annotate(myfield=F('somestuf__myfield')) .rename_annotations(myfield='field') Arguments: annotations: The annotations to rename. Mapping the ...
def add_join_conditions(self, conditions: Dict[str, Any]) -> None: """Adds an extra condition to an existing JOIN. This allows you to for example do: INNER JOIN othertable ON (mytable.id = othertable.other_id AND [extra conditions]) This does not work if nothing else in your query...
def add_fields(self, field_names: List[str], allow_m2m: bool=True) -> bool: """ Adds the given (model) fields to the select set. The field names are added in the order specified. This overrides the base class's add_fields method. This is called by the .values() or .values_list()...
def _is_hstore_field(self, field_name: str) -> Tuple[bool, Optional[models.Field]]: """Gets whether the field with the specified name is a HStoreField. Returns A tuple of a boolean indicating whether the field with the specified name is a HStoreField, and the ...
def values(self, objs: List, insert_fields: List, update_fields: List=[]): """Sets the values to be used in this query. Insert fields are fields that are definitely going to be inserted, and if an existing row is found, are going to be overwritten with the specified value. ...
def create_model(self, model): """Ran when a new model is created.""" for field in model._meta.local_fields: if not isinstance(field, HStoreField): continue self.add_field(model, field)
def delete_model(self, model): """Ran when a model is being deleted.""" for field in model._meta.local_fields: if not isinstance(field, HStoreField): continue self.remove_field(model, field)
def alter_db_table(self, model, old_db_table, new_db_table): """Ran when the name of a model is changed.""" for field in model._meta.local_fields: if not isinstance(field, HStoreField): continue for key in self._iterate_required_keys(field): self...
def add_field(self, model, field): """Ran when a field is added to a model.""" for key in self._iterate_required_keys(field): self._create_hstore_required( model._meta.db_table, field, key )
def remove_field(self, model, field): """Ran when a field is removed from a model.""" for key in self._iterate_required_keys(field): self._drop_hstore_required( model._meta.db_table, field, key )
def alter_field(self, model, old_field, new_field, strict=False): """Ran when the configuration on a field changed.""" is_old_field_hstore = isinstance(old_field, HStoreField) is_new_field_hstore = isinstance(new_field, HStoreField) if not is_old_field_hstore and not is_new_field_hstor...
def _create_hstore_required(self, table_name, field, key): """Creates a REQUIRED CONSTRAINT for the specified hstore key.""" name = self._required_constraint_name( table_name, field, key) sql = self.sql_hstore_required_create.format( name=self.quote_name(name), ...
def _rename_hstore_required(self, old_table_name, new_table_name, old_field, new_field, key): """Renames an existing REQUIRED CONSTRAINT for the specified hstore key.""" old_name = self._required_constraint_name( old_table_name, old_field, key) ...
def _drop_hstore_required(self, table_name, field, key): """Drops a REQUIRED CONSTRAINT for the specified hstore key.""" name = self._required_constraint_name( table_name, field, key) sql = self.sql_hstore_required_drop.format( table=self.quote_name(table_name), ...
def _required_constraint_name(table: str, field, key): """Gets the name for a CONSTRAINT that applies to a single hstore key. Arguments: table: The name of the table the field is a part of. field: The hstore field to creat...
def create_sql(self, model, schema_editor, using=''): """Creates the actual SQL used when applying the migration.""" if django.VERSION >= (2, 0): statement = super().create_sql(model, schema_editor, using) statement.template = self.sql_create_index statement.parts['co...
def deconstruct(self): """Serializes the :see:ConditionalUniqueIndex for the migrations file.""" path = '%s.%s' % (self.__class__.__module__, self.__class__.__name__) path = path.replace('django.db.models.indexes', 'django.db.models') return path, (), {'fields': self.fields, 'name': self...
def create_command(text, commands): """Creates a custom setup.py command.""" class CustomCommand(BaseCommand): description = text def run(self): for cmd in commands: subprocess.check_call(cmd) return CustomCommand
def _get_backend_base(): """Gets the base class for the custom database back-end. This should be the Django PostgreSQL back-end. However, some people are already using a custom back-end from another package. We are nice people and expose an option that allows them to configure the back-end we base ...