text stringlengths 81 112k |
|---|
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:
... |
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.
Updates information required by browser in the Zeroconf cache.
def update_record(self, zeroconf, now, record):
"""Callback invoked by Zeroconf when new information arrives.
Updates information required by browser in the Zeroconf cache... |
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 = ... |
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:
... |
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 = cu... |
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 s... |
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_reco... |
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(br... |
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 ser... |
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:
... |
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_tim... |
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 calle... |
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_a... |
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()
s... |
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)
def handle_query(self, msg, addr, port, orig):
"""
Deal with incoming query... |
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... |
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
s... |
Executes Blurr BTS with the given records. old_state_rdd can be provided to load an older
state from a previous run.
:param identity_records: RDD of the form Tuple[Identity, List[TimeAndRecord]]
:param old_state_rdd: A previous streaming BTS state RDD as Tuple[Identity, Streaming BTS
... |
Reads the data from the given json_files path and converts them into the `Record`s format for
processing. `data_processor` is used to process the per event data in those files to convert
them into `Record`.
:param json_files: List of json file paths. Regular Spark path wildcards are accepted.
... |
Converts a RDD of raw events into the `Record`s format for processing. `data_processor` is
used to process the per row data to convert them into `Record`.
:param rdd: RDD containing the raw events.
:param data_processor: `DataProcessor` to process each row in the given `rdd`.
:return: R... |
Basic helper function to persist data to disk.
If window BTS was provided then the window BTS output to written in csv format, otherwise,
the streaming BTS output is written in JSON format to the `path` provided
:param path: Path where the output should be written.
:param per_identity_... |
Basic helper function to write data to stdout. If window BTS was provided then the window
BTS output is written, otherwise, the streaming BTS output is written to stdout.
WARNING - For large datasets this will be extremely slow.
:param per_identity_data: Output of the `execute()` call.
def pr... |
As distutils.spawn.find_executable, but on Windows, look up
every extension declared in PATHEXT instead of just `.exe`
def find_executable(executable, path=None):
"""
As distutils.spawn.find_executable, but on Windows, look up
every extension declared in PATHEXT instead of just `.exe`
"""
if sy... |
Create and return a copy of os.environ with the specified overrides
def create_environment_dict(overrides):
"""
Create and return a copy of os.environ with the specified overrides
"""
result = os.environ.copy()
result.update(overrides or {})
return result |
Retrieve credentials for `server`. If no credentials are found,
a `StoreError` will be raised.
def get(self, server):
""" Retrieve credentials for `server`. If no credentials are found,
a `StoreError` will be raised.
"""
if not isinstance(server, six.binary_type):
... |
Store credentials for `server`. Raises a `StoreError` if an error
occurs.
def store(self, server, username, secret):
""" Store credentials for `server`. Raises a `StoreError` if an error
occurs.
"""
data_input = json.dumps({
'ServerURL': server,
'... |
Erase credentials for `server`. Raises a `StoreError` if an error
occurs.
def erase(self, server):
""" Erase credentials for `server`. Raises a `StoreError` if an error
occurs.
"""
if not isinstance(server, six.binary_type):
server = server.encode('utf-8')
... |
Evaluates and returns the identity as specified in the schema.
:param record: Record which is used to determine the identity.
:return: The evaluated identity
:raises: IdentityError if identity cannot be determined.
def get_identity(self, record: Record) -> str:
"""
Evaluates and... |
Evaluates and updates data in the StreamingTransformer.
:param record: The 'source' record used for the update.
:raises: IdentityError if identity is different from the one used during
initialization.
def run_evaluate(self, record: Record):
"""
Evaluates and updates data in the ... |
Injects the identity field
def extend_schema_spec(self) -> None:
""" Injects the identity field """
super().extend_schema_spec()
identity_field = {
'Name': '_identity',
'Type': BtsType.STRING,
'Value': 'identity',
ATTRIBUTE_INTERNAL: True
... |
Persists the current data group
def _persist(self) -> None:
"""
Persists the current data group
"""
if self._store:
self._store.save(self._key, self._snapshot) |
Add a schema dictionary to the schema loader. The given schema is stored
against fully_qualified_parent_name + ITEM_SEPARATOR('.') + schema.name.
:param spec: Schema specification.
:param fully_qualified_parent_name: Full qualified name of the parent.
If None is passed then the schema is... |
Adds errors to the error store for the schema
def add_errors(self, *errors: Union[BaseSchemaError, SchemaErrorCollection]) -> None:
""" Adds errors to the error store for the schema """
for error in errors:
self._error_cache.add(error) |
Used to generate a schema object from the given fully_qualified_name.
:param fully_qualified_name: The fully qualified name of the object needed.
:return: An initialized schema object
def get_schema_object(self, fully_qualified_name: str) -> 'BaseSchema':
"""
Used to generate a schema o... |
Used to generate a store object from the given fully_qualified_name.
:param fully_qualified_name: The fully qualified name of the store object needed.
:return: An initialized store object
def get_store(self, fully_qualified_name: str) -> Optional['Store']:
"""
Used to generate a store o... |
Used to generate a schema object from the given fully_qualified_parent_name
and the nested_item_name.
:param fully_qualified_parent_name: The fully qualified name of the parent.
:param nested_item_name: The nested item name.
:return: An initialized schema object of the nested item.
def ... |
Returns the fully qualified name by combining the fully_qualified_parent_name
and nested_item_name.
:param fully_qualified_parent_name: The fully qualified name of the parent.
:param nested_item_name: The nested item name.
:return: The fully qualified name of the nested item.
def get_fu... |
Used to retrieve the specifications of the schema from the given
fully_qualified_name of schema.
:param fully_qualified_name: The fully qualified name of the schema needed.
:return: Schema dictionary.
def get_schema_spec(self, fully_qualified_name: str) -> Dict[str, Any]:
"""
Us... |
Returns a list of fully qualified names and schema dictionary tuples for
the schema types provided.
:param schema_types: Schema types.
:return: List of fully qualified names and schema dictionary tuples.
def get_schema_specs_of_type(self, *schema_types: Type) -> Dict[str, Dict[str, Any]]:
... |
Adds a key and value to the global dictionary
def global_add(self, key: str, value: Any) -> None:
"""
Adds a key and value to the global dictionary
"""
self.global_context[key] = value |
Merges the provided evaluation context to the current evaluation context.
:param evaluation_context: Evaluation context to merge.
def merge(self, evaluation_context: 'EvaluationContext') -> None:
"""
Merges the provided evaluation context to the current evaluation context.
:param evalua... |
Evaluates the expression with the context provided. If the execution
results in failure, an ExpressionEvaluationException encapsulating the
underlying exception is raised.
:param evaluation_context: Global and local context dictionary to be passed for evaluation
def evaluate(self, evaluation_c... |
Copy all the files in source directory to target.
Ignores subdirectories.
def _copy_files(source, target):
"""
Copy all the files in source directory to target.
Ignores subdirectories.
"""
source_files = listdir(source)
if not exists(target):
makedirs(target)
for filename in s... |
Initialises a temporary directory structure and copy of MAGICC
configuration files and binary.
def create_copy(self):
"""
Initialises a temporary directory structure and copy of MAGICC
configuration files and binary.
"""
if self.executable is None or not isfile(self.exec... |
Run MAGICC and parse the output.
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["parameters"]`` where ``output`` is the returned object.
Parameters
---------... |
Check that our MAGICC ``.CFG`` files are set to safely work with PYMAGICC
For further detail about why this is required, please see :ref:`MAGICC flags`.
Raises
------
ValueError
If we are not certain that the config written by PYMAGICC will overwrite
all other c... |
Write an input file to disk
Parameters
----------
mdata : :obj:`pymagicc.io.MAGICCData`
A MAGICCData instance with the data to write
name : str
The name of the file to write. The file will be written to the MAGICC
instance's run directory i.e. ``self... |
Read a parameters.out file
Returns
-------
dict
A dictionary containing all the configuration used by MAGICC
def read_parameters(self):
"""
Read a parameters.out file
Returns
-------
dict
A dictionary containing all the configura... |
Removes a temporary copy of the MAGICC version shipped with Pymagicc.
def remove_temp_copy(self):
"""
Removes a temporary copy of the MAGICC version shipped with Pymagicc.
"""
if self.is_temp and self.root_dir is not None:
shutil.rmtree(self.root_dir)
self.root_d... |
Create a configuration file for MAGICC.
Writes a fortran namelist in run_dir.
Parameters
----------
filename : str
Name of configuration file to write
top_level_key : str
Name of namelist to be written in the
configuration file
kwar... |
Updates a configuration file for MAGICC
Updates the contents of a fortran namelist in the run directory,
creating a new namelist if none exists.
Parameters
----------
filename : str
Name of configuration file to write
top_level_key : str
Name of... |
Set config such that radiative forcing and temperature output will be zero
This method is intended as a convenience only, it does not handle everything in
an obvious way. Adjusting the parameter settings still requires great care and
may behave unepexctedly.
def set_zero_config(self):
... |
Set the start and end dates of the simulations.
Parameters
----------
startyear : int
Start year of the simulation
endyear : int
End year of the simulation
Returns
-------
dict
The contents of the namelist
def set_years(self... |
Set the output configuration, minimising output as much as possible
There are a number of configuration parameters which control which variables
are written to file and in which format. Limiting the variables that are
written to file can greatly speed up the running of MAGICC. By default,
... |
Diagnose TCR and ECS
The transient climate response (TCR), is the global-mean temperature response
at time at which atmopsheric |CO2| concentrations double in a scenario where
atmospheric |CO2| concentrations are increased at 1% per year from
pre-industrial levels.
The equilibr... |
Set the emissions flags correctly.
Parameters
----------
scenario : :obj:`pymagicc.io.MAGICCData`
Scenario to run.
config_dict : dict
Dictionary with current input configurations which is to be validated and
updated where necessary.
Returns
... |
Checks if a type is defined
def contains(value: Union[str, 'Type']) -> bool:
""" Checks if a type is defined """
if isinstance(value, str):
return any(value.lower() == i.value for i in Type)
return any(value == i for i in Type) |
Read the content of an XML template file (XMLT), apply the given
`replacements` to its substitution markers, and write the result into
an XML file with the same name but ending with `xml` instead of `xmlt`.
First, we write an XMLT file, containing a regular HTML comment, a
readily defined element `e1`... |
Return the required indexes based on the given lambda function
and the |Timegrids| object handled by module |pub|. Raise a
|RuntimeError| if the latter is not available.
def _calcidxs(func):
"""Return the required indexes based on the given lambda function
and the |Timegrids| object ha... |
Day of the year index (the first of January = 0...).
For reasons of consistency between leap years and non-leap years,
assuming a daily time step, index 59 is always associated with the
29th of February. Hence, it is missing in non-leap years:
>>> from hydpy import pub
>>> fro... |
Time of the year index (first simulation step of each year = 0...).
The property |Indexer.timeofyear| is best explained through
comparing it with property |Indexer.dayofyear|:
Let us reconsider one of the examples of the documentation on
property |Indexer.dayofyear|:
>>> from ... |
Assign the given docstring to the property instance and, if
possible, to the `__test__` dictionary of the module of its
owner class.
def set_doc(self, doc: str):
"""Assign the given docstring to the property instance and, if
possible, to the `__test__` dictionary of the module of its
... |
Add the given getter function and its docstring to the
property and return it.
def getter_(self, fget) -> 'BaseProperty':
"""Add the given getter function and its docstring to the
property and return it."""
self.fget = fget
self.set_doc(fget.__doc__)
return self |
Return |True| or |False| to indicate if the protected
property is ready for the given object. If the object is
unknow, |ProtectedProperty| returns |False|.
def isready(self, obj) -> bool:
"""Return |True| or |False| to indicate if the protected
property is ready for the given object. ... |
Return |True| or |False| to indicate whether all protected
properties are ready or not.
def allready(self, obj) -> bool:
"""Return |True| or |False| to indicate whether all protected
properties are ready or not."""
for prop in self.__properties:
if not prop.isready(obj):
... |
Return the predefined custom value when available, otherwise,
the value defined by the getter function.
def call_fget(self, obj) -> Any:
"""Return the predefined custom value when available, otherwise,
the value defined by the getter function."""
custom = vars(obj).get(self.name)
... |
Store the given custom value and call the setter function.
def call_fset(self, obj, value) -> None:
"""Store the given custom value and call the setter function."""
vars(obj)[self.name] = self.fset(obj, value) |
Remove the predefined custom value and call the delete function.
def call_fdel(self, obj) -> None:
"""Remove the predefined custom value and call the delete function."""
self.fdel(obj)
try:
del vars(obj)[self.name]
except KeyError:
pass |
Trim upper values in accordance with :math:`RelWB \\leq RelWZ`.
>>> from hydpy.models.lland import *
>>> parameterstep('1d')
>>> nhru(3)
>>> lnk(ACKER)
>>> relwb.values = 0.5
>>> relwz(0.2, 0.5, 0.8)
>>> relwz
relwz(0.5, 0.5, 0.8)
def trim(self, lower=No... |
Trim upper values in accordance with :math:`RelWB \\leq RelWZ`.
>>> from hydpy.models.lland import *
>>> parameterstep('1d')
>>> nhru(3)
>>> lnk(ACKER)
>>> relwz.values = 0.5
>>> relwb(0.2, 0.5, 0.8)
>>> relwb
relwb(0.2, 0.5, 0.5)
def trim(self, lower=No... |
Trim upper values in accordance with :math:`EQI1 \\leq EQB`.
>>> from hydpy.models.lland import *
>>> parameterstep('1d')
>>> eqi1.value = 2.0
>>> eqb(1.0)
>>> eqb
eqb(2.0)
>>> eqb(2.0)
>>> eqb
eqb(2.0)
>>> eqb(3.0)
>>> eqb
... |
Trim upper values in accordance with
:math:`EQI2 \\leq EQI1 \\leq EQB`.
>>> from hydpy.models.lland import *
>>> parameterstep('1d')
>>> eqb.value = 3.0
>>> eqi2.value = 1.0
>>> eqi1(0.0)
>>> eqi1
eqi1(1.0)
>>> eqi1(1.0)
>>> eqi1
e... |
Return digital time choices every half hour from 00:00 to 23:30.
def time_choices():
"""Return digital time choices every half hour from 00:00 to 23:30."""
hours = list(range(0, 24))
times = []
for h in hours:
hour = str(h).zfill(2)
times.append(hour+':00')
times.append(hour+':3... |
Return autodoc commands for a basemodels docstring.
Note that `collection classes` (e.g. `Model`, `ControlParameters`,
`InputSequences` are placed on top of the respective section and the
`contained classes` (e.g. model methods, `ControlParameter` instances,
`InputSequence` instances at the bottom. Th... |
Add an exhaustive docstring to the given module of a basemodel.
Works onlye when all modules of the basemodel are named in the
standard way, e.g. `lland_model`, `lland_control`, `lland_inputs`.
def autodoc_basemodel(module):
"""Add an exhaustive docstring to the given module of a basemodel.
Works onl... |
Improves the docstrings of application models when called
at the bottom of the respective module.
|autodoc_applicationmodel| requires, similar to
|autodoc_basemodel|, that both the application model and its
base model are defined in the conventional way.
def autodoc_applicationmodel(module):
"""Im... |
Prepare and return a |Substituter| object for the main `__init__`
file of *HydPy*.
def prepare_mainsubstituter():
"""Prepare and return a |Substituter| object for the main `__init__`
file of *HydPy*."""
substituter = Substituter()
for module in (builtins, numpy, datetime, unittest, doctest, inspect... |
Try to return the number of the first line of the definition of a
member of a module.
def _number_of_line(member_tuple):
"""Try to return the number of the first line of the definition of a
member of a module."""
member = member_tuple[1]
try:
return member.__code__.co_firstlineno
except... |
Add a short summary of all implemented members to a modules docstring.
def autodoc_module(module):
"""Add a short summary of all implemented members to a modules docstring.
"""
doc = getattr(module, '__doc__')
if doc is None:
doc = ''
members = []
for name, member in inspect.getmembers(... |
Include tuples as `CLASSES` of `ControlParameters` and `RUN_METHODS`
of `Models` into the respective docstring.
def autodoc_tuple2doc(module):
"""Include tuples as `CLASSES` of `ControlParameters` and `RUN_METHODS`
of `Models` into the respective docstring."""
modulename = module.__name__
for membe... |
Return |True| if the given member should be added to the
substitutions. If not return |False|.
Some examples based on the site-package |numpy|:
>>> from hydpy.core.autodoctools import Substituter
>>> import numpy
A constant like |nan| should be added:
>>> Substituter.... |
Return the reStructuredText role `func`, `class`, or `const`
best describing the given member.
Some examples based on the site-package |numpy|. |numpy.clip|
is a function:
>>> from hydpy.core.autodoctools import Substituter
>>> import numpy
>>> Substituter.get_role(num... |
Add the given substitutions both as a `short2long` and a
`medium2long` mapping.
Assume `variable1` is defined in the hydpy module `module1` and the
short and medium descriptions are `var1` and `mod1.var1`:
>>> import types
>>> module1 = types.ModuleType('hydpy.module1')
... |
Add the given module, its members, and their submembers.
The first examples are based on the site-package |numpy|: which
is passed to method |Substituter.add_module|:
>>> from hydpy.core.autodoctools import Substituter
>>> substituter = Substituter()
>>> import numpy
>>... |
Add the modules of the given package without their members.
def add_modules(self, package):
"""Add the modules of the given package without their members."""
for name in os.listdir(package.__path__[0]):
if name.startswith('_'):
continue
name = name.split('.')[0]
... |
Update all `master` |Substituter| objects.
If a |Substituter| object is passed to the constructor of another
|Substituter| object, they become `master` and `slave`:
>>> from hydpy.core.autodoctools import Substituter
>>> sub1 = Substituter()
>>> from hydpy.core import devicetoo... |
Update all `slave` |Substituter| objects.
See method |Substituter.update_masters| for further information.
def update_slaves(self):
"""Update all `slave` |Substituter| objects.
See method |Substituter.update_masters| for further information.
"""
for slave in self.slaves:
... |
Return a string containing multiple `reStructuredText`
replacements with the substitutions currently defined.
Some examples based on the subpackage |optiontools|:
>>> from hydpy.core.autodoctools import Substituter
>>> substituter = Substituter()
>>> from hydpy.core import opti... |
Print all substitutions that include the given text string.
def find(self, text):
"""Print all substitutions that include the given text string."""
for key, value in self:
if (text in key) or (text in value):
print(key, value) |
Add print commands time to the given function informing about
execution time.
To show how the |print_progress| decorator works, we need to modify the
functions used by |print_progress| to gain system time information
available in module |time|.
First, we mock the functions |time.strftime| and |ti... |
Print a simple progress bar while processing the given iterable.
Function |progressbar| does print the progress bar when option
`printprogress` is activted:
>>> from hydpy import pub
>>> pub.options.printprogress = True
You can pass an iterable object. Say you want to calculate the the sum
o... |
Start the *HydPy* server using the given socket.
The folder with the given `projectname` must be available within the
current working directory. The XML configuration file must be placed
within the project folder unless `xmlfilename` is an absolute file path.
The XML configuration file must be valid c... |
Block the current process until either the *HydPy* server is responding
on the given `port` or the given number of `seconds` elapsed.
>>> from hydpy import run_subprocess, TestIO
>>> with TestIO(): # doctest: +ELLIPSIS
... run_subprocess('hyd.py await_server 8080 0.1')
Invoking hyd.py with a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.