sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def load(self):
""" Load the object defined by the plugin entry point """
print("[DEBUG] Loading plugin {} from {}".format(self.name,
self.source))
import pydoc
path, attr = self.source.split(":")
module = pydoc.locate(path... | Load the object defined by the plugin entry point | entailment |
def _default_plugins(self):
""" Get entry points to load any plugins installed.
The build process should create an "entry_points.json" file
with all of the data from the installed entry points.
"""
plugins = {}
try:
with open('entry_points.json') as ... | Get entry points to load any plugins installed.
The build process should create an "entry_points.json" file
with all of the data from the installed entry points. | entailment |
def start(self):
""" Start the application's main event loop
using either twisted or tornado.
"""
#: Schedule a load view if given and remote debugging is not active
#: the remote debugging init call this after dev connection is ready
if self.load_view and self.d... | Start the application's main event loop
using either twisted or tornado. | entailment |
def timed_call(self, ms, callback, *args, **kwargs):
""" Invoke a callable on the main event loop thread at a
specified time in the future.
Parameters
----------
ms : int
The time to delay, in milliseconds, before executing the
callable.
callback... | Invoke a callable on the main event loop thread at a
specified time in the future.
Parameters
----------
ms : int
The time to delay, in milliseconds, before executing the
callable.
callback : callable
The callable object to execute at some po... | entailment |
def add_done_callback(self, future, callback):
""" Add a callback on a future object put here so it can be
implemented with different event loops.
Parameters
-----------
future: Future or Deferred
Future implementation for the current EventLoop
... | Add a callback on a future object put here so it can be
implemented with different event loops.
Parameters
-----------
future: Future or Deferred
Future implementation for the current EventLoop
callback: callable
Callback ... | entailment |
def get_view(self):
""" Get the root view to display. Make sure it is
properly initialized.
"""
view = self.view
if not view.is_initialized:
view.initialize()
if not view.proxy_is_active:
view.activate_proxy()
return view.proxy.wid... | Get the root view to display. Make sure it is
properly initialized. | entailment |
def send_event(self, name, *args, **kwargs):
""" Send an event to the native handler. This call is queued and
batched.
Parameters
----------
name : str
The event name to be processed by MainActivity.processMessages.
*args: args
The arguments requ... | Send an event to the native handler. This call is queued and
batched.
Parameters
----------
name : str
The event name to be processed by MainActivity.processMessages.
*args: args
The arguments required by the event.
**kwargs: kwargs
O... | entailment |
def _bridge_send(self, now=False):
""" Send the events over the bridge to be processed by the native
handler.
Parameters
----------
now: boolean
Send all pending events now instead of waiting for deferred calls
to finish. Use this when you want to updat... | Send the events over the bridge to be processed by the native
handler.
Parameters
----------
now: boolean
Send all pending events now instead of waiting for deferred calls
to finish. Use this when you want to update the screen | entailment |
def process_events(self, data):
""" The native implementation must use this call to """
events = bridge.loads(data)
if self.debug:
print("======== Py <-- Native ======")
for event in events:
print(event)
print("===========================")
... | The native implementation must use this call to | entailment |
def handle_event(self, event):
""" When we get an 'event' type from the bridge
handle it by invoking the handler and if needed
sending back the result.
"""
result_id, ptr, method, args = event[1]
obj = None
result = None
try:
obj, hand... | When we get an 'event' type from the bridge
handle it by invoking the handler and if needed
sending back the result. | entailment |
def handle_error(self, callback):
""" Called when an error occurs in an event loop callback.
By default, sets the error view.
"""
self.loop.log_error(callback)
msg = "\n".join([
"Exception in callback %r"%callback,
traceback.format_exc()
]... | Called when an error occurs in an event loop callback.
By default, sets the error view. | entailment |
def start_dev_session(self):
""" Start a client that attempts to connect to the dev server
running on the host `app.dev`
"""
try:
from .dev import DevServerSession
session = DevServerSession.initialize(host=self.dev)
session.start()
... | Start a client that attempts to connect to the dev server
running on the host `app.dev` | entailment |
def load_plugin_widgets(self):
""" Pull widgets added via plugins using the `enaml_native_widgets`
entry point. The entry point function must return a dictionary of
Widget declarations to add to the core api.
def install():
from charts.widgets.chart_view import BarChart, L... | Pull widgets added via plugins using the `enaml_native_widgets`
entry point. The entry point function must return a dictionary of
Widget declarations to add to the core api.
def install():
from charts.widgets.chart_view import BarChart, LineChart
return {
... | entailment |
def for_action(cls, action, callback, single_shot=True):
""" Create a BroadcastReceiver that is invoked when the given
action is received.
Parameters
----------
action: String
Action to receive
callback: Callable
Callback to invoke when t... | Create a BroadcastReceiver that is invoked when the given
action is received.
Parameters
----------
action: String
Action to receive
callback: Callable
Callback to invoke when the action is received
single_shot: Bool
Cleanup a... | entailment |
def get(self, measurement_class):
"""Return the latest measurement for the given class or None if nothing
has been received from the vehicle.
"""
name = Measurement.name_from_class(measurement_class)
return self._construct_measurement(name) | Return the latest measurement for the given class or None if nothing
has been received from the vehicle. | entailment |
def add_source(self, source):
"""Add a vehicle data source to the instance.
The Vehicle instance will be set as the callback of the source, and the
source will be started if it is startable. (i.e. it has a ``start()``
method).
"""
if source is not None:
self.... | Add a vehicle data source to the instance.
The Vehicle instance will be set as the callback of the source, and the
source will be started if it is startable. (i.e. it has a ``start()``
method). | entailment |
def add_sink(self, sink):
"""Add a vehicle data sink to the instance. ``sink`` should be a
sub-class of ``DataSink`` or at least have a ``receive(message,
**kwargs)`` method.
The sink will be started if it is startable. (i.e. it has a ``start()``
method).
"""
if ... | Add a vehicle data sink to the instance. ``sink`` should be a
sub-class of ``DataSink`` or at least have a ``receive(message,
**kwargs)`` method.
The sink will be started if it is startable. (i.e. it has a ``start()``
method). | entailment |
def register(self, measurement_class, callback):
"""Call the ``callback`` with any new values of ``measurement_class``
received.
"""
self.callbacks[Measurement.name_from_class(measurement_class)
].add(callback) | Call the ``callback`` with any new values of ``measurement_class``
received. | entailment |
def unregister(self, measurement_class, callback):
"""Stop notifying ``callback`` of new values of ``measurement_class``.
If the callback wasn't previously registered, this method will have no
effect.
"""
self.callbacks[Measurement.name_from_class(measurement_class)
... | Stop notifying ``callback`` of new values of ``measurement_class``.
If the callback wasn't previously registered, this method will have no
effect. | entailment |
def _send_complex_request(self, request):
"""Send a request via the USB control request endpoint, rather than as a
bulk transfer.
"""
self.device.ctrl_transfer(0x40, self.COMPLEX_CONTROL_COMMAND, 0, 0,
self.streamer.serialize_for_stream(request)) | Send a request via the USB control request endpoint, rather than as a
bulk transfer. | entailment |
def out_endpoint(self):
"""Open a reference to the USB device's only OUT endpoint. This method
assumes that the USB device configuration has already been set.
"""
if getattr(self, '_out_endpoint', None) is None:
config = self.device.get_active_configuration()
inte... | Open a reference to the USB device's only OUT endpoint. This method
assumes that the USB device configuration has already been set. | entailment |
def wait_for_responses(self):
"""Block the thread and wait for the response to the given request to
arrive from the VI. If no matching response is received in
COMMAND_RESPONSE_TIMEOUT_S seconds, returns anyway.
"""
self.thread.join(self.COMMAND_RESPONSE_TIMEOUT_S)
self.r... | Block the thread and wait for the response to the given request to
arrive from the VI. If no matching response is received in
COMMAND_RESPONSE_TIMEOUT_S seconds, returns anyway. | entailment |
def handle_responses(self):
"""Block and wait for responses to this object's original request, or
until a timeout (self.COMMAND_RESPONSE_TIMEOUT_S).
This function is handy to use as the target function for a thread.
The responses received (or None if none was received before the timeou... | Block and wait for responses to this object's original request, or
until a timeout (self.COMMAND_RESPONSE_TIMEOUT_S).
This function is handy to use as the target function for a thread.
The responses received (or None if none was received before the timeout)
is stored in a list at self.... | entailment |
def _response_matches_request(self, response):
"""Return true if the response is to a diagnostic request, and the bus,
id, mode match. If the request was successful, the PID echo is also
checked.
"""
# Accept success/failure command responses
if super(DiagnosticResponseRe... | Return true if the response is to a diagnostic request, and the bus,
id, mode match. If the request was successful, the PID echo is also
checked. | entailment |
def complex_request(self, request, wait_for_first_response=True):
"""Send a compound command request to the interface over the normal data
channel.
request - A dict storing the request to send to the VI. It will be
serialized to the currently selected output format.
wait_for... | Send a compound command request to the interface over the normal data
channel.
request - A dict storing the request to send to the VI. It will be
serialized to the currently selected output format.
wait_for_first_response - If true, this function will block waiting for
a... | entailment |
def create_diagnostic_request(self, message_id, mode, bus=None, pid=None,
frequency=None, payload=None, wait_for_ack=True,
wait_for_first_response=False, decoded_type=None):
"""Send a new diagnostic message request to the VI
Required:
message_id - The message ID (arbitr... | Send a new diagnostic message request to the VI
Required:
message_id - The message ID (arbitration ID) for the request.
mode - the diagnostic mode (or service).
Optional:
bus - The address of the CAN bus controller to send the request, either
1 or 2 for current VI... | entailment |
def set_passthrough(self, bus, enabled):
"""Control the status of CAN message passthrough for a bus.
Returns True if the command was successful.
"""
request = {
"command": "passthrough",
"bus": bus,
"enabled": enabled
}
return self._ch... | Control the status of CAN message passthrough for a bus.
Returns True if the command was successful. | entailment |
def set_payload_format(self, payload_format):
"""Set the payload format for messages sent to and from the VI.
Returns True if the command was successful.
"""
request = {
"command": "payload_format",
"format": payload_format
}
status = self._check_... | Set the payload format for messages sent to and from the VI.
Returns True if the command was successful. | entailment |
def rtc_configuration(self, unix_time):
"""Set the Unix time if RTC is supported on the device.
Returns True if the command was successful.
"""
request = {
"command": "rtc_configuration",
"unix_time": unix_time
}
status = self._check_command_respo... | Set the Unix time if RTC is supported on the device.
Returns True if the command was successful. | entailment |
def modem_configuration(self, host, port):
"""Set the host:port for the Cellular device to send data to.
Returns True if the command was successful.
"""
request = {
"command": "modem_configuration",
"host": host,
"port": port
}
status ... | Set the host:port for the Cellular device to send data to.
Returns True if the command was successful. | entailment |
def set_acceptance_filter_bypass(self, bus, bypass):
"""Control the status of CAN acceptance filter for a bus.
Returns True if the command was successful.
"""
request = {
"command": "af_bypass",
"bus": bus,
"bypass": bypass
}
return se... | Control the status of CAN acceptance filter for a bus.
Returns True if the command was successful. | entailment |
def sd_mount_status(self):
"""Request for SD Mount status if available.
"""
request = {
"command": "sd_mount_status"
}
responses = self.complex_request(request)
result = None
if len(responses) > 0:
result = responses[0].get('status')
... | Request for SD Mount status if available. | entailment |
def write(self, **kwargs):
"""Serialize a raw or translated write request and send it to the VI,
following the OpenXC message format.
"""
if 'id' in kwargs and 'data' in kwargs:
result = self.write_raw(kwargs['id'], kwargs['data'],
bus=kwargs.get('bus', No... | Serialize a raw or translated write request and send it to the VI,
following the OpenXC message format. | entailment |
def write_translated(self, name, value, event=None):
"""Send a translated write request to the VI.
"""
data = {'name': name}
if value is not None:
data['value'] = self._massage_write_value(value)
if event is not None:
data['event'] = self._massage_write_va... | Send a translated write request to the VI. | entailment |
def write_raw(self, message_id, data, bus=None, frame_format=None):
"""Send a raw write request to the VI.
"""
if not isinstance(message_id, numbers.Number):
try:
message_id = int(message_id, 0)
except ValueError:
raise ValueError("ID must ... | Send a raw write request to the VI. | entailment |
def _massage_write_value(cls, value):
"""Convert string values from command-line arguments into first-order
Python boolean and float objects, if applicable.
"""
if not isinstance(value, numbers.Number):
if value == "true":
value = True
elif value =... | Convert string values from command-line arguments into first-order
Python boolean and float objects, if applicable. | entailment |
def _validate(cls, message):
"""Confirm the validitiy of a given dict as an OpenXC message.
Returns:
``True`` if the message contains at least a ``name`` and ``value``.
"""
valid = False
if(('name' in message and 'value' in message) or
('id' in messag... | Confirm the validitiy of a given dict as an OpenXC message.
Returns:
``True`` if the message contains at least a ``name`` and ``value``. | entailment |
def value(self, new_value):
"""Set the value of this measurement.
Raises:
AttributeError: if the new value isn't of the correct units.
"""
if self.unit != units.Undefined and new_value.unit != self.unit:
raise AttributeError("%s must be in %s" % (
... | Set the value of this measurement.
Raises:
AttributeError: if the new value isn't of the correct units. | entailment |
def from_dict(cls, data):
"""Create a new Measurement subclass instance using the given dict.
If Measurement.name_from_class was previously called with this data's
associated Measurement sub-class in Python, the returned object will be
an instance of that sub-class. If the measurement n... | Create a new Measurement subclass instance using the given dict.
If Measurement.name_from_class was previously called with this data's
associated Measurement sub-class in Python, the returned object will be
an instance of that sub-class. If the measurement name in ``data`` is
unrecogniz... | entailment |
def name_from_class(cls, measurement_class):
"""For a given measurement class, return its generic name.
The given class is expected to have a ``name`` attribute, otherwise this
function will raise an execption. The point of using this method instead
of just trying to grab that attribute... | For a given measurement class, return its generic name.
The given class is expected to have a ``name`` attribute, otherwise this
function will raise an execption. The point of using this method instead
of just trying to grab that attribute in the application is to cache
measurement name... | entailment |
def _store_timestamp(self, timestamp):
"""If not already saved, cache the first timestamp in the active trace
file on the instance.
"""
if getattr(self, 'first_timestamp', None) is None:
self.first_timestamp = timestamp
LOG.debug("Storing %d as the first timestamp... | If not already saved, cache the first timestamp in the active trace
file on the instance. | entailment |
def read(self):
"""Read a line of data from the input source at a time."""
line = self.trace_file.readline()
if line == '':
if self.loop:
self._reopen_file()
else:
self.trace_file.close()
self.trace_file = None
... | Read a line of data from the input source at a time. | entailment |
def _open_file(filename):
"""Attempt to open the the file at ``filename`` for reading.
Raises:
DataSourceError, if the file cannot be opened.
"""
if filename is None:
raise DataSourceError("Trace filename is not defined")
try:
trace_file = op... | Attempt to open the the file at ``filename`` for reading.
Raises:
DataSourceError, if the file cannot be opened. | entailment |
def _wait(starting_time, first_timestamp, timestamp):
"""Given that the first timestamp in the trace file is
``first_timestamp`` and we started playing back the file at
``starting_time``, block until the current ``timestamp`` should occur.
"""
target_time = starting_time + (times... | Given that the first timestamp in the trace file is
``first_timestamp`` and we started playing back the file at
``starting_time``, block until the current ``timestamp`` should occur. | entailment |
def merge(a, b):
"""Merge two deep dicts non-destructively
Uses a stack to avoid maximum recursion depth exceptions
>>> a = {'a': 1, 'b': {1: 1, 2: 2}, 'd': 6}
>>> b = {'c': 3, 'b': {2: 7}, 'd': {'z': [1, 2, 3]}}
>>> c = merge(a, b)
>>> from pprint import pprint; pprint(c)
{'a': 1, 'b': {1... | Merge two deep dicts non-destructively
Uses a stack to avoid maximum recursion depth exceptions
>>> a = {'a': 1, 'b': {1: 1, 2: 2}, 'd': 6}
>>> b = {'c': 3, 'b': {2: 7}, 'd': {'z': [1, 2, 3]}}
>>> c = merge(a, b)
>>> from pprint import pprint; pprint(c)
{'a': 1, 'b': {1: 1, 2: 7}, 'c': 3, 'd':... | entailment |
def from_xml_node(cls, node):
"""Construct a Signal instance from an XML node exported from a Vector
CANoe .dbc file."""
return cls(name=node.find("Name").text,
bit_position=int(node.find("Bitposition").text),
bit_size=int(node.find("Bitsize").text),
... | Construct a Signal instance from an XML node exported from a Vector
CANoe .dbc file. | entailment |
def run(self):
"""Continuously read data from the source and attempt to parse a valid
message from the buffer of bytes. When a message is parsed, passes it
off to the callback if one is set.
"""
message_buffer = b""
while self.running:
try:
mes... | Continuously read data from the source and attempt to parse a valid
message from the buffer of bytes. When a message is parsed, passes it
off to the callback if one is set. | entailment |
def compare_versions(x, y):
"""
Expects 2 strings in the format of 'X.Y.Z' where X, Y and Z are
integers. It will compare the items which will organize things
properly by their major, minor and bugfix version.
::
>>> my_list = ['v1.13', 'v1.14.2', 'v1.14.1', 'v1.9', 'v1.1']
>>> sort... | Expects 2 strings in the format of 'X.Y.Z' where X, Y and Z are
integers. It will compare the items which will organize things
properly by their major, minor and bugfix version.
::
>>> my_list = ['v1.13', 'v1.14.2', 'v1.14.1', 'v1.9', 'v1.1']
>>> sorted(my_list, cmp=compare_versions)
... | entailment |
def compute(self, t, yerr=1.123e-12, check_sorted=True,
A=None, U=None, V=None):
"""
Compute the extended form of the covariance matrix and factorize
Args:
x (array[n]): The independent coordinates of the data points.
This array must be _sorted_ in as... | Compute the extended form of the covariance matrix and factorize
Args:
x (array[n]): The independent coordinates of the data points.
This array must be _sorted_ in ascending order.
yerr (Optional[float or array[n]]): The measurement uncertainties
for the ... | entailment |
def log_likelihood(self, y, _const=math.log(2.0*math.pi), quiet=False):
"""
Compute the marginalized likelihood of the GP model
The factorized matrix from the previous call to :func:`GP.compute` is
used so ``compute`` must be called first.
Args:
y (array[n]): The ob... | Compute the marginalized likelihood of the GP model
The factorized matrix from the previous call to :func:`GP.compute` is
used so ``compute`` must be called first.
Args:
y (array[n]): The observations at coordinates ``x`` from
:func:`GP.compute`.
quiet (... | entailment |
def grad_log_likelihood(self, y, quiet=False):
"""
Compute the gradient of the marginalized likelihood
The factorized matrix from the previous call to :func:`GP.compute` is
used so ``compute`` must be called first. The gradient is taken with
respect to the parameters returned by... | Compute the gradient of the marginalized likelihood
The factorized matrix from the previous call to :func:`GP.compute` is
used so ``compute`` must be called first. The gradient is taken with
respect to the parameters returned by :func:`GP.get_parameter_vector`.
This function requires th... | entailment |
def apply_inverse(self, y):
"""
Apply the inverse of the covariance matrix to a vector or matrix
Solve ``K.x = y`` for ``x`` where ``K`` is the covariance matrix of
the GP with the white noise and ``yerr`` components included on the
diagonal.
Args:
y (array[... | Apply the inverse of the covariance matrix to a vector or matrix
Solve ``K.x = y`` for ``x`` where ``K`` is the covariance matrix of
the GP with the white noise and ``yerr`` components included on the
diagonal.
Args:
y (array[n] or array[n, nrhs]): The vector or matrix ``y`... | entailment |
def dot(self, y, t=None, A=None, U=None, V=None, kernel=None,
check_sorted=True):
"""
Dot the covariance matrix into a vector or matrix
Compute ``K.y`` where ``K`` is the covariance matrix of the GP without
the white noise or ``yerr`` values on the diagonal.
Args:
... | Dot the covariance matrix into a vector or matrix
Compute ``K.y`` where ``K`` is the covariance matrix of the GP without
the white noise or ``yerr`` values on the diagonal.
Args:
y (array[n] or array[n, nrhs]): The vector or matrix ``y``
described above.
... | entailment |
def predict(self, y, t=None, return_cov=True, return_var=False):
"""
Compute the conditional predictive distribution of the model
You must call :func:`GP.compute` before this method.
Args:
y (array[n]): The observations at coordinates ``x`` from
:func:`GP.co... | Compute the conditional predictive distribution of the model
You must call :func:`GP.compute` before this method.
Args:
y (array[n]): The observations at coordinates ``x`` from
:func:`GP.compute`.
t (Optional[array[ntest]]): The independent coordinates where the... | entailment |
def get_matrix(self, x1=None, x2=None, include_diagonal=None,
include_general=None):
"""
Get the covariance matrix at given independent coordinates
Args:
x1 (Optional[array[n1]]): The first set of independent coordinates.
If this is omitted, ``x1``... | Get the covariance matrix at given independent coordinates
Args:
x1 (Optional[array[n1]]): The first set of independent coordinates.
If this is omitted, ``x1`` will be assumed to be equal to ``x``
from a previous call to :func:`GP.compute`.
x2 (Optional[a... | entailment |
def sample(self, size=None):
"""
Sample from the prior distribution over datasets
Args:
size (Optional[int]): The number of samples to draw.
Returns:
array[n] or array[size, n]: The samples from the prior
distribution over datasets.
"""
... | Sample from the prior distribution over datasets
Args:
size (Optional[int]): The number of samples to draw.
Returns:
array[n] or array[size, n]: The samples from the prior
distribution over datasets. | entailment |
def sample_conditional(self, y, t=None, size=None):
"""
Sample from the conditional (predictive) distribution
Note: this method scales as ``O(M^3)`` for large ``M``, where
``M == len(t)``.
Args:
y (array[n]): The observations at coordinates ``x`` from
... | Sample from the conditional (predictive) distribution
Note: this method scales as ``O(M^3)`` for large ``M``, where
``M == len(t)``.
Args:
y (array[n]): The observations at coordinates ``x`` from
:func:`GP.compute`.
t (Optional[array[ntest]]): The indepe... | entailment |
def get_value(self, tau):
"""
Compute the value of the term for an array of lags
Args:
tau (array[...]): An array of lags where the term should be
evaluated.
Returns:
The value of the term for each ``tau``. This will have the same
sha... | Compute the value of the term for an array of lags
Args:
tau (array[...]): An array of lags where the term should be
evaluated.
Returns:
The value of the term for each ``tau``. This will have the same
shape as ``tau``. | entailment |
def get_psd(self, omega):
"""
Compute the PSD of the term for an array of angular frequencies
Args:
omega (array[...]): An array of frequencies where the PSD should
be evaluated.
Returns:
The value of the PSD for each ``omega``. This will have th... | Compute the PSD of the term for an array of angular frequencies
Args:
omega (array[...]): An array of frequencies where the PSD should
be evaluated.
Returns:
The value of the PSD for each ``omega``. This will have the same
shape as ``omega``. | entailment |
def get_complex_coefficients(self, params):
"""
Get the arrays ``alpha_complex_*`` and ``beta_complex_*``
This method should be overloaded by subclasses to return the arrays
``alpha_complex_real``, ``alpha_complex_imag``, ``beta_complex_real``,
and ``beta_complex_imag`` given th... | Get the arrays ``alpha_complex_*`` and ``beta_complex_*``
This method should be overloaded by subclasses to return the arrays
``alpha_complex_real``, ``alpha_complex_imag``, ``beta_complex_real``,
and ``beta_complex_imag`` given the current parameter settings. By
default, this term is e... | entailment |
def coefficients(self):
"""
All of the coefficient arrays
This property is the concatenation of the results from
:func:`terms.Term.get_real_coefficients` and
:func:`terms.Term.get_complex_coefficients` but it will always return
a tuple of length 6, even if ``alpha_comple... | All of the coefficient arrays
This property is the concatenation of the results from
:func:`terms.Term.get_real_coefficients` and
:func:`terms.Term.get_complex_coefficients` but it will always return
a tuple of length 6, even if ``alpha_complex_imag`` was omitted from
``get_comp... | entailment |
def pop(self, key, *args):
'Remove *key* from maps[0] and return its value. Raise KeyError if *key* not in maps[0].'
try:
return self.maps[0].pop(key, *args)
except KeyError:
raise KeyError('Key not found in the first mapping: {!r}'.format(key)) | Remove *key* from maps[0] and return its value. Raise KeyError if *key* not in maps[0]. | entailment |
def _determine_current_dimension_size(self, dim_name, max_size):
"""
Helper method to determine the current size of a dimension.
"""
# Limited dimension.
if self.dimensions[dim_name] is not None:
return max_size
def _find_dim(h5group, dim):
if dim... | Helper method to determine the current size of a dimension. | entailment |
def _create_dim_scales(self):
"""Create all necessary HDF5 dimension scale."""
dim_order = self._dim_order.maps[0]
for dim in sorted(dim_order, key=lambda d: dim_order[d]):
if dim not in self._h5group:
size = self._current_dim_sizes[dim]
kwargs = {}
... | Create all necessary HDF5 dimension scale. | entailment |
def _attach_dim_scales(self):
"""Attach dimension scales to all variables."""
for name, var in self.variables.items():
if name not in self.dimensions:
for n, dim in enumerate(var.dimensions):
var._h5ds.dims[n].attach_scale(self._all_h5groups[dim])
... | Attach dimension scales to all variables. | entailment |
def _detach_dim_scale(self, name):
"""Detach the dimension scale corresponding to a dimension name."""
for var in self.variables.values():
for n, dim in enumerate(var.dimensions):
if dim == name:
var._h5ds.dims[n].detach_scale(self._all_h5groups[dim])
... | Detach the dimension scale corresponding to a dimension name. | entailment |
def resize_dimension(self, dimension, size):
"""
Resize a dimension to a certain size.
It will pad with the underlying HDF5 data sets' fill values (usually
zero) where necessary.
"""
if self.dimensions[dimension] is not None:
raise ValueError("Dimension '%s' ... | Resize a dimension to a certain size.
It will pad with the underlying HDF5 data sets' fill values (usually
zero) where necessary. | entailment |
def multiplyQuats(q1, q2):
"""q1, q2 must be [scalar, x, y, z] but those may be arrays or scalars"""
return np.array([
q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3],
q1[2]*q2[3] - q2[2]*q1[3] + q1[0]*q2[1] + q2[0]*q1[1],
q1[3]*q2[1] - q2[3]*q1[1] + q1[0]*q2[2] + q2[0]... | q1, q2 must be [scalar, x, y, z] but those may be arrays or scalars | entailment |
def quatInv(q):
"""Returns QBar such that Q*QBar = 1"""
qConj = -q
qConj[0] = -qConj[0]
normSqr = multiplyQuats(q, qConj)[0]
return qConj/normSqr | Returns QBar such that Q*QBar = 1 | entailment |
def alignVec_quat(vec):
"""Returns a unit quaternion that will align vec with the z-axis"""
alpha = np.arctan2(vec[1], vec[0])
beta = np.arccos(vec[2])
gamma = -alpha*vec[2]
cb = np.cos(0.5*beta)
sb = np.sin(0.5*beta)
return np.array([cb*np.cos(0.5*(alpha + gamma)),
sb*n... | Returns a unit quaternion that will align vec with the z-axis | entailment |
def transformTimeDependentVector(quat, vec, inverse=0):
"""Given (for example) a minimal rotation frame quat, transforms
vec from the minimal rotation frame to the inertial frame.
With inverse=1, transforms from the inertial frame to the minimal
rotation frame."""
qInv = quatInv(quat)
if inverse... | Given (for example) a minimal rotation frame quat, transforms
vec from the minimal rotation frame to the inertial frame.
With inverse=1, transforms from the inertial frame to the minimal
rotation frame. | entailment |
def rotate_in_plane(chi, phase):
"""For transforming spins between the coprecessing and coorbital frames"""
v = chi.T
sp = np.sin(phase)
cp = np.cos(phase)
res = 1.*v
res[0] = v[0]*cp + v[1]*sp
res[1] = v[1]*cp - v[0]*sp
return res.T | For transforming spins between the coprecessing and coorbital frames | entailment |
def transform_vector_coorb_to_inertial(vec_coorb, orbPhase, quat_copr):
"""Given a vector (of size 3) in coorbital frame, orbital phase in
coprecessing frame and a minimal rotation frame quat, transforms
the vector from the coorbital to the inertial frame.
"""
# Transform to coprecessing frame
... | Given a vector (of size 3) in coorbital frame, orbital phase in
coprecessing frame and a minimal rotation frame quat, transforms
the vector from the coorbital to the inertial frame. | entailment |
def transform_error_coorb_to_inertial(vec_coorb, vec_err_coorb, orbPhase,
quat_copr):
""" Transform error in a vector from the coorbital frame to the inertial
frame. Generates distributions in the coorbital frame, transforms them
to inertial frame and returns 1-simga widths in the inertial frame.
... | Transform error in a vector from the coorbital frame to the inertial
frame. Generates distributions in the coorbital frame, transforms them
to inertial frame and returns 1-simga widths in the inertial frame. | entailment |
def _load_fits(self, h5file):
""" Loads fits from h5file and returns a dictionary of fits. """
fits = {}
for key in ['mf']:
fits[key] = self._load_scalar_fit(fit_key=key, h5file=h5file)
for key in ['chif', 'vf']:
fits[key] = self._load_vector_fit(key, h5file)
... | Loads fits from h5file and returns a dictionary of fits. | entailment |
def _extra_regression_kwargs(self):
""" List of additional kwargs to use in regression tests.
"""
# larger than default sometimes needed when extrapolating
omega_switch_test = 0.019
extra_args = []
extra_args.append({
'omega0': 5e-3,
'PN_approxim... | List of additional kwargs to use in regression tests. | entailment |
def _get_fit_params(self, x, fit_key):
""" Transforms the input parameter to fit parameters for the 7dq2 model.
That is, maps from
x = [q, chiAx, chiAy, chiAz, chiBx, chiBy, chiBz]
fit_params = [np.log(q), chiAx, chiAy, chiHat, chiBx, chiBy, chi_a]
chiHat is defined in Eq.(3) of 1508.07253, but... | Transforms the input parameter to fit parameters for the 7dq2 model.
That is, maps from
x = [q, chiAx, chiAy, chiAz, chiBx, chiBy, chiBz]
fit_params = [np.log(q), chiAx, chiAy, chiHat, chiBx, chiBy, chi_a]
chiHat is defined in Eq.(3) of 1508.07253, but with chiAz and chiBz instead
of chiA and chiB.... | entailment |
def _evolve_spins(self, q, chiA0, chiB0, omega0, PN_approximant,
PN_dt, PN_spin0, PN_phase0, omega0_nrsur):
""" Evolves spins of the component BHs from an initial orbital
frequency = omega0 until t=-100 M from the peak of the waveform.
If omega0 < omega0_nrsur, use PN to evolve the s... | Evolves spins of the component BHs from an initial orbital
frequency = omega0 until t=-100 M from the peak of the waveform.
If omega0 < omega0_nrsur, use PN to evolve the spins until
orbital frequency = omega0. Then evolves further with the NRSur7dq2
waveform model until t=-100M from the... | entailment |
def _eval_wrapper(self, fit_key, q, chiA, chiB, **kwargs):
"""Evaluates the surfinBH7dq2 model.
"""
chiA = np.array(chiA)
chiB = np.array(chiB)
# Warn/Exit if extrapolating
allow_extrap = kwargs.pop('allow_extrap', False)
self._check_param_limits(q, chiA, chiB, a... | Evaluates the surfinBH7dq2 model. | entailment |
def LoadFits(name):
""" Loads data for a fit.
If data is not available, downloads it before loading.
"""
if name not in fits_collection.keys():
raise Exception('Invalid fit name : %s'%name)
else:
testPath = DataPath() + '/' + fits_collection[name].data_url.split('/')[-1]
if (... | Loads data for a fit.
If data is not available, downloads it before loading. | entailment |
def DownloadData(name='all', data_dir=DataPath()):
""" Downloads fit data to DataPath() diretory.
If name='all', gets all fit data.
"""
if name == 'all':
for tmp_name in fits_collection.keys():
DownloadData(name=tmp_name, data_dir=data_dir)
return
if name not in fits... | Downloads fit data to DataPath() diretory.
If name='all', gets all fit data. | entailment |
def _load_fits(self, h5file):
""" Loads fits from h5file and returns a dictionary of fits. """
fits = {}
for key in ['mf', 'chifz', 'vfx', 'vfy']:
fits[key] = self._load_scalar_fit(fit_key=key, h5file=h5file)
return fits | Loads fits from h5file and returns a dictionary of fits. | entailment |
def _eval_wrapper(self, fit_key, q, chiA, chiB, **kwargs):
""" Evaluates the surfinBH3dq8 model.
"""
chiA = np.array(chiA)
chiB = np.array(chiB)
# Warn/Exit if extrapolating
allow_extrap = kwargs.pop('allow_extrap', False)
self._check_param_limits(q, chiA, chiB, ... | Evaluates the surfinBH3dq8 model. | entailment |
def lal_spin_evloution_wrapper(approximant, q, omega0, chiA0, chiB0,
dt, spinO, phaseO):
"""
Inputs:
approximant: 'SpinTaylorT1/T2/T4'
q: Mass ratio (q>=1)
omega0: Initial orbital frequency in dimless units.
chiA0: Dimless spin of BhA at i... | Inputs:
approximant: 'SpinTaylorT1/T2/T4'
q: Mass ratio (q>=1)
omega0: Initial orbital frequency in dimless units.
chiA0: Dimless spin of BhA at initial freq.
chiB0: Dimless spin of BhB at initial freq.
dt: Dimless ste... | entailment |
def evolve_pn_spins(q, chiA0, chiB0, omega0, omegaTimesM_final,
approximant='SpinTaylorT4', dt=0.1, spinO=7, phaseO=7):
""" Evolves PN spins from a starting orbital frequency and spins to a final
frequency.
Inputs:
q: Mass ratio (q>=1)
chiA0: Dimless sp... | Evolves PN spins from a starting orbital frequency and spins to a final
frequency.
Inputs:
q: Mass ratio (q>=1)
chiA0: Dimless spin of BhA at initial freq.
chiB0: Dimless spin of BhB at initial freq.
omega0: Initial orbital freque... | entailment |
def is_null(value):
"""
Check if the scalar value or tuple/list value is NULL.
:param value: Value to check.
:type value: a scalar or tuple or list
:return: Returns ``True`` if and only if the value is NULL (scalar value is None
or _any_ tuple/list elements are None).
:rtype: bool
... | Check if the scalar value or tuple/list value is NULL.
:param value: Value to check.
:type value: a scalar or tuple or list
:return: Returns ``True`` if and only if the value is NULL (scalar value is None
or _any_ tuple/list elements are None).
:rtype: bool | entailment |
def qual(obj):
"""
Return fully qualified name of a class.
"""
return u'{}.{}'.format(obj.__class__.__module__, obj.__class__.__name__) | Return fully qualified name of a class. | entailment |
def select(self, txn, from_key=None, to_key=None, return_keys=True, return_values=True, reverse=False, limit=None):
"""
Select all records (key-value pairs) in table, optionally within a given key range.
:param txn: The transaction in which to run.
:type txn: :class:`zlmdb.Transaction`
... | Select all records (key-value pairs) in table, optionally within a given key range.
:param txn: The transaction in which to run.
:type txn: :class:`zlmdb.Transaction`
:param from_key: Return records starting from (and including) this key.
:type from_key: object
:param to_key: ... | entailment |
def count(self, txn, prefix=None):
"""
Count number of records in the persistent map. When no prefix
is given, the total number of records is returned. When a prefix
is given, only the number of records with keys that have this
prefix are counted.
:param txn: The transac... | Count number of records in the persistent map. When no prefix
is given, the total number of records is returned. When a prefix
is given, only the number of records with keys that have this
prefix are counted.
:param txn: The transaction in which to run.
:type txn: :class:`zlmdb.... | entailment |
def count_range(self, txn, from_key, to_key):
"""
Counter number of records in the perstistent map with keys
within the given range.
:param txn: The transaction in which to run.
:type txn: :class:`zlmdb.Transaction`
:param from_key: Count records starting and including ... | Counter number of records in the perstistent map with keys
within the given range.
:param txn: The transaction in which to run.
:type txn: :class:`zlmdb.Transaction`
:param from_key: Count records starting and including from this key.
:type from_key: object
:param to_k... | entailment |
def _random_string():
"""
Generate a globally unique serial / product code of the form ``u'YRAC-EL4X-FQQE-AW4T-WNUV-VN6T'``.
The generated value is cryptographically strong and has (at least) 114 bits of entropy.
:return: new random string key
"""
rng = random.SystemRandom()
token_value = u... | Generate a globally unique serial / product code of the form ``u'YRAC-EL4X-FQQE-AW4T-WNUV-VN6T'``.
The generated value is cryptographically strong and has (at least) 114 bits of entropy.
:return: new random string key | entailment |
def _read_dict(self, f):
""" Converts h5 groups to dictionaries
"""
d = {}
for k, item in f.items():
if type(item) == h5py._hl.dataset.Dataset:
v = item.value
if type(v) == np.string_:
v = str(v)
if type(v) =... | Converts h5 groups to dictionaries | entailment |
def _load_scalar_fit(self, fit_key=None, h5file=None, fit_data=None):
""" Loads a single fit
"""
if (fit_key is None) ^ (h5file is None):
raise ValueError("Either specify both fit_key and h5file, or"
" neither")
if not ((fit_key is None) ^ (fit_data is None))... | Loads a single fit | entailment |
def _load_vector_fit(self, fit_key, h5file):
""" Loads a vector of fits
"""
vector_fit = []
for i in range(len(h5file[fit_key].keys())):
fit_data = self._read_dict(h5file[fit_key]['comp_%d'%i])
vector_fit.append(self._load_scalar_fit(fit_data=fit_data))
re... | Loads a vector of fits | entailment |
def _evaluate_fits(self, x, fit_key):
""" Evaluates a particular fit by passing fit_key to self.fits.
Assumes self._get_fit_params() has been overriden.
"""
fit = self.fits[fit_key]
fit_params = self._get_fit_params(np.copy(x), fit_key)
if type(fit) == list:
... | Evaluates a particular fit by passing fit_key to self.fits.
Assumes self._get_fit_params() has been overriden. | entailment |
def _check_unused_kwargs(self, kwargs):
""" Call this at the end of call module to check if all the kwargs have
been used. Assumes kwargs were extracted using pop.
"""
if len(kwargs.keys()) != 0:
unused = ""
for k in kwargs.keys():
unused += "'%s',... | Call this at the end of call module to check if all the kwargs have
been used. Assumes kwargs were extracted using pop. | entailment |
def _check_param_limits(self, q, chiA, chiB, allow_extrap):
""" Checks that params are within allowed range of paramters.
Raises a warning if outside self.soft_param_lims limits and
raises an error if outside self.hard_param_lims.
If allow_extrap=True, skips these checks.
"""
... | Checks that params are within allowed range of paramters.
Raises a warning if outside self.soft_param_lims limits and
raises an error if outside self.hard_param_lims.
If allow_extrap=True, skips these checks. | entailment |
def slot(self, slot_index, marshal=None, unmarshal=None, build=None, cast=None, compress=False):
"""
Decorator for use on classes derived from zlmdb.PersistentMap. The decorator define slots
in a LMDB database schema based on persistent maps, and slot configuration.
:param slot_index:
... | Decorator for use on classes derived from zlmdb.PersistentMap. The decorator define slots
in a LMDB database schema based on persistent maps, and slot configuration.
:param slot_index:
:param marshal:
:param unmarshal:
:param build:
:param cast:
:param compress:
... | entailment |
def DataPath():
""" Return the default path for fit data h5 files"""
return os.path.abspath('%s/data'%(os.path.dirname( \
os.path.realpath(__file__)))) | Return the default path for fit data h5 files | entailment |
def request_object_encryption(msg, service_context, **kwargs):
"""
Created an encrypted JSON Web token with *msg* as body.
:param msg: The mesaqg
:param service_context:
:param kwargs:
:return:
"""
try:
encalg = kwargs["request_object_encryption_alg"]
except KeyError:
... | Created an encrypted JSON Web token with *msg* as body.
:param msg: The mesaqg
:param service_context:
:param kwargs:
:return: | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.