INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Extract the tabulated data from the input file.
def process_data(self, stream, metadata): """ Extract the tabulated data from the input file. Parameters ---------- stream : Streamlike object A Streamlike object (nominally StringIO) containing the table to be extracted metadata : dict ...
stream: Streamlike object A Streamlike object ( nominally StringIO ) containing the data to be extracted
def _convert_data_block_and_headers_to_df(self, stream): """ stream : Streamlike object A Streamlike object (nominally StringIO) containing the data to be extracted ch : dict Column headers to use for the output pd.DataFrame Returns ------- ...
Determine the file variable from the filepath.
def _get_variable_from_filepath(self): """ Determine the file variable from the filepath. Returns ------- str Best guess of variable name from the filepath """ try: return self.regexp_capture_variable.search(self.filepath).group(1) ...
Parse the header for additional metadata.
def process_header(self, header): """ Parse the header for additional metadata. Parameters ---------- header : str All the lines in the header. Returns ------- dict The metadata in the header. """ metadata = {} ...
Read a data header line ensuring that it starts with the expected header
def _read_data_header_line(self, stream, expected_header): """Read a data header line, ensuring that it starts with the expected header Parameters ---------- stream : :obj:`StreamIO` Stream object containing the text to read expected_header : str, list of strs ...
Read out the next chunk of memory
def read_chunk(self, t): """ Read out the next chunk of memory Values in fortran binary streams begin and end with the number of bytes :param t: Data type (same format as used by struct). :return: Numpy array if the variable is an array, otherwise a scalar. """ s...
Extract the tabulated data from the input file
def process_data(self, stream, metadata): """ Extract the tabulated data from the input file # Arguments stream (Streamlike object): A Streamlike object (nominally StringIO) containing the table to be extracted metadata (dict): metadata read in from the header and th...
Reads the first part of the file to get some essential metadata
def process_header(self, data): """ Reads the first part of the file to get some essential metadata # Returns return (dict): the metadata in the header """ metadata = { "datacolumns": data.read_chunk("I"), "firstyear": data.read_chunk("I"), ...
Write a MAGICC input file from df and metadata
def write(self, magicc_input, filepath): """ Write a MAGICC input file from df and metadata Parameters ---------- magicc_input : :obj:`pymagicc.io.MAGICCData` MAGICCData object which holds the data to write filepath : str Filepath of the file to ...
Append any input which can be converted to MAGICCData to self.
def append(self, other, inplace=False, **kwargs): """ Append any input which can be converted to MAGICCData to self. Parameters ---------- other : MAGICCData, pd.DataFrame, pd.Series, str Source of data to append. inplace : bool If True, append `...
Write an input file to disk.
def write(self, filepath, magicc_version): """ Write an input file to disk. Parameters ---------- filepath : str Filepath of the file to write. magicc_version : int The MAGICC version for which we want to write files. MAGICC7 and MAGICC6 ...
Validates a set of attributes as identifiers in a spec
def validate_python_identifier_attributes(fully_qualified_name: str, spec: Dict[str, Any], *attributes: str) -> List[InvalidIdentifierError]: """ Validates a set of attributes as identifiers in a spec """ errors: List[InvalidIdentifierError] = [] checks: List[Tuple...
Validates to ensure that a set of attributes are present in spec
def validate_required_attributes(fully_qualified_name: str, spec: Dict[str, Any], *attributes: str) -> List[RequiredAttributeError]: """ Validates to ensure that a set of attributes are present in spec """ return [ RequiredAttributeError(fully_qualified_name, spec, attri...
Validates to ensure that a set of attributes do not contain empty values
def validate_empty_attributes(fully_qualified_name: str, spec: Dict[str, Any], *attributes: str) -> List[EmptyAttributeError]: """ Validates to ensure that a set of attributes do not contain empty values """ return [ EmptyAttributeError(fully_qualified_name, spec, attribute...
Validates to ensure that the value is a number of the specified type and lies with the specified range
def validate_number_attribute( fully_qualified_name: str, spec: Dict[str, Any], attribute: str, value_type: Union[Type[int], Type[float]] = int, minimum: Optional[Union[int, float]] = None, maximum: Optional[Union[int, float]] = None) -> Optional[InvalidNumberError]: ...
Validates to ensure that the value of an attribute lies within an allowed set of candidates
def validate_enum_attribute(fully_qualified_name: str, spec: Dict[str, Any], attribute: str, candidates: Set[Union[str, int, float]]) -> Optional[InvalidValueError]: """ Validates to ensure that the value of an attribute lies within an allowed set of candidates """ if attribute not ...
Parses a flat key string and returns a key
def parse(key_string: str) -> 'Key': """ Parses a flat key string and returns a key """ parts = key_string.split(Key.PARTITION) key_type = KeyType.DIMENSION if parts[3]: key_type = KeyType.TIMESTAMP return Key(key_type, parts[0], parts[1], parts[2].split(Key.DIMENSION...
Parses a flat key string and returns a key
def parse_sort_key(identity: str, sort_key_string: str) -> 'Key': """ Parses a flat key string and returns a key """ parts = sort_key_string.split(Key.PARTITION) key_type = KeyType.DIMENSION if parts[2]: key_type = KeyType.TIMESTAMP return Key(key_type, identity, part...
Checks if this key starts with the other key provided. Returns False if key_type identity or group are different. For KeyType. TIMESTAMP returns True. For KeyType. DIMENSION does prefix match between the two dimensions property.
def starts_with(self, other: 'Key') -> bool: """ Checks if this key starts with the other key provided. Returns False if key_type, identity or group are different. For `KeyType.TIMESTAMP` returns True. For `KeyType.DIMENSION` does prefix match between the two dimensions property....
Evaluates the dimension fields. Returns False if any of the fields could not be evaluated.
def _evaluate_dimension_fields(self) -> bool: """ Evaluates the dimension fields. Returns False if any of the fields could not be evaluated. """ for _, item in self._dimension_fields.items(): item.run_evaluate() if item.eval_error: return False ...
Compares the dimension field values to the value in regular fields.
def _compare_dimensions_to_fields(self) -> bool: """ Compares the dimension field values to the value in regular fields.""" for name, item in self._dimension_fields.items(): if item.value != self._nested_items[name].value: return False return True
Generates the Key object based on dimension fields.
def _key(self): """ Generates the Key object based on dimension fields. """ return Key(self._schema.key_type, self._identity, self._name, [str(item.value) for item in self._dimension_fields.values()])
Run a MAGICC scenario and return output data and ( optionally ) config parameters.
def run(scenario, magicc_version=6, **kwargs): """ Run a MAGICC scenario and return output data and (optionally) config parameters. As a reminder, putting ``out_parameters=1`` will cause MAGICC to write out its parameters into ``out/PARAMETERS.OUT`` and they will then be read into ``output.metadata...
Evaluates the anchor condition against the specified block.: param block: Block to run the anchor condition against.: return: True if the anchor condition is met otherwise False.
def run_evaluate(self, block: TimeAggregate) -> bool: """ Evaluates the anchor condition against the specified block. :param block: Block to run the anchor condition against. :return: True, if the anchor condition is met, otherwise, False. """ if self._anchor.evaluate_anc...
Injects the block start and end times
def extend_schema_spec(self) -> None: """ Injects the block start and end times """ super().extend_schema_spec() if self.ATTRIBUTE_FIELDS in self._spec: # Add new fields to the schema spec. Since `_identity` is added by the super, new elements are added after predefined_...
Constructs the spec for predefined fields that are to be included in the master spec prior to schema load: param name_in_context: Name of the current object in the context: return:
def _build_time_fields_spec(name_in_context: str) -> List[Dict[str, Any]]: """ Constructs the spec for predefined fields that are to be included in the master spec prior to schema load :param name_in_context: Name of the current object in the context :return: """ return [...
Apply a number of substitutions to a string ( s ).
def apply_string_substitutions( inputs, substitutions, inverse=False, case_insensitive=False, unused_substitutions="ignore", ): """Apply a number of substitutions to a string(s). The substitutions are applied effectively all at once. This means that conflicting substitutions don't inter...
Returns the list of items from the store based on the given time range or count.: param base_key: Items which don t start with the base_key are filtered out.: param start_time: Start time to for the range query: param end_time: End time of the range query. If None count is used.: param count: The number of items to be ...
def get_range(self, base_key: Key, start_time: datetime, end_time: datetime = None, count: int = 0) -> List[Tuple[Key, Any]]: """ Returns the list of items from the store based on the given time range or count. :param base_k...
Returns the list of items from the store based on the given time range or count.
def _get_range_timestamp_key(self, start: Key, end: Key, count: int = 0) -> List[Tuple[Key, Any]]: """ Returns the list of items from the store based on the given time range or count. This is used when the key being used is a TIMESTAMP key. """ r...
Returns the list of items from the store based on the given time range or count.
def _get_range_dimension_key(self, base_key: Key, start_time: datetime, end_time: datetime, count: int = 0) -> List[Tuple[Key, Any]]: """ Returns the list of items from the...
Restricts items to count number if len ( items ) is larger than abs ( count ). This function assumes that items is sorted by time.
def _restrict_items_to_count(items: List[Tuple[Key, Any]], count: int) -> List[Tuple[Key, Any]]: """ Restricts items to count number if len(items) is larger than abs(count). This function assumes that items is sorted by time. :param items: The items to restrict. :param count: Th...
Builds an expression object. Adds an error if expression creation has errors.
def build_expression(self, attribute: str) -> Optional[Expression]: """ Builds an expression object. Adds an error if expression creation has errors. """ expression_string = self._spec.get(attribute, None) if expression_string: try: return Expression(str(expression_...
Adds errors to the error repository in schema loader
def add_errors(self, *errors: Union[BaseSchemaError, List[BaseSchemaError]]) -> None: """ Adds errors to the error repository in schema loader """ self.schema_loader.add_errors(*errors)
Validates that the schema contains a series of required attributes
def validate_required_attributes(self, *attributes: str) -> None: """ Validates that the schema contains a series of required attributes """ self.add_errors( validate_required_attributes(self.fully_qualified_name, self._spec, *attributes))
Validates that the attribute contains a numeric value within boundaries if specified
def validate_number_attribute(self, attribute: str, value_type: Union[Type[int], Type[float]] = int, minimum: Optional[Union[int, float]] = None, maximum: Optional[Union[int, float]] =...
Validates that the attribute value is among the candidates
def validate_enum_attribute(self, attribute: str, candidates: Set[Union[str, int, float]]) -> None: """ Validates that the attribute value is among the candidates """ self.add_errors( validate_enum_attribute(self.fully_qualified_name, self._spec, attribute, ca...
Contains the validation routines that are to be executed as part of initialization by subclasses. When this method is being extended the first line should always be: super (). validate_schema_spec ()
def validate_schema_spec(self) -> None: """ Contains the validation routines that are to be executed as part of initialization by subclasses. When this method is being extended, the first line should always be: ```super().validate_schema_spec()``` """ self.add_errors( validate_empty_...
Returns True when: 1. Where clause is not specified 2. Where WHERE clause is specified and it evaluates to True Returns false if a where clause is specified and it evaluates to False
def _needs_evaluation(self) -> bool: """ Returns True when: 1. Where clause is not specified 2. Where WHERE clause is specified and it evaluates to True Returns false if a where clause is specified and it evaluates to False """ return self._schema.when is ...
Evaluates the current item: returns An evaluation result object containing the result or reasons why evaluation failed
def run_evaluate(self, *args, **kwargs) -> None: """ Evaluates the current item :returns An evaluation result object containing the result, or reasons why evaluation failed """ if self._needs_evaluation: for _, item in self._nested_items.items(): ...
Implements snapshot for collections by recursively invoking snapshot of all child items
def _snapshot(self) -> Dict[str, Any]: """ Implements snapshot for collections by recursively invoking snapshot of all child items """ try: return {name: item._snapshot for name, item in self._nested_items.items()} except Exception as e: raise SnapshotErro...
Restores the state of a collection from a snapshot
def run_restore(self, snapshot: Dict[Union[str, Key], Any]) -> 'BaseItemCollection': """ Restores the state of a collection from a snapshot """ try: for name, snap in snapshot.items(): if isinstance(name, Key): self._nested_items[name.grou...
Prepares window if any is specified.: param start_time: The anchor block start_time from where the window should be generated.
def _prepare_window(self, start_time: datetime) -> None: """ Prepares window if any is specified. :param start_time: The anchor block start_time from where the window should be generated. """ # evaluate window first which sets the correct window in the store store...
Generates the end time to be used for the store range query.: param start_time: Start time to use as an offset to calculate the end time based on the window type in the schema.: return:
def _get_end_time(self, start_time: datetime) -> datetime: """ Generates the end time to be used for the store range query. :param start_time: Start time to use as an offset to calculate the end time based on the window type in the schema. :return: """ if Type.is_...
Converts [ ( Key block ) ] to [ BlockAggregate ]: param blocks: List of ( Key block ) blocks.: return: List of BlockAggregate
def _load_blocks(self, blocks: List[Tuple[Key, Any]]) -> List[TimeAggregate]: """ Converts [(Key, block)] to [BlockAggregate] :param blocks: List of (Key, block) blocks. :return: List of BlockAggregate """ return [ TypeLoader.load_item(self._schema.source.type...
Executes the streaming and window BTS on the given records. An option old state can provided which initializes the state for execution. This is useful for batch execution where the previous state is written out to storage and can be loaded for the next batch run.
def execute_per_identity_records( self, identity: str, records: List[TimeAndRecord], old_state: Optional[Dict[Key, Any]] = None) -> Tuple[str, Tuple[Dict, List]]: """ Executes the streaming and window BTS on the given records. An option old state can provi...
Uses the given iteratable events and the data processor convert the event into a list of Records along with its identity and time.: param events: iteratable events.: param data_processor: DataProcessor to process each event in events.: return: yields Tuple [ Identity TimeAndRecord ] for all Records in events
def get_per_identity_records(self, events: Iterable, data_processor: DataProcessor ) -> Generator[Tuple[str, TimeAndRecord], None, None]: """ Uses the given iteratable events and the data processor convert the event into a list of Records along with its identity ...
String representation with additional information
def to_string(self, hdr, other): """String representation with additional information""" result = "%s[%s,%s" % ( hdr, self.get_type(self.type), self.get_clazz(self.clazz)) if self.unique: result += "-unique," else: result += "," result += s...
Returns true if the question is answered by the record
def answered_by(self, rec): """Returns true if the question is answered by the record""" return self.clazz == rec.clazz and \ (self.type == rec.type or self.type == _TYPE_ANY) and \ self.name == rec.name
Sets this record s TTL and created time to that of another record.
def reset_ttl(self, other): """Sets this record's TTL and created time to that of another record.""" self.created = other.created self.ttl = other.ttl
String representation with addtional information
def to_string(self, other): """String representation with addtional information""" arg = "%s/%s,%s" % ( self.ttl, self.get_remaining_ttl(current_time_millis()), other) return DNSEntry.to_string(self, "record", arg)
Used in constructing an outgoing packet
def write(self, out): """Used in constructing an outgoing packet""" out.write_string(self.address, len(self.address))
Used in constructing an outgoing packet
def write(self, out): """Used in constructing an outgoing packet""" out.write_string(self.cpu, len(self.cpu)) out.write_string(self.os, len(self.os))
Used in constructing an outgoing packet
def write(self, out): """Used in constructing an outgoing packet""" out.write_string(self.text, len(self.text))
Update only one property in the dict
def set_property(self, key, value): """ Update only one property in the dict """ self.properties[key] = value self.sync_properties()
Used in constructing an outgoing packet
def write(self, out): """Used in constructing an outgoing packet""" out.write_short(self.priority) out.write_short(self.weight) out.write_short(self.port) out.write_name(self.server)
Reads header portion of packet
def read_header(self): """Reads header portion of packet""" format = '!HHHHHH' length = struct.calcsize(format) info = struct.unpack(format, self.data[self.offset:self.offset + length]) self.offset += length self.id = info[0] self.flags = info[1] ...
Reads questions section of packet
def read_questions(self): """Reads questions section of packet""" format = '!HH' length = struct.calcsize(format) for i in range(0, self.num_questions): name = self.read_name() info = struct.unpack(format, self.data[self.offset:self.offset + le...
Reads an integer from the packet
def read_int(self): """Reads an integer from the packet""" format = '!I' length = struct.calcsize(format) info = struct.unpack(format, self.data[self.offset:self.offset + length]) self.offset += length return info[0]
Reads a character string from the packet
def read_character_string(self): """Reads a character string from the packet""" length = ord(self.data[self.offset]) self.offset += 1 return self.read_string(length)
Reads a string of a given length from the packet
def read_string(self, len): """Reads a string of a given length from the packet""" format = '!' + str(len) + 's' length = struct.calcsize(format) info = struct.unpack(format, self.data[self.offset:self.offset + length]) self.offset += length return info[0]
Reads the answers authorities and additionals section of the packet
def read_others(self): """Reads the answers, authorities and additionals section of the packet""" format = '!HHiH' length = struct.calcsize(format) n = self.num_answers + self.num_authorities + self.num_additionals for i in range(0, n): domain = self.read_name...
Reads a UTF - 8 string of a given length from the packet
def read_utf(self, offset, len): """Reads a UTF-8 string of a given length from the packet""" try: result = self.data[offset:offset + len].decode('utf-8') except UnicodeDecodeError: result = str('') return result
Reads a domain name from the packet
def read_name(self): """Reads a domain name from the packet""" result = '' off = self.offset next = -1 first = off while 1: len = ord(self.data[off]) off += 1 if len == 0: break t = len & 0xC0 if...
Adds an answer
def add_answer(self, inp, record): """Adds an answer""" if not record.suppressed_by(inp): self.add_answer_at_time(record, 0)
Adds an answer if if does not expire by a certain time
def add_answer_at_time(self, record, now): """Adds an answer if if does not expire by a certain time""" if record is not None: if now == 0 or not record.is_expired(now): self.answers.append((record, now)) if record.rrsig is not None: self.a...
Writes a single byte to the packet
def write_byte(self, value): """Writes a single byte to the packet""" format = '!B' self.data.append(struct.pack(format, value)) self.size += 1
Inserts an unsigned short in a certain position in the packet
def insert_short(self, index, value): """Inserts an unsigned short in a certain position in the packet""" format = '!H' self.data.insert(index, struct.pack(format, value)) self.size += 2
Writes an unsigned integer to the packet
def write_int(self, value): """Writes an unsigned integer to the packet""" format = '!I' self.data.append(struct.pack(format, int(value))) self.size += 4
Writes a string to the packet
def write_string(self, value, length): """Writes a string to the packet""" format = '!' + str(length) + 's' self.data.append(struct.pack(format, value)) self.size += length
Writes a UTF - 8 string of a given length to the packet
def write_utf(self, s): """Writes a UTF-8 string of a given length to the packet""" utfstr = s.encode('utf-8') length = len(utfstr) if length > 64: raise NamePartTooLongException self.write_byte(length) self.write_string(utfstr, length)
Writes a domain name to the packet
def write_name(self, name): """Writes a domain name to the packet""" try: # Find existing instance of this name in packet # index = self.names[name] except KeyError: # No record of this name already, so write it # out as normal, record...
Writes a question to the packet
def write_question(self, question): """Writes a question to the packet""" self.write_name(question.name) self.write_short(question.type) self.write_short(question.clazz)
Writes a record ( answer authoritative answer additional ) to the packet
def write_record(self, record, now): """Writes a record (answer, authoritative answer, additional) to the packet""" self.write_name(record.name) self.write_short(record.type) if record.unique and self.multicast: self.write_short(record.clazz | _CLASS_UNIQUE) e...
Returns a string containing the packet s bytes
def packet(self): """Returns a string containing the packet's bytes No further parts should be added to the packet once this is done.""" if not self.finished: self.finished = 1 for question in self.questions: self.write_question(question) ...
Adds an entry
def add(self, entry): """Adds an entry""" if self.get(entry) is not None: return try: list = self.cache[entry.key] except: list = self.cache[entry.key] = [] list.append(entry)
Adds and sign an entry
def sign(self, entry, signer=None): """Adds and sign an entry""" if (self.get(entry) is not None): return if (entry.rrsig is None) and (self.private is not None): entry.rrsig = DNSSignatureS(entry.name, _TYPE_RRSIG, _CLASS_IN, entry, self.private, sign...
Removes an entry
def remove(self, entry): """Removes an entry""" try: list = self.cache[entry.key] list.remove(entry) except: pass
Gets an entry by key. Will return None if there is no matching entry.
def get(self, entry): """Gets an entry by key. Will return None if there is no matching entry.""" try: list = self.cache[entry.key] return list[list.index(entry)] except: return None
Gets an entry by details. Will return None if there is no matching entry.
def get_by_details(self, name, type, clazz): """Gets an entry by details. Will return None if there is no matching entry.""" entry = DNSEntry(name, type, clazz) return self.get(entry)
Returns a list of all entries
def entries(self): """Returns a list of all entries""" def add(x, y): return x + y try: return reduce(add, list(self.cache.values())) except: return []
Callback invoked by Zeroconf when new information arrives.
def update_record(self, zeroconf, now, record): """Callback invoked by Zeroconf when new information arrives. Updates information required by browser in the Zeroconf cache.""" if record.type == _TYPE_PTR and record.name == self.type: expired = record.is_expired(now) try:...
Sets properties and text of this info from a dictionary
def set_properties(self, properties): """Sets properties and text of this info from a dictionary""" if isinstance(properties, dict): self.properties = properties self.sync_properties() else: self.text = properties
Sets properties and text given a text field
def set_text(self, text): """Sets properties and text given a text field""" self.text = text try: self.properties = text_to_dict(text) except: traceback.print_exc() self.properties = None
Name accessor
def get_name(self): """Name accessor""" if self.type is not None and self.name.endswith("." + self.type): return self.name[:len(self.name) - len(self.type) - 1] return self.name
Updates service information from a DNS record
def update_record(self, zeroconf, now, record): """Updates service information from a DNS record""" if record is not None and not record.is_expired(now): if record.type == _TYPE_A: if record.name == self.name: if not record.address in self.address: ...
Returns true if the service could be discovered on the network and updates this object with details discovered.
def request(self, zeroconf, timeout): """Returns true if the service could be discovered on the network, and updates this object with details discovered. """ now = current_time_millis() delay = _LISTENER_TIME next = now + delay last = now + timeout result ...
Calling thread waits for a given number of milliseconds or until notified.
def wait(self, timeout): """Calling thread waits for a given number of milliseconds or until notified.""" self.condition.acquire() self.condition.wait(timeout // 1000) self.condition.release()
Notifies all waiting threads
def notify_all(self): """Notifies all waiting threads""" self.condition.acquire() # python 3.x try: self.condition.notify_all() except: self.condition.notifyAll() self.condition.release()
Returns network s service information for a particular name and type or None if no service matches by the timeout which defaults to 3 seconds.
def get_service_info(self, type, name, timeout=3000): """Returns network's service information for a particular name and type, or None if no service matches by the timeout, which defaults to 3 seconds.""" info = ServiceInfo(type, name) if info.request(self, timeout): ...
Adds a listener for a particular service type. This object will then have its update_record method called when information arrives for that type.
def add_serviceListener(self, type, listener): """Adds a listener for a particular service type. This object will then have its update_record method called when information arrives for that type.""" self.remove_service_listener(listener) self.browsers.append(ServiceBrowser(self,...
Removes a listener from the set that is currently listening.
def remove_service_listener(self, listener): """Removes a listener from the set that is currently listening.""" for browser in self.browsers: if browser.listener == listener: browser.cancel() del(browser)
Registers service information to the network with a default TTL of 60 seconds. Zeroconf will then respond to requests for information for that service. The name of the service may be changed if needed to make it unique on the network.
def register_service(self, info): """Registers service information to the network with a default TTL of 60 seconds. Zeroconf will then respond to requests for information for that service. The name of the service may be changed if needed to make it unique on the network.""" sel...
Unregister a service.
def unregister_service(self, info): """Unregister a service.""" try: del(self.services[info.name.lower()]) except: pass now = current_time_millis() next_time = now i = 0 while i < 3: if now < next_time: self.wait...
Checks the network for a unique service name modifying the ServiceInfo passed in if it is not unique.
def check_service(self, info): """Checks the network for a unique service name, modifying the ServiceInfo passed in if it is not unique.""" now = current_time_millis() next_time = now i = 0 while i < 3: for record in self.cache.entries_with_name(info.type): ...
Adds a listener for a given question. The listener will have its update_record method called when information is available to answer the question.
def add_listener(self, listener, question): """Adds a listener for a given question. The listener will have its update_record method called when information is available to answer the question.""" now = current_time_millis() self.listeners.append(listener) if question is...
Used to notify listeners of new information that has updated a record.
def update_record(self, now, rec): """Used to notify listeners of new information that has updated a record.""" for listener in self.listeners: listener.update_record(self, now, rec) self.notify_all()
Deal with incoming response packets. All answers are held in the cache and listeners are notified.
def handle_response(self, msg, address): """Deal with incoming response packets. All answers are held in the cache, and listeners are notified.""" now = current_time_millis() sigs = [] precache = [] for record in msg.answers: if isinstance(record, DNSSignat...
Deal with incoming query packets. Provides a response if possible.
def handle_query(self, msg, addr, port, orig): """ Deal with incoming query packets. Provides a response if possible. msg - message to process addr - dst addr port - dst port orig - originating address (for adaptive records) """ out =...
Sends an outgoing packet.
def send(self, out, addr=_MDNS_ADDR, port=_MDNS_PORT): """Sends an outgoing packet.""" # This is a quick test to see if we can parse the packets we generate #temp = DNSIncoming(out.packet()) for i in self.intf.values(): try: return i.sendto(out.packet(), 0, (a...
Ends the background threads and prevent this instance from servicing further queries.
def close(self): """Ends the background threads, and prevent this instance from servicing further queries.""" if globals()['_GLOBAL_DONE'] == 0: globals()['_GLOBAL_DONE'] = 1 self.notify_all() self.engine.notify() self.unregister_all_services() ...