code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def toString(self, obj):
"""
Convert the given L{Identifier} to a string.
"""
return Box(shareID=obj.shareID.encode('utf-8'),
localpart=obj.localpart.encode('utf-8'),
domain=obj.domain.encode('utf-8')).serialize() | Convert the given L{Identifier} to a string. |
def _gen_dimension_table(self):
"""
2D array describing each registered dimension
together with headers - for use in __str__
"""
headers = ['Dimension Name', 'Description',
'Global Size', 'Extents']
table = []
for dimval in sorted(self.dimensions(copy... | 2D array describing each registered dimension
together with headers - for use in __str__ |
def automodsumm_to_autosummary_lines(fn, app):
"""
Generates lines from a file with an "automodsumm" entry suitable for
feeding into "autosummary".
Searches the provided file for `automodsumm` directives and returns
a list of lines specifying the `autosummary` commands for the modules
requested... | Generates lines from a file with an "automodsumm" entry suitable for
feeding into "autosummary".
Searches the provided file for `automodsumm` directives and returns
a list of lines specifying the `autosummary` commands for the modules
requested. This does *not* return the whole file contents - just an
... |
def remote_space_available(self, search_pattern=r"(\d+) \w+ free"):
"""Return space available on remote device."""
remote_cmd = "dir {}".format(self.file_system)
remote_output = self.ssh_ctl_chan.send_command_expect(remote_cmd)
match = re.search(search_pattern, remote_output)
if ... | Return space available on remote device. |
def cv_squared(x):
"""The squared coefficient of variation of a sample.
Useful as a loss to encourage a positive distribution to be more uniform.
Epsilons added for numerical stability.
Returns 0 for an empty Tensor.
Args:
x: a `Tensor`.
Returns:
a `Scalar`.
"""
epsilon = 1e-10
float_size =... | The squared coefficient of variation of a sample.
Useful as a loss to encourage a positive distribution to be more uniform.
Epsilons added for numerical stability.
Returns 0 for an empty Tensor.
Args:
x: a `Tensor`.
Returns:
a `Scalar`. |
def auth_criteria(self):
"""
This attribute provides the mapping of services to their auth requirement
Returns:
(dict) : the mapping from services to their auth requirements.
"""
# the dictionary we will return
auth = {}
# go over each at... | This attribute provides the mapping of services to their auth requirement
Returns:
(dict) : the mapping from services to their auth requirements. |
def download_files_maybe_extract(urls, directory, check_files=[]):
""" Download the files at ``urls`` to ``directory``. Extract to ``directory`` if tar or zip.
Args:
urls (str): Url of files.
directory (str): Directory to download to.
check_files (list of str): Check if these files exis... | Download the files at ``urls`` to ``directory``. Extract to ``directory`` if tar or zip.
Args:
urls (str): Url of files.
directory (str): Directory to download to.
check_files (list of str): Check if these files exist, ensuring the download succeeded.
If these files exist before... |
def read_data(self, blocksize=4096):
"""Generates byte strings reflecting the audio data in the file.
"""
frames = ctypes.c_uint(blocksize // self._client_fmt.mBytesPerFrame)
buf = ctypes.create_string_buffer(blocksize)
buflist = AudioBufferList()
buflist.mNumberBuffers ... | Generates byte strings reflecting the audio data in the file. |
def log_indexing_error(cls, indexing_errors):
""" Logs indexing errors and raises a general ElasticSearch Exception"""
indexing_errors_log = []
for indexing_error in indexing_errors:
indexing_errors_log.append(str(indexing_error))
raise exceptions.ElasticsearchException(', '.... | Logs indexing errors and raises a general ElasticSearch Exception |
def check_str(obj):
""" Returns a string for various input types """
if isinstance(obj, str):
return obj
if isinstance(obj, float):
return str(int(obj))
else:
return str(obj) | Returns a string for various input types |
def points(self):
""" returns a pointer to the points as a numpy object """
vtk_data = self.GetPoints().GetData()
arr = vtk_to_numpy(vtk_data)
return vtki_ndarray(arr, vtk_data) | returns a pointer to the points as a numpy object |
def unset_sentry_context(self, tag):
"""Remove a context tag from sentry
:param tag: The context tag to remove
:type tag: :class:`str`
"""
if self.sentry_client:
self.sentry_client.tags.pop(tag, None) | Remove a context tag from sentry
:param tag: The context tag to remove
:type tag: :class:`str` |
def parse_sentry_configuration(filename):
"""Parse Sentry DSN out of an application or Sentry configuration file"""
filetype = os.path.splitext(filename)[-1][1:].lower()
if filetype == 'ini': # Pyramid, Pylons
config = ConfigParser()
config.read(filename)
ini_key = 'dsn'
in... | Parse Sentry DSN out of an application or Sentry configuration file |
def mktar_from_dockerfile(fileobject: BinaryIO) -> IO:
"""
Create a zipped tar archive from a Dockerfile
**Remember to close the file object**
Args:
fileobj: a Dockerfile
Returns:
a NamedTemporaryFile() object
"""
f = tempfile.NamedTemporaryFile()
t = tarfile.open(mode="... | Create a zipped tar archive from a Dockerfile
**Remember to close the file object**
Args:
fileobj: a Dockerfile
Returns:
a NamedTemporaryFile() object |
def frontendediting_request_processor(page, request):
"""
Sets the frontend editing state in the cookie depending on the
``frontend_editing`` GET parameter and the user's permissions.
"""
if 'frontend_editing' not in request.GET:
return
response = HttpResponseRedirect(request.path)
... | Sets the frontend editing state in the cookie depending on the
``frontend_editing`` GET parameter and the user's permissions. |
def __calculate_center(self, cluster):
"""!
@brief Calculates new center.
@return (list) New value of the center of the specified cluster.
"""
dimension = len(self.__pointer_data[cluster[0]]);
center = [0] * dimension;
for index_point i... | !
@brief Calculates new center.
@return (list) New value of the center of the specified cluster. |
def proc_monomer(self, monomer_info, parent, mon_cls=False):
"""Processes a records into a `Monomer`.
Parameters
----------
monomer_info : (set, OrderedDict)
Labels and data for a monomer.
parent : ampal.Polymer
`Polymer` used to assign `ampal_parent` on ... | Processes a records into a `Monomer`.
Parameters
----------
monomer_info : (set, OrderedDict)
Labels and data for a monomer.
parent : ampal.Polymer
`Polymer` used to assign `ampal_parent` on created
`Monomer`.
mon_cls : `Monomer class or subcl... |
def stop(self, timeout=None):
"""Requests device to stop running, waiting at most the given timout in seconds (fractional). Has no effect if
`run()` was not called with background=True set. Returns True if successfully stopped (or already not running).
"""
stopped = True
self.__s... | Requests device to stop running, waiting at most the given timout in seconds (fractional). Has no effect if
`run()` was not called with background=True set. Returns True if successfully stopped (or already not running). |
def export_network(nw, mode=''):
"""
Export all nodes and lines of the network nw as DataFrames
Parameters
----------
nw: :any:`list` of NetworkDing0
The MV grid(s) to be studied
mode: str
If 'MV' export only medium voltage nodes and lines
If 'LV' export only low voltage... | Export all nodes and lines of the network nw as DataFrames
Parameters
----------
nw: :any:`list` of NetworkDing0
The MV grid(s) to be studied
mode: str
If 'MV' export only medium voltage nodes and lines
If 'LV' export only low voltage nodes and lines
else, exports MV and... |
def print_rev_id(localRepoPath):
"""prints information about the specified local repository to STDOUT. Expected method of execution: command-line or
shell script call
Parameters
----------
localRepoPath: string
Local repository path.
Returns
=======
Nothing as such. subroutine ... | prints information about the specified local repository to STDOUT. Expected method of execution: command-line or
shell script call
Parameters
----------
localRepoPath: string
Local repository path.
Returns
=======
Nothing as such. subroutine will exit with a state of 0 if everythin... |
def get_user(uid):
"""Get an user by the UID.
:param str uid: UID to find
:return: the user
:rtype: User object
:raises ValueError: uid is not an integer
:raises KeyError: if user does not exist
"""
if db is not None:
try:
uid = uid.decode('utf-8')
except Att... | Get an user by the UID.
:param str uid: UID to find
:return: the user
:rtype: User object
:raises ValueError: uid is not an integer
:raises KeyError: if user does not exist |
def evaluate(self, password=''):
"""Evaluates the development set.
The passwords is sent as plain text.
:return: the evaluation results.
"""
# Make a copy only keeping the development set
dev_submission = self
if self['metadata'].get('evaluation_setting', {}).g... | Evaluates the development set.
The passwords is sent as plain text.
:return: the evaluation results. |
def _event_monitor_loop(region_name, vpc_id,
watcher_plugin, health_plugin,
iterations, sleep_time,
route_check_time_interval=30):
"""
Monitor queues to receive updates about new route specs or any detected
failed IPs.
If any of th... | Monitor queues to receive updates about new route specs or any detected
failed IPs.
If any of those have updates, notify the health-monitor thread with a
message on a special queue and also re-process the entire routing table.
The 'iterations' argument allows us to limit the running time of the watch
... |
def getLatency(self, instId: int) -> float:
"""
Return a dict with client identifier as a key and calculated latency as a value
"""
if len(self.clientAvgReqLatencies) == 0:
return 0.0
return self.clientAvgReqLatencies[instId].get_avg_latency() | Return a dict with client identifier as a key and calculated latency as a value |
def _set_member_vlan(self, v, load=False):
"""
Setter method for member_vlan, mapped from YANG variable /topology_group/member_vlan (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_member_vlan is considered as a private
method. Backends looking to populate... | Setter method for member_vlan, mapped from YANG variable /topology_group/member_vlan (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_member_vlan is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._se... |
def _get_or_open_file(filename):
'''If ``filename`` is a string or bytes object, open the
``filename`` and return the file object. If ``filename`` is
file-like (i.e., it has 'read' and 'write' attributes, return
``filename``.
Parameters
----------
filename : str,... | If ``filename`` is a string or bytes object, open the
``filename`` and return the file object. If ``filename`` is
file-like (i.e., it has 'read' and 'write' attributes, return
``filename``.
Parameters
----------
filename : str, bytes, file
Raises
------
... |
def nl_send(sk, msg):
"""Transmit Netlink message.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L416
Transmits the Netlink message `msg` over the Netlink socket using the `socket.sendmsg()`. This function is based on
`nl_send_iovec()`.
The message is addressed to the peer as specifi... | Transmit Netlink message.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L416
Transmits the Netlink message `msg` over the Netlink socket using the `socket.sendmsg()`. This function is based on
`nl_send_iovec()`.
The message is addressed to the peer as specified in the socket by either th... |
def _load_fsstat_data(self, timeout=3):
"""Using :command:`fsstat`, adds some additional information of the volume to the Volume."""
def stats_thread():
try:
cmd = ['fsstat', self.get_raw_path(), '-o', str(self.offset // self.disk.block_size)]
# Setting the ... | Using :command:`fsstat`, adds some additional information of the volume to the Volume. |
def connect(self, hardware: hc.API):
""" Connect to a running hardware API.
This can be either a simulator or a full hardware controller.
Note that there is no true disconnected state for a
:py:class:`.ProtocolContext`; :py:meth:`disconnect` simply creates
a new simulator and r... | Connect to a running hardware API.
This can be either a simulator or a full hardware controller.
Note that there is no true disconnected state for a
:py:class:`.ProtocolContext`; :py:meth:`disconnect` simply creates
a new simulator and replaces the current hardware with it. |
def start(path=None, host=None, port=None, color=None, cors=None, detach=False, nolog=False):
"""start web server"""
if detach:
sys.argv.append('--no-log')
idx = sys.argv.index('-d')
del sys.argv[idx]
cmd = sys.executable + ' ' + ' '.join([sys.argv[0], 'start'] + sys.argv[1... | start web server |
def sqlite_to_csv(
input_filename,
table_name,
output_filename,
dialect=csv.excel,
batch_size=10000,
encoding="utf-8",
callback=None,
query=None,
):
"""Export a table inside a SQLite database to CSV"""
# TODO: should be able to specify fields
# TODO: should be able to specif... | Export a table inside a SQLite database to CSV |
def save(self, **kwargs):
"""
Method that creates the translations tasks for every selected instance
:param kwargs:
:return:
"""
try:
# result_ids = []
manager = Manager()
for item in self.model_class.objects.language(manager.get_main_... | Method that creates the translations tasks for every selected instance
:param kwargs:
:return: |
def create_skeleton(shutit):
"""Creates module based on a pattern supplied as a git repo.
"""
skel_path = shutit.cfg['skeleton']['path']
skel_module_name = shutit.cfg['skeleton']['module_name']
skel_domain = shutit.cfg['skeleton']['domain']
skel_domain_hash = shutit.cfg['skeleton']['domain_hash']
ske... | Creates module based on a pattern supplied as a git repo. |
def get_transaction_index(self, transaction_hash: Hash32) -> Tuple[BlockNumber, int]:
"""
Returns a 2-tuple of (block_number, transaction_index) indicating which
block the given transaction can be found in and at what index in the
block transactions.
Raises TransactionNotFound i... | Returns a 2-tuple of (block_number, transaction_index) indicating which
block the given transaction can be found in and at what index in the
block transactions.
Raises TransactionNotFound if the transaction_hash is not found in the
canonical chain. |
def pacl_term(DiamTube, ConcClay, ConcAl, ConcNatOrgMat, NatOrgMat,
coag, material, RatioHeightDiameter):
"""Return the fraction of the surface area that is covered with coagulant
that is not covered with humic acid.
:param DiamTube: Diameter of the dosing tube
:type Diamtube: float
... | Return the fraction of the surface area that is covered with coagulant
that is not covered with humic acid.
:param DiamTube: Diameter of the dosing tube
:type Diamtube: float
:param ConcClay: Concentration of clay in solution
:type ConcClay: float
:param ConcAl: Concentration of alumninum in so... |
def reformat(found_sequences):
'''Truncate the FASTA headers so that the first field is a 4-character ID.'''
for (pdb_id, chain, file_name), sequence in sorted(found_sequences.iteritems()):
header = sequence[0]
assert(header[0] == '>')
tokens = header.split('|')
tokens[0] = token... | Truncate the FASTA headers so that the first field is a 4-character ID. |
def plot(data: Dict[str, np.array], fields: List[str] = None, *args, **kwargs):
"""
Plot simulation data.
:data: A dictionary of arrays.
:fields: A list of variables you want to plot (e.g. ['x', y', 'c'])
"""
if plt is None:
return
if fields is None:
fields = ['x', 'y', 'm',... | Plot simulation data.
:data: A dictionary of arrays.
:fields: A list of variables you want to plot (e.g. ['x', y', 'c']) |
def exclude_fields(self):
"""Excludes fields that are included in the queryparameters"""
request = self.context.get('request')
if request:
exclude = request.query_params.get('exclude', None)
if exclude is None: return
excluded_fields = exclude... | Excludes fields that are included in the queryparameters |
def download(self):
"""
MLBAM dataset download
"""
p = Pool()
p.map(self._download, self.days) | MLBAM dataset download |
def setup(self, **kwargs):
'''
This is called during production de-trending, prior to
calling the :py:obj:`Detrender.run()` method.
:param inter piter: The number of iterations in the minimizer. \
Default 3
:param int pmaxf: The maximum number of function evaluati... | This is called during production de-trending, prior to
calling the :py:obj:`Detrender.run()` method.
:param inter piter: The number of iterations in the minimizer. \
Default 3
:param int pmaxf: The maximum number of function evaluations per \
iteration. Default 300... |
def update(self):
"""todo: Docstring for update
:return:
:rtype:
"""
logger.debug("")
rd = self.repo_dir
logger.debug("pkg path %s", rd)
if not rd:
print(
"unable to find pkg '%s'. %s" % (self.name, did_u_mean(self.name))
... | todo: Docstring for update
:return:
:rtype: |
def _ack(self, message_id, subscription_id, **kwargs):
"""Acknowledge receipt of a message. This only makes sense when the
'acknowledgement' flag was set for the relevant subscription.
:param message_id: ID of the message to be acknowledged
:param subscription: ID of the relevant subscri... | Acknowledge receipt of a message. This only makes sense when the
'acknowledgement' flag was set for the relevant subscription.
:param message_id: ID of the message to be acknowledged
:param subscription: ID of the relevant subscriptiong
:param **kwargs: Further parameters for the transpo... |
def _compute_magnitude(self, rup, C):
"""
Compute the first term of the equation described on p. 1144:
``c1 + c2 * (M - 6) + c3 * log(M / 6)``
"""
return C['c1'] + C['c2'] * (rup.mag - 6.0) +\
(C['c3'] * np.log(rup.mag / 6.0)) | Compute the first term of the equation described on p. 1144:
``c1 + c2 * (M - 6) + c3 * log(M / 6)`` |
def write_to_fp(self, fp):
"""Do the TTS API request and write bytes to a file-like object.
Args:
fp (file object): Any file-like object to write the ``mp3`` to.
Raises:
:class:`gTTSError`: When there's an error with the API request.
TypeError: When ``fp`` i... | Do the TTS API request and write bytes to a file-like object.
Args:
fp (file object): Any file-like object to write the ``mp3`` to.
Raises:
:class:`gTTSError`: When there's an error with the API request.
TypeError: When ``fp`` is not a file-like object that takes by... |
def check_input_and_output_numbers(operator, input_count_range=None, output_count_range=None):
'''
Check if the number of input(s)/output(s) is correct
:param operator: A Operator object
:param input_count_range: A list of two integers or an integer. If it's a list the first/second element is the
m... | Check if the number of input(s)/output(s) is correct
:param operator: A Operator object
:param input_count_range: A list of two integers or an integer. If it's a list the first/second element is the
minimal/maximal number of inputs. If it's an integer, it is equivalent to specify that number twice in a lis... |
def add_application(self, application_id, **kwargs):
"""
Add an application to a group.
`application_id` is the name of the application to add. Any
application options can be specified as kwargs.
"""
path = 'group/%s/application' % self.id
data = {'application_i... | Add an application to a group.
`application_id` is the name of the application to add. Any
application options can be specified as kwargs. |
def remove_accessibility_type(self, accessibility_type=None):
"""Removes an accessibility type.
:param accessibility_type: accessibility type to remove
:type accessibility_type: ``osid.type.Type``
:raise: ``NoAccess`` -- ``Metadata.isReadOnly()`` is ``true``
:raise: ``NotFound``... | Removes an accessibility type.
:param accessibility_type: accessibility type to remove
:type accessibility_type: ``osid.type.Type``
:raise: ``NoAccess`` -- ``Metadata.isReadOnly()`` is ``true``
:raise: ``NotFound`` -- acessibility type not found
:raise: ``NullArgument`` -- ``acc... |
def _analyze_ini_file(self, add_header=False):
"""
:returns: same format as super().analyze()
"""
def wrapped(file, filename):
potential_secrets = {}
with self.non_quoted_string_regex():
for value, lineno in IniFileParser(
file... | :returns: same format as super().analyze() |
def export_request_rate_by_interval(
self, parameters, location, custom_headers=None, raw=False, polling=True, **operation_config):
"""Export logs that show Api requests made by this subscription in the
given time window to show throttling activities.
:param parameters: Parameters s... | Export logs that show Api requests made by this subscription in the
given time window to show throttling activities.
:param parameters: Parameters supplied to the LogAnalytics
getRequestRateByInterval Api.
:type parameters:
~azure.mgmt.compute.v2018_04_01.models.RequestRateByI... |
def encrypt_file(cls, key, in_filename, out_filename=None, chunksize=64 * 1024):
""" Encrypts a file using AES (CBC mode) with the
given key.
key:
The encryption key - a string that must be
either 16, 24 or 32 bytes long. Longer keys
a... | Encrypts a file using AES (CBC mode) with the
given key.
key:
The encryption key - a string that must be
either 16, 24 or 32 bytes long. Longer keys
are more secure.
in_filename:
Name of the input file
... |
def format_kinds(raw):
"""Format a string representing the kinds."""
output = ' '.join('{} {}'.format(*kind) for kind in raw if kind)
return output | Format a string representing the kinds. |
def load_contents(self):
"""
Loads contents of Database from a filename database.csv.
"""
with open(self.name + ".csv") as f:
list_of_rows = f.readlines()
list_of_rows = map(
lambda x: x.strip(),
map(
lambda x: x.replace("\... | Loads contents of Database from a filename database.csv. |
def get_last_depth(self, symbol, _type):
"""
获取marketdepth
:param symbol
:param type: 可选值:{ percent10, step0, step1, step2, step3, step4, step5 }
:return:
"""
params = {'symbol': symbol, 'type': _type}
url = u.MARKET_URL + '/market/depth'
def _wr... | 获取marketdepth
:param symbol
:param type: 可选值:{ percent10, step0, step1, step2, step3, step4, step5 }
:return: |
def generate(self, output_dir, work, ngrams, labels, minus_ngrams):
"""Generates HTML reports for each witness to `work`, showing its text
with the n-grams in `ngrams` highlighted.
Any n-grams in `minus_ngrams` have any highlighting of them
(or subsets of them) removed.
:param ... | Generates HTML reports for each witness to `work`, showing its text
with the n-grams in `ngrams` highlighted.
Any n-grams in `minus_ngrams` have any highlighting of them
(or subsets of them) removed.
:param output_dir: directory to write report to
:type output_dir: `str`
... |
def _calculate_refund_amount(self, amount=None):
"""
:rtype: int
:return: amount that can be refunded, in CENTS
"""
eligible_to_refund = self.amount - (self.amount_refunded or 0)
if amount:
amount_to_refund = min(eligible_to_refund, amount)
else:
amount_to_refund = eligible_to_refund
return int(am... | :rtype: int
:return: amount that can be refunded, in CENTS |
def prox_l1(v, alpha):
r"""Compute the proximal operator of the :math:`\ell_1` norm (scalar
shrinkage/soft thresholding)
.. math::
\mathrm{prox}_{\alpha f}(\mathbf{v}) =
\mathcal{S}_{1,\alpha}(\mathbf{v}) = \mathrm{sign}(\mathbf{v})
\odot \max(0, |\mathbf{v}| - \alpha)
where :math:`... | r"""Compute the proximal operator of the :math:`\ell_1` norm (scalar
shrinkage/soft thresholding)
.. math::
\mathrm{prox}_{\alpha f}(\mathbf{v}) =
\mathcal{S}_{1,\alpha}(\mathbf{v}) = \mathrm{sign}(\mathbf{v})
\odot \max(0, |\mathbf{v}| - \alpha)
where :math:`f(\mathbf{x}) = \|\mathbf{x... |
def parse_workflow_call_body(self, i):
"""
Required.
:param i:
:return:
"""
io_map = OrderedDict()
if isinstance(i, wdl_parser.Terminal):
return i.source_string # no io mappings; represents just a blank call
elif isinstance(i, wdl_parser.Ast)... | Required.
:param i:
:return: |
def close(self):
"""Close the plot and release its memory.
"""
from matplotlib.pyplot import close
for ax in self.axes[::-1]:
# avoid matplotlib/matplotlib#9970
ax.set_xscale('linear')
ax.set_yscale('linear')
# clear the axes
ax... | Close the plot and release its memory. |
def register_sizer(self, attr_name, sizedimage_cls):
"""
Register a new SizedImage subclass (`sizedimage_cls`).
To be used via the attribute (`attr_name`).
"""
if attr_name.startswith(
'_'
) or attr_name in self.unallowed_sizer_names:
raise Unallo... | Register a new SizedImage subclass (`sizedimage_cls`).
To be used via the attribute (`attr_name`). |
def distance_restraint_force(self, atoms, distances, strengths):
"""
Parameters
----------
atoms : tuple of tuple of int or str
Pair of atom indices to be restrained, with shape (n, 2),
like ((a1, a2), (a3, a4)). Items can be str compatible with MDTraj DSL.
... | Parameters
----------
atoms : tuple of tuple of int or str
Pair of atom indices to be restrained, with shape (n, 2),
like ((a1, a2), (a3, a4)). Items can be str compatible with MDTraj DSL.
distances : tuple of float
Equilibrium distances for each pair
... |
def point3d(value, lon, lat, depth):
"""
This is used to convert nodes of the form
<hypocenter lon="LON" lat="LAT" depth="DEPTH"/>
:param value: None
:param lon: longitude string
:param lat: latitude string
:returns: a validated triple (lon, lat, depth)
"""
return longitude(lon), la... | This is used to convert nodes of the form
<hypocenter lon="LON" lat="LAT" depth="DEPTH"/>
:param value: None
:param lon: longitude string
:param lat: latitude string
:returns: a validated triple (lon, lat, depth) |
def get_dummy_dynamic_run(nsamples, **kwargs):
"""Generate dummy data for a dynamic nested sampling run.
Loglikelihood values of points are generated from a uniform distribution
in (0, 1), sorted, scaled by logl_range and shifted by logl_start (if it is
not -np.inf). Theta values of each point are each... | Generate dummy data for a dynamic nested sampling run.
Loglikelihood values of points are generated from a uniform distribution
in (0, 1), sorted, scaled by logl_range and shifted by logl_start (if it is
not -np.inf). Theta values of each point are each generated from a uniform
distribution in (0, 1).
... |
def desbloquear_sat(self):
"""Sobrepõe :meth:`~satcfe.base.FuncoesSAT.desbloquear_sat`.
:return: Uma resposta SAT padrão.
:rtype: satcfe.resposta.padrao.RespostaSAT
"""
retorno = super(ClienteSATLocal, self).desbloquear_sat()
return RespostaSAT.desbloquear_sat(retorno) | Sobrepõe :meth:`~satcfe.base.FuncoesSAT.desbloquear_sat`.
:return: Uma resposta SAT padrão.
:rtype: satcfe.resposta.padrao.RespostaSAT |
def create(name, **params):
'''
Function to create device in Server Density. For more info, see the `API
docs`__.
.. __: https://apidocs.serverdensity.com/Inventory/Devices/Creating
CLI Example:
.. code-block:: bash
salt '*' serverdensity_device.create lama
salt '*' serverden... | Function to create device in Server Density. For more info, see the `API
docs`__.
.. __: https://apidocs.serverdensity.com/Inventory/Devices/Creating
CLI Example:
.. code-block:: bash
salt '*' serverdensity_device.create lama
salt '*' serverdensity_device.create rich_lama group=lama_... |
def linear_extrapolation_plot(log_prob_adv_array, y, file_name,
min_epsilon=-10, max_epsilon=10,
num_points=21):
"""Generate linear extrapolation plot.
Args:
log_prob_adv_array: Numpy array containing log probabilities
y: Tf placeholder for th... | Generate linear extrapolation plot.
Args:
log_prob_adv_array: Numpy array containing log probabilities
y: Tf placeholder for the labels
file_name: Plot filename
min_epsilon: Minimum value of epsilon over the interval
max_epsilon: Maximum value of epsilon over the interval
num_poin... |
def gimbal_torque_cmd_report_send(self, target_system, target_component, rl_torque_cmd, el_torque_cmd, az_torque_cmd, force_mavlink1=False):
'''
100 Hz gimbal torque command telemetry
target_system : System ID (uint8_t)
target_component ... | 100 Hz gimbal torque command telemetry
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
rl_torque_cmd : Roll Torque Command (int16_t)
el_torque_cmd : Elevation Torque Command (int16... |
def post_handler_err(self, function_arn, invocation_id, handler_err):
"""
Post the error message from executing the function handler for :code:`function_arn`
with specifid :code:`invocation_id`
:param function_arn: Arn of the Lambda function which has the handler error message.
... | Post the error message from executing the function handler for :code:`function_arn`
with specifid :code:`invocation_id`
:param function_arn: Arn of the Lambda function which has the handler error message.
:type function_arn: string
:param invocation_id: Invocation ID of the work that ... |
def delete_activity(self, activity_id):
"""Deletes the ``Activity`` identified by the given ``Id``.
arg: activity_id (osid.id.Id): the ``Id`` of the ``Activity``
to delete
raise: NotFound - an ``Activity`` was not found identified by
the given ``Id``
... | Deletes the ``Activity`` identified by the given ``Id``.
arg: activity_id (osid.id.Id): the ``Id`` of the ``Activity``
to delete
raise: NotFound - an ``Activity`` was not found identified by
the given ``Id``
raise: NullArgument - ``activity_id`` is ``null``
... |
def getOutputElementCount(self, name):
"""
Returns the size of the output array
"""
if name in ["activeCells", "learnableCells", "sensoryAssociatedCells"]:
return self.cellCount * self.moduleCount
else:
raise Exception("Invalid output name specified: " + name) | Returns the size of the output array |
def _open_interface(self, conn_id, iface, callback):
"""Open an interface on this device
Args:
conn_id (int): the unique identifier for the connection
iface (string): the interface name to open
callback (callback): Callback to be called when this command finishes
... | Open an interface on this device
Args:
conn_id (int): the unique identifier for the connection
iface (string): the interface name to open
callback (callback): Callback to be called when this command finishes
callback(conn_id, adapter_id, success, failure_reas... |
def movies_released_in(self, year):
"""Return list of movies that were released in certain year.
:param year: Release year
:type year: int
:rtype: list[movies.models.Movie]
:return: List of movie instances.
"""
return [movie for movie in self._movie_finder.find_... | Return list of movies that were released in certain year.
:param year: Release year
:type year: int
:rtype: list[movies.models.Movie]
:return: List of movie instances. |
def set_prev_hard(self):
"""
Выставляет параметры твёрдости/мягкости, для предыдущих согласных.
"""
prev = self.get_prev_letter()
if not prev:
return
if not prev.is_consonant():
return
if self.is_softener(prev):
prev.set_hard(Fa... | Выставляет параметры твёрдости/мягкости, для предыдущих согласных. |
def parse_connection_option(
header: str, pos: int, header_name: str
) -> Tuple[ConnectionOption, int]:
"""
Parse a Connection option from ``header`` at the given position.
Return the protocol value and the new position.
Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` on invalid inputs.
... | Parse a Connection option from ``header`` at the given position.
Return the protocol value and the new position.
Raise :exc:`~websockets.exceptions.InvalidHeaderFormat` on invalid inputs. |
def _set_ext_src_vtep_ip_any(self, v, load=False):
"""
Setter method for ext_src_vtep_ip_any, mapped from YANG variable /overlay/access_list/type/vxlan/extended/ext_seq/ext_src_vtep_ip_any (empty)
If this variable is read-only (config: false) in the
source YANG file, then _set_ext_src_vtep_ip_any is con... | Setter method for ext_src_vtep_ip_any, mapped from YANG variable /overlay/access_list/type/vxlan/extended/ext_seq/ext_src_vtep_ip_any (empty)
If this variable is read-only (config: false) in the
source YANG file, then _set_ext_src_vtep_ip_any is considered as a private
method. Backends looking to populate t... |
def _encrypt(data):
"""Equivalent to OpenSSL using 256 bit AES in CBC mode"""
BS = AES.block_size
def pad(s):
n = BS - len(s) % BS
char = chr(n).encode('utf8')
return s + n * char
password = settings.GECKOBOARD_PASSWORD
salt = Random.new().read(BS - len('Salted__'))
key... | Equivalent to OpenSSL using 256 bit AES in CBC mode |
def create(self, server):
"""Create the task on the server"""
if len(self.geometries) == 0:
raise Exception('no geometries')
return server.post(
'task_admin',
self.as_payload(),
replacements={
'slug': self.__challenge__.slug,
... | Create the task on the server |
def _validate_all_tags_are_used(metadata):
"""Ensure all tags are used in some filter."""
tag_names = set([tag_name for tag_name, _ in metadata.tags])
filter_arg_names = set()
for location, _ in metadata.registered_locations:
for filter_info in metadata.get_filter_infos(location):
fo... | Ensure all tags are used in some filter. |
def from_iter(self, iterable):
# type: (Any, Any) -> Any
'''Takes an object and an iterable and produces a new object that is
a copy of the original with data from ``iterable`` reincorporated. It
is intended as the inverse of the ``to_iter`` function. Any state in
``self`` that is not modelled by th... | Takes an object and an iterable and produces a new object that is
a copy of the original with data from ``iterable`` reincorporated. It
is intended as the inverse of the ``to_iter`` function. Any state in
``self`` that is not modelled by the iterable should remain unchanged.
The following equality shou... |
def on_while(self, node): # ('test', 'body', 'orelse')
"""While blocks."""
while self.run(node.test):
self._interrupt = None
for tnode in node.body:
self.run(tnode)
if self._interrupt is not None:
break
if isinsta... | While blocks. |
def _set_packet_error_counters(self, v, load=False):
"""
Setter method for packet_error_counters, mapped from YANG variable /mpls_state/rsvp/statistics/packet_error_counters (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_packet_error_counters is considered a... | Setter method for packet_error_counters, mapped from YANG variable /mpls_state/rsvp/statistics/packet_error_counters (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_packet_error_counters is considered as a private
method. Backends looking to populate this variabl... |
def repr_data_size(size_in_bytes, precision=2): # pragma: no cover
"""Return human readable string represent of a file size. Doesn"t support
size greater than 1EB.
For example:
- 100 bytes => 100 B
- 100,000 bytes => 97.66 KB
- 100,000,000 bytes => 95.37 MB
- 100,000,000,000 bytes => 93.1... | Return human readable string represent of a file size. Doesn"t support
size greater than 1EB.
For example:
- 100 bytes => 100 B
- 100,000 bytes => 97.66 KB
- 100,000,000 bytes => 95.37 MB
- 100,000,000,000 bytes => 93.13 GB
- 100,000,000,000,000 bytes => 90.95 TB
- 100,000,000,000,000,... |
def setLinkQuality(self, EUIadr, LinkQuality):
"""set custom LinkQualityIn for all receiving messages from the specified EUIadr
Args:
EUIadr: a given extended address
LinkQuality: a given custom link quality
link quality/link margin mapping table
... | set custom LinkQualityIn for all receiving messages from the specified EUIadr
Args:
EUIadr: a given extended address
LinkQuality: a given custom link quality
link quality/link margin mapping table
3: 21 - 255 (dB)
... |
def submit(recaptcha_challenge_field,
recaptcha_response_field,
private_key,
remoteip,
use_ssl=False):
"""
Submits a reCAPTCHA request for verification. Returns RecaptchaResponse
for the request
recaptcha_challenge_field -- The value of recaptcha_challenge_fi... | Submits a reCAPTCHA request for verification. Returns RecaptchaResponse
for the request
recaptcha_challenge_field -- The value of recaptcha_challenge_field
from the form
recaptcha_response_field -- The value of recaptcha_response_field
from the form
private_key -- your reCAPTCHA private key
... |
def copy(self):
"""
Return a copy of this object.
"""
self_copy = self.dup()
self_copy._scopes = copy.copy(self._scopes)
return self_copy | Return a copy of this object. |
def get_var(self, name, recurse=True):
"""Return the first var of name ``name`` in the current
scope stack (remember, vars are the ones that parse the
input stream)
:name: The name of the id
:recurse: Whether parent scopes should also be searched (defaults to True)
:retu... | Return the first var of name ``name`` in the current
scope stack (remember, vars are the ones that parse the
input stream)
:name: The name of the id
:recurse: Whether parent scopes should also be searched (defaults to True)
:returns: TODO |
def draw(self, x, y):
"""Places the flattened canvas in NodeBox.
Exports to a temporary PNG file.
Draws the PNG in NodeBox using the image() command.
Removes the temporary file.
"""
try:
from time import time
imp... | Places the flattened canvas in NodeBox.
Exports to a temporary PNG file.
Draws the PNG in NodeBox using the image() command.
Removes the temporary file. |
def normalize_response_value(rv):
""" Normalize the response value into a 3-tuple (rv, status, headers)
:type rv: tuple|*
:returns: tuple(rv, status, headers)
:rtype: tuple(Response|JsonResponse|*, int|None, dict|None)
"""
status = headers = None
if isinstance(rv, tuple):
... | Normalize the response value into a 3-tuple (rv, status, headers)
:type rv: tuple|*
:returns: tuple(rv, status, headers)
:rtype: tuple(Response|JsonResponse|*, int|None, dict|None) |
def match_input_fmt(self, fmt_list):
"""Given a list of Fortran format specifiers, e.g., ['I5', '2X', 'F4.1'],
this function constructs a list of tuples for matching an input
string against those format specifiers."""
rexp_list = []
for fmt in fmt_list:
rexp_list.ext... | Given a list of Fortran format specifiers, e.g., ['I5', '2X', 'F4.1'],
this function constructs a list of tuples for matching an input
string against those format specifiers. |
def delete(self, client=None, reload_data=False):
"""API call: delete the project via a ``DELETE`` request.
See
https://cloud.google.com/resource-manager/reference/rest/v1beta1/projects/delete
This actually changes the status (``lifecycleState``) from ``ACTIVE``
to ``DELETE_RE... | API call: delete the project via a ``DELETE`` request.
See
https://cloud.google.com/resource-manager/reference/rest/v1beta1/projects/delete
This actually changes the status (``lifecycleState``) from ``ACTIVE``
to ``DELETE_REQUESTED``.
Later (it's not specified when), the proje... |
def find_and_reserve_fcp(self, assigner_id):
"""reserve the fcp to assigner_id
The function to reserve a fcp for user
1. Check whether assigner_id has a fcp already
if yes, make the reserve of that record to 1
2. No fcp, then find a fcp and reserve it
fcp will be ret... | reserve the fcp to assigner_id
The function to reserve a fcp for user
1. Check whether assigner_id has a fcp already
if yes, make the reserve of that record to 1
2. No fcp, then find a fcp and reserve it
fcp will be returned, or None indicate no fcp |
def patch_ref(self, sha):
""" Patch reference on the origin master branch
:param sha: Sha to use for the branch
:return: Status of success
:rtype: str or self.ProxyError
"""
uri = "{api}/repos/{origin}/git/refs/heads/{branch}".format(
api=self.github_api_url,... | Patch reference on the origin master branch
:param sha: Sha to use for the branch
:return: Status of success
:rtype: str or self.ProxyError |
def main():
""" Main entry point of the CLI. """
try:
args = sys.argv[1:]
try:
_, args = getopt.getopt(args, MAIN_OPTS, MAIN_LONG_OPTS)
except getopt.GetoptError as e:
error(str(e))
sys.exit(1)
if args[0] == 'prompt':
try:
... | Main entry point of the CLI. |
def _loadConfiguration(self):
"""
Load module configuration files.
:return: <void>
"""
configPath = os.path.join(self.path, "config")
if not os.path.isdir(configPath):
return
config = Config(configPath)
Config.mergeDictionaries(config.getDat... | Load module configuration files.
:return: <void> |
def rm(self, path):
"""Delete file or directory."""
resp = self._sendRequest("DELETE", path)
# By documentation server must return 200 "OK", but I get 204 "No Content".
# Anyway file or directory have been removed.
if not (resp.status_code in (200, 204)):
raise YaDis... | Delete file or directory. |
def _check_status(func, read_exception, *args, **kwargs):
"""
Checks the status of a single component by
calling the func with the args. The func is expected to
return a dict with at least an `available=<bool>` key
value pair
:param func func: The function to call
... | Checks the status of a single component by
calling the func with the args. The func is expected to
return a dict with at least an `available=<bool>` key
value pair
:param func func: The function to call
:param read_exception: If an exception is thrown
should the exc... |
def upper_diag_self_prodx(list_):
"""
upper diagnoal of cartesian product of self and self.
Weird name. fixme
Args:
list_ (list):
Returns:
list:
CommandLine:
python -m utool.util_alg --exec-upper_diag_self_prodx
Example:
>>> # ENABLE_DOCTEST
>>> fr... | upper diagnoal of cartesian product of self and self.
Weird name. fixme
Args:
list_ (list):
Returns:
list:
CommandLine:
python -m utool.util_alg --exec-upper_diag_self_prodx
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>>... |
def get_depth_pmf(self, depth_bins, default_depth=5.0, bootstrap=None):
"""
Returns the depth distribution of the catalogue as a probability mass
function
"""
if len(self.data['depth']) == 0:
# If depth information is missing
return PMF([(1.0, default_dept... | Returns the depth distribution of the catalogue as a probability mass
function |
def authenticate(self):
"""
Handles authentication, and persists the X-APPLE-WEB-KB cookie so that
subsequent logins will not cause additional e-mails from Apple.
"""
logger.info("Authenticating as %s", self.user['apple_id'])
data = dict(self.user)
# We authent... | Handles authentication, and persists the X-APPLE-WEB-KB cookie so that
subsequent logins will not cause additional e-mails from Apple. |
def list_default_storage_policy_of_datastore(datastore, service_instance=None):
'''
Returns a list of datastores assign the the storage policies.
datastore
Name of the datastore to assign.
The datastore needs to be visible to the VMware entity the proxy
points to.
service_insta... | Returns a list of datastores assign the the storage policies.
datastore
Name of the datastore to assign.
The datastore needs to be visible to the VMware entity the proxy
points to.
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
... |
def send_global_velocity(velocity_x, velocity_y, velocity_z, duration):
"""
Move vehicle in direction based on specified velocity vectors.
This uses the SET_POSITION_TARGET_GLOBAL_INT command with type mask enabling only
velocity components
(http://dev.ardupilot.com/wiki/copter-commands-in-guided... | Move vehicle in direction based on specified velocity vectors.
This uses the SET_POSITION_TARGET_GLOBAL_INT command with type mask enabling only
velocity components
(http://dev.ardupilot.com/wiki/copter-commands-in-guided-mode/#set_position_target_global_int).
Note that from AC3.3 the message sh... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.