code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def get_nested_streams(dmap):
"""Recurses supplied DynamicMap to find all streams
Args:
dmap: DynamicMap to recurse to look for streams
Returns:
List of streams that were found
"""
return list({s for dmap in get_nested_dmaps(dmap) for s in dmap.streams}) | Recurses supplied DynamicMap to find all streams
Args:
dmap: DynamicMap to recurse to look for streams
Returns:
List of streams that were found |
def create_folder(query, default_name=None, default_path=None):
"""Shows a user dialog for folder creation
A dialog is opened with the prompt `query`. The current path is set to the last path that was opened/created. The
roots of all libraries is added to the list of shortcut folders.
:param ... | Shows a user dialog for folder creation
A dialog is opened with the prompt `query`. The current path is set to the last path that was opened/created. The
roots of all libraries is added to the list of shortcut folders.
:param str query: Prompt asking the user for a specific folder
:param str ... |
def get_line_flux(line_wave, wave, flux, **kwargs):
"""Interpolated flux at a given wavelength (calls np.interp)."""
return np.interp(line_wave, wave, flux, **kwargs) | Interpolated flux at a given wavelength (calls np.interp). |
def get_certificate():
''' Read openvswitch certificate from disk '''
if os.path.exists(CERT_PATH):
log('Reading ovs certificate from {}'.format(CERT_PATH))
with open(CERT_PATH, 'r') as cert:
full_cert = cert.read()
begin_marker = "-----BEGIN CERTIFICATE-----"
... | Read openvswitch certificate from disk |
def _is_empty(self):
"""
True if this cell contains only a single empty ``<w:p>`` element.
"""
block_items = list(self.iter_block_items())
if len(block_items) > 1:
return False
p = block_items[0] # cell must include at least one <w:p> element
if len(p... | True if this cell contains only a single empty ``<w:p>`` element. |
def fwdl_status_output_fwdl_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fwdl_status = ET.Element("fwdl_status")
config = fwdl_status
output = ET.SubElement(fwdl_status, "output")
fwdl_state = ET.SubElement(output, "fwdl-state")
... | Auto Generated Code |
def dump(file_name, predictions=None, algo=None, verbose=0):
"""A basic wrapper around Pickle to serialize a list of prediction and/or
an algorithm on drive.
What is dumped is a dictionary with keys ``'predictions'`` and ``'algo'``.
Args:
file_name(str): The name (with full path) specifying wh... | A basic wrapper around Pickle to serialize a list of prediction and/or
an algorithm on drive.
What is dumped is a dictionary with keys ``'predictions'`` and ``'algo'``.
Args:
file_name(str): The name (with full path) specifying where to dump the
predictions.
predictions(list of... |
def _processing_controller_status(self):
"""Report on the status of the Processing Block queue(s)."""
LOG.info('Starting Processing Block queue reporter.')
while True:
LOG.info('PB queue length = %d', len(self._queue))
time.sleep(self._report_interval)
if acti... | Report on the status of the Processing Block queue(s). |
def start(name, call=None):
'''
Start a node
CLI Examples:
.. code-block:: bash
salt-cloud -a start myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Starting node %s', name... | Start a node
CLI Examples:
.. code-block:: bash
salt-cloud -a start myinstance |
def state(self):
"""State of this service."""
if self._proto.HasField('state'):
return yamcsManagement_pb2.ServiceState.Name(self._proto.state)
return None | State of this service. |
def w(msg, *args, **kwargs):
'''
log a message at warn level;
'''
return logging.log(WARN, msg, *args, **kwargs) | log a message at warn level; |
def copyfileobj(fsrc, fdst, length=16*1024):
"""copy data from file-like object fsrc to file-like object fdst"""
while 1:
buf = fsrc.read(length)
if not buf:
break
fdst.write(buf) | copy data from file-like object fsrc to file-like object fdst |
def refresh_oauth_credential(self):
"""Refresh session's OAuth 2.0 credentials if they are stale."""
if self.session.token_type == auth.SERVER_TOKEN_TYPE:
return
credential = self.session.oauth2credential
if credential.is_stale():
refresh_session = refresh_access... | Refresh session's OAuth 2.0 credentials if they are stale. |
def E(self,*args,**kwargs):
"""
NAME:
E
PURPOSE:
calculate the energy
INPUT:
t - (optional) time at which to get the radius
pot= potential instance or list of such instances
OUTPUT:
energy
HISTORY:
2010-09-... | NAME:
E
PURPOSE:
calculate the energy
INPUT:
t - (optional) time at which to get the radius
pot= potential instance or list of such instances
OUTPUT:
energy
HISTORY:
2010-09-15 - Written - Bovy (NYU)
2011-04-18 ... |
def add_callback(self, name, func):
"""Add a callback when device events happen.
Args:
name (str): currently support 'on_scan' and 'on_disconnect'
func (callable): the function that should be called
"""
if name == 'on_scan':
events = ['device_seen']
... | Add a callback when device events happen.
Args:
name (str): currently support 'on_scan' and 'on_disconnect'
func (callable): the function that should be called |
def get_account_tokens(self, address):
"""
Get the list of tokens that this address owns
"""
cur = self.db.cursor()
return namedb_get_account_tokens(cur, address) | Get the list of tokens that this address owns |
def push(self, undoObj):
"""
Add ``undoObj`` command to stack and run its ``commit`` method.
|Args|
* ``undoObj`` (**QtmacsUndoCommand**): the new command object.
|Returns|
* **None**
|Raises|
* **QtmacsArgumentError** if at least one argument has an... | Add ``undoObj`` command to stack and run its ``commit`` method.
|Args|
* ``undoObj`` (**QtmacsUndoCommand**): the new command object.
|Returns|
* **None**
|Raises|
* **QtmacsArgumentError** if at least one argument has an invalid type. |
async def fetch_lightpad(self, lpid):
"""Lookup details for a given lightpad"""
url = "https://production.plum.technology/v2/getLightpad"
data = {"lpid": lpid}
return await self.__post(url, data) | Lookup details for a given lightpad |
def Serialize(self, writer):
"""
Serialize full object.
Args:
writer (neo.IO.BinaryWriter):
"""
super(Header, self).Serialize(writer)
writer.WriteByte(0) | Serialize full object.
Args:
writer (neo.IO.BinaryWriter): |
def filter_slaves(selfie, slaves):
"""
Remove slaves that are in an ODOWN or SDOWN state
also remove slaves that do not have 'ok' master-link-status
"""
return [(s['ip'], s['port']) for s in slaves
if not s['is_odown'] and
not s['is_sdown'] and
... | Remove slaves that are in an ODOWN or SDOWN state
also remove slaves that do not have 'ok' master-link-status |
def lookup_field_label(self, context, field, default=None):
"""
Figures out what the field label should be for the passed in field name.
We overload this so as to use our form to see if there is label set there. If so
then we'll pass that as the default instead of having our parent der... | Figures out what the field label should be for the passed in field name.
We overload this so as to use our form to see if there is label set there. If so
then we'll pass that as the default instead of having our parent derive
the field from the name. |
def custom_background_code():
""" Custom code run in a background thread. Prints the current block height.
This function is run in a daemonized thread, which means it can be instantly killed at any
moment, whenever the main thread quits. If you need more safety, don't use a daemonized
thread and handl... | Custom code run in a background thread. Prints the current block height.
This function is run in a daemonized thread, which means it can be instantly killed at any
moment, whenever the main thread quits. If you need more safety, don't use a daemonized
thread and handle exiting this thread in another way (... |
def compose(f: Callable[[Any], Monad], g: Callable[[Any], Monad]) -> Callable[[Any], Monad]:
r"""Monadic compose function.
Right-to-left Kleisli composition of two monadic functions.
(<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c
f <=< g = \x -> g x >>= f
"""
return lambda x: g(x).bi... | r"""Monadic compose function.
Right-to-left Kleisli composition of two monadic functions.
(<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c
f <=< g = \x -> g x >>= f |
def get_critical_path_timings(self):
"""
Get the cumulative timings of each goal and all of the goals it (transitively) depended on.
"""
setup_workunit = WorkUnitLabel.SETUP.lower()
transitive_dependencies = dict()
for goal_info in self._sorted_goal_infos:
deps = transitive_dependencies.se... | Get the cumulative timings of each goal and all of the goals it (transitively) depended on. |
def create_response_dic(self):
"""
Generate the dic that will be jsonify. Checking scopes given vs
registered.
Returns a dic.
"""
dic = {}
for scope in self.scopes:
if scope in self._scopes_registered():
dic.update(getattr(self, 'scop... | Generate the dic that will be jsonify. Checking scopes given vs
registered.
Returns a dic. |
def getTypeWidth(self, dtype: "HdlType", do_eval=False) -> Tuple[int, str, bool]:
"""
:return: tuple (current value of width,
string of value (can be ID or int),
Flag which specifies if width of signal is locked
or can be changed by parameter)
"""
rais... | :return: tuple (current value of width,
string of value (can be ID or int),
Flag which specifies if width of signal is locked
or can be changed by parameter) |
def set_hostname(hostname=None, deploy=False):
'''
Set the hostname of the Palo Alto proxy minion. A commit will be required before this is processed.
CLI Example:
Args:
hostname (str): The hostname to set
deploy (bool): If true then commit the full candidate configuration, if false o... | Set the hostname of the Palo Alto proxy minion. A commit will be required before this is processed.
CLI Example:
Args:
hostname (str): The hostname to set
deploy (bool): If true then commit the full candidate configuration, if false only set pending change.
.. code-block:: bash
... |
def _delete(self):
"""Deletes this AssessmentSection from database.
Will be called by AssessmentTaken._delete() for clean-up purposes.
"""
collection = JSONClientValidated('assessment',
collection='AssessmentSection',
... | Deletes this AssessmentSection from database.
Will be called by AssessmentTaken._delete() for clean-up purposes. |
def run_license_checker(config_path):
# type: (str) -> None
"""Generate table of installed packages and check for license
warnings based off user defined restricted license values.
:param config_path: str
:return:
"""
whitelist_licenses = _get_whitelist_licenses(config_path)
table = Pri... | Generate table of installed packages and check for license
warnings based off user defined restricted license values.
:param config_path: str
:return: |
def create_unihan_table(columns, metadata):
"""Create table and return :class:`sqlalchemy.Table`.
Parameters
----------
columns : list
columns for table, e.g. ``['kDefinition', 'kCantonese']``
metadata : :class:`sqlalchemy.schema.MetaData`
Instance of sqlalchemy metadata
Retur... | Create table and return :class:`sqlalchemy.Table`.
Parameters
----------
columns : list
columns for table, e.g. ``['kDefinition', 'kCantonese']``
metadata : :class:`sqlalchemy.schema.MetaData`
Instance of sqlalchemy metadata
Returns
-------
:class:`sqlalchemy.schema.Table`... |
def angleOfView2(x,y, b, x0=None,y0=None):
'''
Corrected AngleOfView equation by Koentges (via mail from 14/02/2017)
b --> distance between the camera and the module in m
x0 --> viewable with in the module plane of the camera in m
y0 --> viewable height in the module plane of the camera in m
... | Corrected AngleOfView equation by Koentges (via mail from 14/02/2017)
b --> distance between the camera and the module in m
x0 --> viewable with in the module plane of the camera in m
y0 --> viewable height in the module plane of the camera in m
x,y --> pixel position [m] from top left |
def verify(info, directory_path):
"""Return True if the checksum values in the torrent file match the
computed checksum values of downloaded file(s) in the directory and if
each file has the correct length as specified in the torrent file.
"""
base_path = os.path.join(directory_path, info['name'])
... | Return True if the checksum values in the torrent file match the
computed checksum values of downloaded file(s) in the directory and if
each file has the correct length as specified in the torrent file. |
def run(self, queue):
"""
Create the fullname, and store a a message serving as result in the job
"""
# add some random time to simulate a long job
time.sleep(random.random())
# compute the fullname
obj = self.get_object()
obj.fullname.hset('%s %s' % tupl... | Create the fullname, and store a a message serving as result in the job |
def to_dict(self, index=True, ordered=False):
"""
Returns a dict where the keys are the column names and the values are lists of the values for that column.
:param index: If True then include the index in the dict with the index_name as the key
:param ordered: If True then return an Ord... | Returns a dict where the keys are the column names and the values are lists of the values for that column.
:param index: If True then include the index in the dict with the index_name as the key
:param ordered: If True then return an OrderedDict() to preserve the order of the columns in the DataFrame
... |
def expected_counts_stationary(T, n, mu=None):
r"""Expected transition counts for Markov chain in equilibrium.
Since mu is stationary for T we have
.. math::
E(C^{(N)})=N diag(mu)*T.
Parameters
----------
T : (M, M) ndarray
Transition matrix.
n : int
Number of ste... | r"""Expected transition counts for Markov chain in equilibrium.
Since mu is stationary for T we have
.. math::
E(C^{(N)})=N diag(mu)*T.
Parameters
----------
T : (M, M) ndarray
Transition matrix.
n : int
Number of steps for chain.
mu : (M,) ndarray (optional)
... |
def _set_preprovision(self, v, load=False):
"""
Setter method for preprovision, mapped from YANG variable /preprovision (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_preprovision is considered as a private
method. Backends looking to populate this varia... | Setter method for preprovision, mapped from YANG variable /preprovision (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_preprovision is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_preprovisi... |
def _find_single(self, match_class, **keywds):
"""implementation details"""
self._logger.debug('find single query execution - started')
start_time = timeit.default_timer()
norm_keywds = self.__normalize_args(**keywds)
decl_matcher = self.__create_matcher(match_class, **norm_keywd... | implementation details |
def _group_by_batches(samples, check_fn):
"""Group calls by batches, processing families together during ensemble calling.
"""
batch_groups = collections.defaultdict(list)
extras = []
for data in [x[0] for x in samples]:
if check_fn(data):
batch_groups[multi.get_batch_for_key(dat... | Group calls by batches, processing families together during ensemble calling. |
def execute_task(bufs):
"""Deserialize the buffer and execute the task.
Returns the result or throws exception.
"""
user_ns = locals()
user_ns.update({'__builtins__': __builtins__})
f, args, kwargs = unpack_apply_message(bufs, user_ns, copy=False)
# We might need to look into callability ... | Deserialize the buffer and execute the task.
Returns the result or throws exception. |
def backward_word_extend_selection(self, e): #
u"""Move back to the start of the current or previous word. Words are
composed of letters and digits."""
self.l_buffer.backward_word_extend_selection(self.argument_reset)
self.finalize() | u"""Move back to the start of the current or previous word. Words are
composed of letters and digits. |
def leave_room(self, sid, room, namespace=None):
"""Leave a room.
The only difference with the :func:`socketio.Server.leave_room` method
is that when the ``namespace`` argument is not given the namespace
associated with the class is used.
"""
return self.server.leave_roo... | Leave a room.
The only difference with the :func:`socketio.Server.leave_room` method
is that when the ``namespace`` argument is not given the namespace
associated with the class is used. |
def calculate_mean(samples, weights):
r'''Calculate the mean of weighted samples (like the output of an
importance-sampling run).
:param samples:
Matrix-like numpy array; the samples to be used.
:param weights:
Vector-like numpy array; the (unnormalized) importance weights.
'''
... | r'''Calculate the mean of weighted samples (like the output of an
importance-sampling run).
:param samples:
Matrix-like numpy array; the samples to be used.
:param weights:
Vector-like numpy array; the (unnormalized) importance weights. |
def negate(arg):
"""
Negate a numeric expression
Parameters
----------
arg : numeric value expression
Returns
-------
negated : type of caller
"""
op = arg.op()
if hasattr(op, 'negate'):
result = op.negate()
else:
result = ops.Negate(arg)
return res... | Negate a numeric expression
Parameters
----------
arg : numeric value expression
Returns
-------
negated : type of caller |
def __process_by_ccore(self):
"""!
@brief Performs cluster analysis using CCORE (C/C++ part of pyclustering library).
"""
cure_data_pointer = wrapper.cure_algorithm(self.__pointer_data, self.__number_cluster,
self.__number_represe... | !
@brief Performs cluster analysis using CCORE (C/C++ part of pyclustering library). |
def binary_operation_math(self, rule, left, right, **kwargs):
"""
Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.binary_operation_math` interface.
"""
if isinstance(left, NumberRule) and isinstance(right, NumberRule):
return self._calculate_operation_math(r... | Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.binary_operation_math` interface. |
def btc_script_classify(scriptpubkey, private_key_info=None):
"""
Classify a scriptpubkey, optionally also using the private key info that will generate the corresponding scriptsig/witness
Return None if not known (nonstandard)
"""
if scriptpubkey.startswith("76a914") and scriptpubkey.endswith("88ac... | Classify a scriptpubkey, optionally also using the private key info that will generate the corresponding scriptsig/witness
Return None if not known (nonstandard) |
def handle(self,
t_input: inference.TranslatorInput,
t_output: inference.TranslatorOutput,
t_walltime: float = 0.):
"""
:param t_input: Translator input.
:param t_output: Translator output.
:param t_walltime: Total walltime for translation.
... | :param t_input: Translator input.
:param t_output: Translator output.
:param t_walltime: Total walltime for translation. |
def unapply_top_patch(self, force=False):
""" Unapply top patch """
self._check(force)
patch = self.db.top_patch()
self._unapply_patch(patch)
self.db.save()
self.unapplied(self.db.top_patch()) | Unapply top patch |
def wb_db020(self, value=None):
""" Corresponds to IDD Field `wb_db020`
mean coincident wet-bulb temperature to
Dry-bulb temperature corresponding to 2.0% annual cumulative frequency of occurrence (warm conditions)
Args:
value (float): value for IDD Field `wb_db020`
... | Corresponds to IDD Field `wb_db020`
mean coincident wet-bulb temperature to
Dry-bulb temperature corresponding to 2.0% annual cumulative frequency of occurrence (warm conditions)
Args:
value (float): value for IDD Field `wb_db020`
Unit: C
if `value` i... |
def remove_objects_not_in(self, objects_to_keep, verbosity):
"""
Delete all the objects in the database that are not in objects_to_keep.
- objects_to_keep: A map where the keys are classes, and the values are a
set of the objects of that class we should keep.
"""
for cla... | Delete all the objects in the database that are not in objects_to_keep.
- objects_to_keep: A map where the keys are classes, and the values are a
set of the objects of that class we should keep. |
def setParameter(self, parameterName, index, parameterValue):
"""
Set the value of a Spec parameter. Most parameters are handled
automatically by PyRegion's parameter set mechanism. The ones that need
special treatment are explicitly handled here.
"""
if hasattr(self, parameterName):
setat... | Set the value of a Spec parameter. Most parameters are handled
automatically by PyRegion's parameter set mechanism. The ones that need
special treatment are explicitly handled here. |
def list_runtime(self, scope="", skip_policy_evaluation=True, start_time=None, end_time=None):
'''**Description**
List runtime containers
**Arguments**
- scope: An AND-composed string of predicates that selects the scope in which the alert will be applied. (like: 'host.domain = ... | **Description**
List runtime containers
**Arguments**
- scope: An AND-composed string of predicates that selects the scope in which the alert will be applied. (like: 'host.domain = "example.com" and container.image != "alpine:latest"')
- skip_policy_evaluation: If true, no p... |
def send_vdp_query_msg(self, mode, mgrid, typeid, typeid_ver, vsiid_frmt,
vsiid, filter_frmt, gid, mac, vlan, oui_id,
oui_data):
"""Constructs and Sends the VDP Query Message.
Please refer http://www.ieee802.org/1/pages/802.1bg.html VDP
Sect... | Constructs and Sends the VDP Query Message.
Please refer http://www.ieee802.org/1/pages/802.1bg.html VDP
Section for more detailed information
:param mode: Associate or De-associate
:param mgrid: MGR ID
:param typeid: Type ID
:param typeid_ver: Version of the Type ID
... |
def decompressBWTPoolProcess(tup):
'''
Individual process for decompression
'''
(inputDir, outputDir, startIndex, endIndex) = tup
if startIndex == endIndex:
return True
#load the thing we'll be extracting from
msbwt = MultiStringBWT.CompressedMSBWT()
msbwt.loadMsbwt(inp... | Individual process for decompression |
def parse_gzip(file_path):
"""Return a decoded API to the data from a file path. File is gzip compressed.
:param file_path: the input file path. Data is gzip compressed.
:return an API to decoded data"""
newDecoder = MMTFDecoder()
newDecoder.decode_data(_unpack(gzip.open(file_path, "rb")))
retur... | Return a decoded API to the data from a file path. File is gzip compressed.
:param file_path: the input file path. Data is gzip compressed.
:return an API to decoded data |
def artist_create(self, name, other_names_comma=None, group_name=None,
url_string=None, body=None):
"""Function to create an artist (Requires login) (UNTESTED).
Parameters:
name (str):
other_names_comma (str): List of alternative names for this
... | Function to create an artist (Requires login) (UNTESTED).
Parameters:
name (str):
other_names_comma (str): List of alternative names for this
artist, comma delimited.
group_name (str): The name of the group this artist belongs to.
... |
def main(doc, timeout, size, debug, allow_codes, whitelist):
"""
Examples:
simple call
$ vl README.md
Adding debug outputs
$ vl README.md --debug
Adding a custom timeout for each url. time on seconds.
$ vl README.md -t 3
Adding a custom size param, to add throttle n requests per... | Examples:
simple call
$ vl README.md
Adding debug outputs
$ vl README.md --debug
Adding a custom timeout for each url. time on seconds.
$ vl README.md -t 3
Adding a custom size param, to add throttle n requests per time
$ vl README -s 1000
Skipping some error codes. This will ... |
def at(host, command, seq, params):
"""
Parameters:
command -- the command
seq -- the sequence number
params -- a list of elements which can be either int, float or string
"""
params_str = []
for p in params:
if type(p) == int:
params_str.append('{:d}'.format(p))
... | Parameters:
command -- the command
seq -- the sequence number
params -- a list of elements which can be either int, float or string |
def get_tree(self, process_name):
""" return tree that is managing time-periods for given process"""
for tree_name, tree in self.trees.items():
if process_name in tree:
return tree | return tree that is managing time-periods for given process |
def precheck(context):
"""
calls a function named "precheck_<key>" where <key> is context_key with '-' changed to '_'
(e.g. "precheck_ami_id")
Checking function should return True if OK, or raise RuntimeError w/ message if not
Args:
context: a populated EFVersionContext object
Returns:
True if the p... | calls a function named "precheck_<key>" where <key> is context_key with '-' changed to '_'
(e.g. "precheck_ami_id")
Checking function should return True if OK, or raise RuntimeError w/ message if not
Args:
context: a populated EFVersionContext object
Returns:
True if the precheck passed, or if there was... |
def _runResponder(self, responder, request, command, identifier):
"""Run the responser function. If it succeeds, add the _answer key.
If it fails with an error known to the command, serialize the
error.
"""
d = defer.maybeDeferred(responder, **request)
def _addIdentifie... | Run the responser function. If it succeeds, add the _answer key.
If it fails with an error known to the command, serialize the
error. |
def discover(service="ssdp:all", timeout=1, retries=2, ipAddress="239.255.255.250", port=1900):
"""Discovers UPnP devices in the local network.
Try to discover all devices in the local network which do support UPnP. The discovery process can fail
for various reasons and it is recommended to do ... | Discovers UPnP devices in the local network.
Try to discover all devices in the local network which do support UPnP. The discovery process can fail
for various reasons and it is recommended to do at least two discoveries, which you can specify with the
``retries`` parameter.
The defaul... |
def gpgga_to_dms(gpgga):
'''
Convert GPS coordinate in GPGGA format to degree/minute/second
Reference: http://us.cactii.net/~bb/gps.py
'''
deg_min, dmin = gpgga.split('.')
degrees = int(deg_min[:-2])
minutes = float('%s.%s' % (deg_min[-2:], dmin))
decimal = degrees + (minutes / 60)
... | Convert GPS coordinate in GPGGA format to degree/minute/second
Reference: http://us.cactii.net/~bb/gps.py |
def geodetic_distance(lons1, lats1, lons2, lats2, diameter=2*EARTH_RADIUS):
"""
Calculate the geodetic distance between two points or two collections
of points.
Parameters are coordinates in decimal degrees. They could be scalar
float numbers or numpy arrays, in which case they should "broadcast
... | Calculate the geodetic distance between two points or two collections
of points.
Parameters are coordinates in decimal degrees. They could be scalar
float numbers or numpy arrays, in which case they should "broadcast
together".
Implements http://williams.best.vwh.net/avform.htm#Dist
:returns:... |
def vlr_factory(raw_vlr):
""" Given a raw_vlr tries to find its corresponding KnownVLR class
that can parse its data.
If no KnownVLR implementation is found, returns a VLR (record_data will still be bytes)
"""
user_id = raw_vlr.header.user_id.rstrip(NULL_BYTE).decode()
known_vlrs = BaseKnownVLR.... | Given a raw_vlr tries to find its corresponding KnownVLR class
that can parse its data.
If no KnownVLR implementation is found, returns a VLR (record_data will still be bytes) |
def doExperiment(numColumns, l2Overrides, objectDescriptions, noiseMu,
noiseSigma, numInitialTraversals, noiseEverywhere):
"""
Touch every point on an object 'numInitialTraversals' times, then evaluate
whether it has inferred the object by touching every point once more and
checking the number ... | Touch every point on an object 'numInitialTraversals' times, then evaluate
whether it has inferred the object by touching every point once more and
checking the number of correctly active and incorrectly active cells.
@param numColumns (int)
The number of sensors to use
@param l2Overrides (dict)
Parameter... |
def print_tb(tb, limit=None, file=None):
"""Print up to 'limit' stack trace entries from the traceback 'tb'.
If 'limit' is omitted or None, all entries are printed. If 'file'
is omitted or None, the output goes to sys.stderr; otherwise
'file' should be an open file or file-like object with a write()
... | Print up to 'limit' stack trace entries from the traceback 'tb'.
If 'limit' is omitted or None, all entries are printed. If 'file'
is omitted or None, the output goes to sys.stderr; otherwise
'file' should be an open file or file-like object with a write()
method. |
def on_receive_transactions(self, proto, transactions):
"receives rlp.decoded serialized"
log.debug('----------------------------------')
log.debug('remote_transactions_received', count=len(transactions), remote_id=proto)
def _add_txs():
for tx in transactions:
... | receives rlp.decoded serialized |
def _with_meta_to_py_ast(
ctx: GeneratorContext, node: WithMeta, **kwargs
) -> GeneratedPyAST:
"""Generate a Python AST node for Python interop method calls."""
assert node.op == NodeOp.WITH_META
handle_expr = _WITH_META_EXPR_HANDLER.get(node.expr.op)
assert (
handle_expr is not None
),... | Generate a Python AST node for Python interop method calls. |
def qteSplitApplet(self, applet: (QtmacsApplet, str)=None,
splitHoriz: bool=True,
windowObj: QtmacsWindow=None):
"""
Reveal ``applet`` by splitting the space occupied by the
current applet.
If ``applet`` is already visible then the method do... | Reveal ``applet`` by splitting the space occupied by the
current applet.
If ``applet`` is already visible then the method does
nothing. Furthermore, this method does not change the focus,
ie. the currently active applet will remain active.
If ``applet`` is **None** then the nex... |
def row_table(cls, d, order=None, labels=None):
"""prints a pretty table from data in the dict.
:param d: A dict to be printed
:param order: The order in which the columns are printed.
The order is specified by the key names of the dict.
:param labels: The array of ... | prints a pretty table from data in the dict.
:param d: A dict to be printed
:param order: The order in which the columns are printed.
The order is specified by the key names of the dict.
:param labels: The array of labels for the column |
def security(policy, app_secret):
"""
Creates a valid signature and policy based on provided app secret and
parameters
```python
from filestack import Client, security
# a policy requires at least an expiry
policy = {'expiry': 56589012, 'call': ['read', 'store', 'pick']}
sec = security(... | Creates a valid signature and policy based on provided app secret and
parameters
```python
from filestack import Client, security
# a policy requires at least an expiry
policy = {'expiry': 56589012, 'call': ['read', 'store', 'pick']}
sec = security(policy, 'APP_SECRET')
client = Client('A... |
def replace_nan( trainingset, replace_with = None ): # if replace_with = None, replaces with mean value
"""
Replace instanced of "not a number" with either the mean of the signal feature
or a specific value assigned by `replace_nan_with`
"""
training_data = np.array( [instance.features for instance ... | Replace instanced of "not a number" with either the mean of the signal feature
or a specific value assigned by `replace_nan_with` |
def update_entity(self, table_name, entity, if_match='*', timeout=None):
'''
Updates an existing entity in a table. Throws if the entity does not exist.
The update_entity operation replaces the entire entity and can be used to
remove properties.
:param str table_name:
... | Updates an existing entity in a table. Throws if the entity does not exist.
The update_entity operation replaces the entire entity and can be used to
remove properties.
:param str table_name:
The name of the table containing the entity to update.
:param entity:
... |
def UpdateFlow(self,
client_id,
flow_id,
flow_obj=db.Database.unchanged,
flow_state=db.Database.unchanged,
client_crash_info=db.Database.unchanged,
pending_termination=db.Database.unchanged,
processing... | Updates flow objects in the database. |
def get_mods(self, project_path, vars):
"""
Build the mod list to enable
"""
# Start with answers from interactive command
mods = [var.name for var in self.vars if vars[var.name].lower() == 'yes']
mods = set(mods)
# Base mods
for name in self.mods_list:
... | Build the mod list to enable |
def _legacy_symbol_table(build_file_aliases):
"""Construct a SymbolTable for the given BuildFileAliases.
:param build_file_aliases: BuildFileAliases to register.
:type build_file_aliases: :class:`pants.build_graph.build_file_aliases.BuildFileAliases`
:returns: A SymbolTable.
"""
table = {
alias: _make... | Construct a SymbolTable for the given BuildFileAliases.
:param build_file_aliases: BuildFileAliases to register.
:type build_file_aliases: :class:`pants.build_graph.build_file_aliases.BuildFileAliases`
:returns: A SymbolTable. |
def search(self,
initial_state: State,
transition_function: TransitionFunction) -> Dict[int, List[State]]:
"""
Parameters
----------
initial_state : ``State``
The starting state of our search. This is assumed to be `batched`, and our beam search... | Parameters
----------
initial_state : ``State``
The starting state of our search. This is assumed to be `batched`, and our beam search
is batch-aware - we'll keep ``beam_size`` states around for each instance in the batch.
transition_function : ``TransitionFunction``
... |
def refresh(self, accept=MEDIA_TYPE_TAXII_V20):
"""Updates Status information"""
response = self.__raw = self._conn.get(self.url,
headers={"Accept": accept})
self._populate_fields(**response) | Updates Status information |
def heating_stats(self):
"""Calculate some heating data stats."""
local_5 = []
local_10 = []
for i in range(0, 10):
level = self.past_heating_level(i)
if level == 0:
_LOGGER.debug('Cant calculate stats yet...')
return
i... | Calculate some heating data stats. |
def nearest(items, pivot):
'''Find nearest value in array, including datetimes
Args
----
items: iterable
List of values from which to find nearest value to `pivot`
pivot: int or float
Value to find nearest of in `items`
Returns
-------
nearest: int or float
Valu... | Find nearest value in array, including datetimes
Args
----
items: iterable
List of values from which to find nearest value to `pivot`
pivot: int or float
Value to find nearest of in `items`
Returns
-------
nearest: int or float
Value in items nearest to `pivot` |
def render_response(self):
"""Render as a string formatted for HTTP response headers
(detailed 'Set-Cookie: ' style).
"""
# Use whatever renderers are defined for name and value.
# (.attributes() is responsible for all other rendering.)
name, value = self.name, self.value... | Render as a string formatted for HTTP response headers
(detailed 'Set-Cookie: ' style). |
def get_method(self, method_name, default=None):
"""
Returns the contained method of the specified name, or `default` if
not found.
"""
for method in self.methods:
if method.name == method_name:
return method
return default | Returns the contained method of the specified name, or `default` if
not found. |
def set_focused(self, account, is_focused):
# type: (OutlookAccount, bool) -> bool
""" Emails from this contact will either always be put in the Focused inbox, or always put in Other, based on
the value of is_focused.
Args:
account (OutlookAccount): The :class:`OutlookAccoun... | Emails from this contact will either always be put in the Focused inbox, or always put in Other, based on
the value of is_focused.
Args:
account (OutlookAccount): The :class:`OutlookAccount <pyOutlook.core.main.OutlookAccount>`
the override should be set for
is_f... |
def _leave_event_hide(self):
""" Hides the tooltip after some time has passed (assuming the cursor is
not over the tooltip).
"""
if (not self._hide_timer.isActive() and
# If Enter events always came after Leave events, we wouldn't need
# this check. But on Mac... | Hides the tooltip after some time has passed (assuming the cursor is
not over the tooltip). |
def p_base_type(self, p): # noqa
'''base_type : BOOL annotations
| BYTE annotations
| I8 annotations
| I16 annotations
| I32 annotations
| I64 annotations
| DOUBLE annotations
... | base_type : BOOL annotations
| BYTE annotations
| I8 annotations
| I16 annotations
| I32 annotations
| I64 annotations
| DOUBLE annotations
| STRING annotations
... |
def reset(self):
"""
Resets stream parameters to their defaults.
"""
with util.disable_constant(self):
for k, p in self.params().items():
if k != 'name':
setattr(self, k, p.default) | Resets stream parameters to their defaults. |
def connect(self, address='session'):
"""Connect to *address* and wait until the connection is established.
The *address* argument must be a D-BUS server address, in the format
described in the D-BUS specification. It may also be one of the special
addresses ``'session'`` or ``'system'`... | Connect to *address* and wait until the connection is established.
The *address* argument must be a D-BUS server address, in the format
described in the D-BUS specification. It may also be one of the special
addresses ``'session'`` or ``'system'``, to connect to the D-BUS
session and sy... |
def generate(self, trilegal_filename, ra=None, dec=None,
n=2e4, ichrone='mist', MAfn=None,
mags=None, maxrad=None, f_binary=0.4, **kwargs):
"""
Generate population.
"""
n = int(n)
#generate/load BG primary stars from TRILEGAL simulation
... | Generate population. |
def daterange(value, details=False):
'''Display a date range in the shorter possible maner.'''
if not isinstance(value, db.DateRange):
raise ValueError('daterange only accept db.DateRange as parameter')
if details:
return daterange_with_details(value)
date_format = 'YYYY'
delta = ... | Display a date range in the shorter possible maner. |
def set_data(self, index, value):
"""Uses given data setter, and emit modelReset signal"""
acces, field = self.get_item(index), self.header[index.column()]
self.beginResetModel()
self.set_data_hook(acces, field, value)
self.endResetModel() | Uses given data setter, and emit modelReset signal |
def _run_command(self, arguments: List[str], input_data: Any=None, output_encoding: str="utf-8") -> str:
"""
Run a command as a subprocess.
Ignores errors given over stderr if there is output on stdout (this is the case where baton has been run
correctly and has expressed the error in i... | Run a command as a subprocess.
Ignores errors given over stderr if there is output on stdout (this is the case where baton has been run
correctly and has expressed the error in it's JSON out, which can be handled more appropriately upstream to this
method.)
:param arguments: the argumen... |
def prepare_response(self, request, cached):
"""Verify our vary headers match and construct a real urllib3
HTTPResponse object.
"""
# Special case the '*' Vary value as it means we cannot actually
# determine if the cached response is suitable for this request.
if "*" in ... | Verify our vary headers match and construct a real urllib3
HTTPResponse object. |
def line_cap_type(self):
"""Cap type, one of `butt`, `round`, `square`."""
key = self._data.get(b'strokeStyleLineCapType').enum
return self.STROKE_STYLE_LINE_CAP_TYPES.get(key, str(key)) | Cap type, one of `butt`, `round`, `square`. |
def nodes(self):
"""
Return the nodes for this VSS Container
:rtype: SubElementCollection(VSSContainerNode)
"""
resource = sub_collection(
self.get_relation('vss_container_node'),
VSSContainerNode)
resource._load_from_engine(self, 'nodes... | Return the nodes for this VSS Container
:rtype: SubElementCollection(VSSContainerNode) |
def repl_command(fxn):
"""
Decorator for cmd methods
Parses arguments from the arg string and passes them to the method as *args
and **kwargs.
"""
@functools.wraps(fxn)
def wrapper(self, arglist):
"""Wraps the command method"""
args = []
kwargs = {}
if argl... | Decorator for cmd methods
Parses arguments from the arg string and passes them to the method as *args
and **kwargs. |
def verify(self, otp, for_time=None, valid_window=0):
"""
Verifies the OTP passed in against the current time OTP
@param [String/Integer] otp the OTP to check against
@param [Integer] valid_window extends the validity to this many counter ticks before and after the current one
""... | Verifies the OTP passed in against the current time OTP
@param [String/Integer] otp the OTP to check against
@param [Integer] valid_window extends the validity to this many counter ticks before and after the current one |
def expectation_importance_sampler_logspace(
log_f,
log_p,
sampling_dist_q,
z=None,
n=None,
seed=None,
name='expectation_importance_sampler_logspace'):
r"""Importance sampling with a positive function, in log-space.
With \\(p(z) := exp^{log_p(z)}\\), and \\(f(z) = exp{log_f(z)}\\),
th... | r"""Importance sampling with a positive function, in log-space.
With \\(p(z) := exp^{log_p(z)}\\), and \\(f(z) = exp{log_f(z)}\\),
this `Op` returns
\\(Log[ n^{-1} sum_{i=1}^n [ f(z_i) p(z_i) / q(z_i) ] ], z_i ~ q,\\)
\\(\approx Log[ E_q[ f(Z) p(Z) / q(Z) ] ]\\)
\\(= Log[E_p[f(Z)]]\\)
This integra... |
def write_elements(fd, mtp, data, is_name=False):
"""Write data element tag and data.
The tag contains the array type and the number of
bytes the array data will occupy when written to file.
If data occupies 4 bytes or less, it is written immediately
as a Small Data Element (SDE).
"""
fmt ... | Write data element tag and data.
The tag contains the array type and the number of
bytes the array data will occupy when written to file.
If data occupies 4 bytes or less, it is written immediately
as a Small Data Element (SDE). |
def graft_neuron(root_section):
'''Returns a neuron starting at root_section'''
assert isinstance(root_section, Section)
return Neuron(soma=Soma(root_section.points[:1]), neurites=[Neurite(root_section)]) | Returns a neuron starting at root_section |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.