code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def is_instance_or_subclass(val, class_):
"""Return True if ``val`` is either a subclass or instance of ``class_``."""
try:
return issubclass(val, class_)
except TypeError:
return isinstance(val, class_) | Return True if ``val`` is either a subclass or instance of ``class_``. |
def dict_from_hdf5(dict_like, h5group):
"""
Load a dictionnary-like object from a h5 file group
"""
# Read attributes
for name, value in h5group.attrs.items():
dict_like[name] = value | Load a dictionnary-like object from a h5 file group |
def _get_data(filenames):
"""Read data from file(s) or STDIN.
Args:
filenames (list): List of files to read to get data. If empty or
None, read from STDIN.
"""
if filenames:
data = ""
for filename in filenames:
with open(filename, "rb") as f:
... | Read data from file(s) or STDIN.
Args:
filenames (list): List of files to read to get data. If empty or
None, read from STDIN. |
def convert_dict(d, cls=AttrDict): # not used
'''
recursively convert a normal Mapping `d` and it's values to a specified type
(defaults to AttrDict)
'''
for k, v in d.items():
if isinstance(v, Mapping):
d[k] = convert_dict(v)
elif isinstance(v, list):
for i, ... | recursively convert a normal Mapping `d` and it's values to a specified type
(defaults to AttrDict) |
def get_transformer_choices():
"""
:rtype: list
"""
from luma.emulator.render import transformer
return [fn for fn in dir(transformer) if fn[0:2] != "__"] | :rtype: list |
def JECXZ(cpu, target):
"""
Jumps short if ECX register is 0.
:param cpu: current CPU.
:param target: destination operand.
"""
cpu.PC = Operators.ITEBV(cpu.address_bit_size, cpu.ECX == 0, target.read(), cpu.PC) | Jumps short if ECX register is 0.
:param cpu: current CPU.
:param target: destination operand. |
def _set_secondary_path(self, v, load=False):
"""
Setter method for secondary_path, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/lsp/secondary_path (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_secondary_path is considered as a private
... | Setter method for secondary_path, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/lsp/secondary_path (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_secondary_path is considered as a private
method. Backends looking to populate this variable should... |
def _AddToSingleColumnTable(self, tableName, columnHeading, newValue):
"""
Add an entry to a table containing a single column. Checks existing
table entries to avoid duplicate entries if the given value already
exists in the table.
Parameters
----------
tableName : string
Name of ... | Add an entry to a table containing a single column. Checks existing
table entries to avoid duplicate entries if the given value already
exists in the table.
Parameters
----------
tableName : string
Name of table to add entry to.
columnHeading : string
Name of column heading... |
def get_opcodes(self, script, verify_minimal_data=False, pc=0):
"""
Iterator. Return opcode, data, pc, new_pc at each step
"""
while pc < len(script):
opcode, data, new_pc, is_ok = self.scriptStreamer.get_opcode(
script, pc, verify_minimal_data=verify_minimal_... | Iterator. Return opcode, data, pc, new_pc at each step |
def set_options(
self, time_duration: int = 1, time_reset: int = 2, peak: int = -30
) -> None:
"""Set option parameter for noise sensor."""
self._time_duration = time_duration
self._time_reset = time_reset
self._peak = peak | Set option parameter for noise sensor. |
def to_pngs(pdf_path):
''' Converts a multi-page pdfs to a list of pngs via the `sips` command
:returns: A list of converted pngs
'''
pdf_list = split_pdf(pdf_path)
pngs = []
for pdf in pdf_list:
pngs.append(to_png(pdf))
os.remove(pdf) # Clean up
return pngs | Converts a multi-page pdfs to a list of pngs via the `sips` command
:returns: A list of converted pngs |
def from_bool(value):
'''
Convert zfs bool to python bool
'''
if value in ['on', 'yes']:
value = True
elif value in ['off', 'no']:
value = False
elif value == 'none':
value = None
return value | Convert zfs bool to python bool |
def _verify_password(self, raw_password, hashed_password):
"""
Verifies that a plaintext password matches the hashed version of that
password using the stored passlib password context
"""
PraetorianError.require_condition(
self.pwd_ctx is not None,
"Praeto... | Verifies that a plaintext password matches the hashed version of that
password using the stored passlib password context |
def evaluate_recurrence_coefficients(
distribution,
k_data,
parameters=None,
cache=None,
):
"""
Evaluate three terms recurrence coefficients (TTR).
Args:
distribution (Dist):
Distribution to evaluate.
x_data (numpy.ndarray):
Locations ... | Evaluate three terms recurrence coefficients (TTR).
Args:
distribution (Dist):
Distribution to evaluate.
x_data (numpy.ndarray):
Locations for where evaluate recurrence coefficients for.
parameters (:py:data:typing.Any):
Collection of parameters to overri... |
def _create_authenticator(a_service):
"""Create an instance of :class:`google.auth.tokens.Authenticator`.
Args:
a_service (:class:`endpoints_management.gen.servicemanagement_v1_messages.Service`): a
service instance
"""
if not isinstance(a_service, sm_messages.Service):
raise Valu... | Create an instance of :class:`google.auth.tokens.Authenticator`.
Args:
a_service (:class:`endpoints_management.gen.servicemanagement_v1_messages.Service`): a
service instance |
def set_metadata(self, fp):
"""
Set the XML metadata on a set.
:param file fp: file-like object to read the XML metadata from.
"""
base_url = self._client.get_url('SET', 'GET', 'single', {'id': self.id})
self._manager._metadata.set(base_url, fp)
# reload myself
... | Set the XML metadata on a set.
:param file fp: file-like object to read the XML metadata from. |
def has_netmask(interface_name):
"""
Checks if an interface has a netmask.
:param interface: interface name
:returns: boolean
"""
for interface in interfaces():
if interface["name"] == interface_name:
if interface["netmask"] and len(interface["netmask"]) > 0:
... | Checks if an interface has a netmask.
:param interface: interface name
:returns: boolean |
def bayesianUpperLimit(self, alpha, steps=1.e5, plot=False):
"""
Compute one-sided upper limit using Bayesian Method of Helene.
Several methods of increasing numerical stability have been implemented.
"""
x_dense, y_dense = self.densify()
y_dense -= np.max(y_dense) # Nume... | Compute one-sided upper limit using Bayesian Method of Helene.
Several methods of increasing numerical stability have been implemented. |
def run(self):
""" Runs the given OPF task against the given Model instance """
self._logger.debug("Starting Dummy Model: modelID=%s;" % (self._modelID))
# =========================================================================
# Initialize periodic activities (e.g., for model result updates)
# ... | Runs the given OPF task against the given Model instance |
def Disconnect(self, reason=None, isDead=True):
"""Close the connection with the remote node client."""
self.disconnecting = True
self.expect_verack_next = False
if reason:
logger.debug(f"Disconnecting with reason: {reason}")
self.stop_block_loop()
self.stop_h... | Close the connection with the remote node client. |
def start_tasks(self):
"""
Start however many tasks we can based on our limits and what we have left to finish.
"""
while self.tasks_at_once > len(self.pending_results) and self._has_more_tasks():
task, parent_result = self.tasks.popleft()
self.execute_task(task, ... | Start however many tasks we can based on our limits and what we have left to finish. |
def iter_regions(self):
"""
Return an iterable list of all region files. Use this function if you only
want to loop through each region files once, and do not want to cache the results.
"""
# TODO: Implement BoundingBox
# TODO: Implement sort order
for x,z in self... | Return an iterable list of all region files. Use this function if you only
want to loop through each region files once, and do not want to cache the results. |
def check_ip(self, ip):
"""
Check IP trough the httpBL API
:param ip: ipv4 ip address
:return: httpBL results or None if any error is occurred
"""
self._last_result = None
if is_valid_ipv4(ip):
key = None
if self._use_cache:
... | Check IP trough the httpBL API
:param ip: ipv4 ip address
:return: httpBL results or None if any error is occurred |
def DOM_discardSearchResults(self, searchId):
"""
Function path: DOM.discardSearchResults
Domain: DOM
Method name: discardSearchResults
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'searchId' (type: string) -> Unique search session identifier.
No ret... | Function path: DOM.discardSearchResults
Domain: DOM
Method name: discardSearchResults
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'searchId' (type: string) -> Unique search session identifier.
No return value.
Description: Discards search results ... |
def json_post_required(*decorator_args):
"""View decorator that enforces that the method was called using POST and
contains a field containing a JSON dictionary. This method should
only be used to wrap views and assumes the first argument of the method
being wrapped is a ``request`` object.
.. code... | View decorator that enforces that the method was called using POST and
contains a field containing a JSON dictionary. This method should
only be used to wrap views and assumes the first argument of the method
being wrapped is a ``request`` object.
.. code-block:: python
@json_post_required('da... |
def getTarget(self):
""" Returns the location of the match click target (center by default, but may be offset) """
return self.getCenter().offset(self._target.x, self._target.y) | Returns the location of the match click target (center by default, but may be offset) |
def unlock(self, session=None):
"""Unlock a previously locked server.
:Parameters:
- `session` (optional): a
:class:`~pymongo.client_session.ClientSession`.
.. versionchanged:: 3.6
Added ``session`` parameter.
"""
cmd = SON([("fsyncUnlock", 1)])... | Unlock a previously locked server.
:Parameters:
- `session` (optional): a
:class:`~pymongo.client_session.ClientSession`.
.. versionchanged:: 3.6
Added ``session`` parameter. |
def thermostat_state(self, name):
"""Changes the thermostat state to the one passed as an argument as name
:param name: The name of the thermostat state to change to.
"""
self._validate_thermostat_state_name(name)
id_ = next((key for key in STATES.keys()
if S... | Changes the thermostat state to the one passed as an argument as name
:param name: The name of the thermostat state to change to. |
def stats_keyboard(events, table):
"""Return statistics and collated events for keyboard events."""
if len(events) < 2: return [], []
deltas, prev_dt = [], None
sessions, session = [], None
UNBROKEN_DELTA = datetime.timedelta(seconds=conf.KeyboardSessionMaxDelta)
blank = collections.defaul... | Return statistics and collated events for keyboard events. |
async def handler(self):
'''Handle loop, get and process messages'''
self.ws = await websockets.connect(self.url, ssl=self.ssl)
while self.ws:
message = await self.ws.recv()
for handle in self.on_message:
if asyncio.iscoroutinefunction(handle):
await handle(self, message)
... | Handle loop, get and process messages |
def create(self, from_=None, **kwargs):
"""
Create and send a new outbound message.
Returns :class:`Message` object contains next attributes: 'id', 'href', 'type',
'sessionId', 'bulkId', 'messageId', 'scheduledId'.
:Example:
message = client.messages.create(from_="44762... | Create and send a new outbound message.
Returns :class:`Message` object contains next attributes: 'id', 'href', 'type',
'sessionId', 'bulkId', 'messageId', 'scheduledId'.
:Example:
message = client.messages.create(from_="447624800500", phones="999000001", text="Hello!", lists="1909100"... |
def signal(signal=None):
'''
Signals Apache Solr to start, stop, or restart. Obviously this is only
going to work if the minion resides on the solr host. Additionally Solr
doesn't ship with an init script so one must be created.
signal : str (None)
The command to pass to the apache solr ini... | Signals Apache Solr to start, stop, or restart. Obviously this is only
going to work if the minion resides on the solr host. Additionally Solr
doesn't ship with an init script so one must be created.
signal : str (None)
The command to pass to the apache solr init valid values are 'start',
'... |
def _set_output_arguments(self):
"""Activate output arguments parsing"""
group = self.parser.add_argument_group('output arguments')
group.add_argument('-o', '--output', type=argparse.FileType('w'),
dest='outfile', default=sys.stdout,
help="o... | Activate output arguments parsing |
def find_vext_files(self):
"""
:return: Absolute paths to any provided vext files
"""
packages = self.depends_on("vext")
vext_files = []
for location in [package.get("location") for package in packages]:
if not location:
continue
v... | :return: Absolute paths to any provided vext files |
def push(self, channel_id, data):
"""Push message with POST ``data`` for ``channel_id``
"""
channel_path = self.channel_path(channel_id)
response = requests.post(channel_path, data)
return response.json() | Push message with POST ``data`` for ``channel_id`` |
def fontFamilyIndex(qFont, families):
""" Searches the index of qFont.family in the families list.
If qFont.family() is not in the list, the index of qFont.defaultFamily() is returned.
If that is also not present an error is raised.
"""
try:
return families.index(qFont.family())
... | Searches the index of qFont.family in the families list.
If qFont.family() is not in the list, the index of qFont.defaultFamily() is returned.
If that is also not present an error is raised. |
def _xml_convert(self, element):
"""
convert the xml `element` into the corresponding python object
"""
children = list(element)
if len(children) == 0:
return self._type_convert(element.text)
else:
# if the fist child tag is list-item means all c... | convert the xml `element` into the corresponding python object |
def document(info=None, input=None, output=None):
"""
Add extra information about request handler and its params
"""
def wrapper(func):
if info is not None:
setattr(func, "_swg_info", info)
if input is not None:
setattr(func, "_swg_input", input)
if output... | Add extra information about request handler and its params |
def _process_consensus_mhcii(mhc_file, normal=False):
"""
Process the results from running IEDB MHCII binding predictions using the consensus method into
a pandas dataframe.
:param str mhc_file: Output file containing consensus mhcii:peptide binding predictions
:param bool normal: Is this processin... | Process the results from running IEDB MHCII binding predictions using the consensus method into
a pandas dataframe.
:param str mhc_file: Output file containing consensus mhcii:peptide binding predictions
:param bool normal: Is this processing the results of a normal?
:return: Results in a tabular forma... |
def _request(self, path, method, body=None):
"Base request function"
h = httplib2.Http()
resp, content = h.request(
self.base_url + path,
method,
body = json.dumps(body),
)
if resp['status'] == "200":
return json.loads(content)
... | Base request function |
def read_inifile (self, noexistok=False, typed=False):
"""Open assuming an “ini-file” format and return a generator yielding data
records using either :func:`pwkit.inifile.read_stream` (if *typed* is
false) or :func:`pwkit.tinifile.read_stream` (if it’s true). The
latter version is desig... | Open assuming an “ini-file” format and return a generator yielding data
records using either :func:`pwkit.inifile.read_stream` (if *typed* is
false) or :func:`pwkit.tinifile.read_stream` (if it’s true). The
latter version is designed to work with numerical data using the
:mod:`pwkit.msmt... |
def add_device(self, device: Union[DeviceType, str]) -> None:
"""Add the given |Node| or |Element| object to the actual
|Nodes| or |Elements| object.
You can pass either a string or a device:
>>> from hydpy import Nodes
>>> nodes = Nodes()
>>> nodes.add_device('old_node... | Add the given |Node| or |Element| object to the actual
|Nodes| or |Elements| object.
You can pass either a string or a device:
>>> from hydpy import Nodes
>>> nodes = Nodes()
>>> nodes.add_device('old_node')
>>> nodes
Nodes("old_node")
>>> nodes.add_devi... |
def planner(self, *, resource=''):
""" Get an instance to read information from Microsoft planner """
if not isinstance(self.protocol, MSGraphProtocol):
# TODO: Custom protocol accessing OneDrive/Sharepoint Api fails here
raise RuntimeError(
'planner api only wor... | Get an instance to read information from Microsoft planner |
def from_Track(track):
"""Process a Track object and return the LilyPond equivalent in a string."""
# Throw exception
if not hasattr(track, 'bars'):
return False
lastkey = Key('C')
lasttime = (4, 4)
# Handle the Bars:
result = ''
for bar in track.bars:
if lastkey != bar.... | Process a Track object and return the LilyPond equivalent in a string. |
def folder_shared_message(self, request, user, folder):
"""
Send messages.success message after successful share.
"""
messages.success(request, _("Folder {} is now shared with {}".format(folder, user))) | Send messages.success message after successful share. |
def forward(self, inputs, label, begin_state, sampled_values): # pylint: disable=arguments-differ
"""Defines the forward computation.
Parameters
-----------
inputs : NDArray
input tensor with shape `(sequence_length, batch_size)`
when `layout` is "TNC".
b... | Defines the forward computation.
Parameters
-----------
inputs : NDArray
input tensor with shape `(sequence_length, batch_size)`
when `layout` is "TNC".
begin_state : list
initial recurrent state tensor with length equals to num_layers*2.
... |
def exec_rabbitmqctl_list(self, resources, args=[],
rabbitmq_opts=['-q', '--no-table-headers']):
"""
Execute a ``rabbitmqctl`` command to list the given resources.
:param resources: the resources to list, e.g. ``'vhosts'``
:param args: a list of args for th... | Execute a ``rabbitmqctl`` command to list the given resources.
:param resources: the resources to list, e.g. ``'vhosts'``
:param args: a list of args for the command
:param rabbitmqctl_opts:
a list of extra options to pass to ``rabbitmqctl``
:returns: a tuple of the command ... |
def display(table, limit=0, vrepr=None, index_header=None, caption=None,
tr_style=None, td_styles=None, encoding=None, truncate=None,
epilogue=None):
"""
Display a table inline within an IPython notebook.
"""
from IPython.core.display import display_html
html = _display_htm... | Display a table inline within an IPython notebook. |
def is_causal(self):
"""
Tests whether all filters in the list are causal (i.e., no future-data
delay in positive ``z`` exponents). Non-linear filters are seem as causal
by default. CascadeFilter and ParallelFilter are causal if all the
filters they group are causal.
"""
return all(filt.is_... | Tests whether all filters in the list are causal (i.e., no future-data
delay in positive ``z`` exponents). Non-linear filters are seem as causal
by default. CascadeFilter and ParallelFilter are causal if all the
filters they group are causal. |
def item_straat_adapter(obj, request):
"""
Adapter for rendering an object of
:class:`crabpy.gateway.crab.Straat` to json.
"""
return {
'id': obj.id,
'label': obj.label,
'namen': obj.namen,
'status': {
'id': obj.status.id,
'naam': obj.status.na... | Adapter for rendering an object of
:class:`crabpy.gateway.crab.Straat` to json. |
def get_help(command):
"""
Get the Cmd help function from the click command
:param command: The click Command object
:return: the help_* method for Cmd
:rtype: function
"""
assert isinstance(command, click.Command)
def help_(self): # pylint: disable=unused-argument
extra = {}
... | Get the Cmd help function from the click command
:param command: The click Command object
:return: the help_* method for Cmd
:rtype: function |
def extract_element_internationalized_comment(element):
""" Extracts the xib element's comment, if the element has been internationalized.
Args:
element (element): The element from which to extract the comment.
Returns:
The element's internationalized comment, None if it does not exist, or... | Extracts the xib element's comment, if the element has been internationalized.
Args:
element (element): The element from which to extract the comment.
Returns:
The element's internationalized comment, None if it does not exist, or hasn't been internationalized (according
to the JTLocal... |
def get_value(self, default=None):
"""Get selection from widget.
Parameters
----------
default : str
str for use by widget
Returns
-------
str
selected item from the combobox
"""
if default is None:
default = ... | Get selection from widget.
Parameters
----------
default : str
str for use by widget
Returns
-------
str
selected item from the combobox |
def from_week(cls, year, iso_week):
"""
Create ``daterange`` based on a year and an ISO week
:param year: Year as an integer
:param iso_week: ISO week number
:return: A new ``daterange`` for the given week
.. versionadded:: 0.4.0
"""
first_day = date_fr... | Create ``daterange`` based on a year and an ISO week
:param year: Year as an integer
:param iso_week: ISO week number
:return: A new ``daterange`` for the given week
.. versionadded:: 0.4.0 |
def parse_color(color):
'''Return the RGB 0-255 representation of the current string
passed.
It first tries to match the string with DVI color names.
'''
# Let's parse the color string
if isinstance(color, str):
# Try dvi names
try:
col = get(color)
exc... | Return the RGB 0-255 representation of the current string
passed.
It first tries to match the string with DVI color names. |
def setup_arrow_buttons(self):
"""
Setup the up and down arrow buttons that are placed at the top and
bottom of the scrollarea.
"""
# Get the height of the up/down arrow of the default vertical
# scrollbar :
vsb = self.scrollarea.verticalScrollBar()
style ... | Setup the up and down arrow buttons that are placed at the top and
bottom of the scrollarea. |
def unwrap(self, message, signature):
"""
NTLM GSSUnwrap()
:param message: The message to be decrypted
:return: The decrypted message
"""
plain_text = _Ntlm2Session.decrypt(self, message)
_Ntlm2Session.verify(self, plain_text, signature)
return plain_text | NTLM GSSUnwrap()
:param message: The message to be decrypted
:return: The decrypted message |
def base_url(self, url):
"""Return url without querystring or fragment"""
parts = list(self.parse_url(url))
parts[4:] = ['' for i in parts[4:]]
return urlunparse(parts) | Return url without querystring or fragment |
def delete(self, port, qos_policy=None):
"""Remove QoS rules from port.
:param port: port object.
:param qos_policy: the QoS policy to be removed from port.
"""
LOG.info("Deleting QoS policy %(qos_policy)s on port %(port)s",
dict(qos_policy=qos_policy, port=port... | Remove QoS rules from port.
:param port: port object.
:param qos_policy: the QoS policy to be removed from port. |
def has_parent_books(self, book_id):
"""Tests if the ``Book`` has any parents.
arg: book_id (osid.id.Id): a book ``Id``
return: (boolean) - ``true`` if the book has parents, f ``alse``
otherwise
raise: NotFound - ``book_id`` is not found
raise: NullArgument ... | Tests if the ``Book`` has any parents.
arg: book_id (osid.id.Id): a book ``Id``
return: (boolean) - ``true`` if the book has parents, f ``alse``
otherwise
raise: NotFound - ``book_id`` is not found
raise: NullArgument - ``book_id`` is ``null``
raise: Operat... |
def get_response(response: Dict[str, Any]) -> JSONRPCResponse:
"""
Converts a deserialized response into a JSONRPCResponse object.
The dictionary be either an error or success response, never a notification.
Args:
response: Deserialized response dictionary. We can assume the response is valid
... | Converts a deserialized response into a JSONRPCResponse object.
The dictionary be either an error or success response, never a notification.
Args:
response: Deserialized response dictionary. We can assume the response is valid
JSON-RPC here, since it passed the jsonschema validation. |
def _convert_num(self, sign):
"""
Converts number registered in get_number_from_sign.
input = ["a2", "☉", "be3"]
output = ["a₂", "☉", "be₃"]
:param sign: string
:return sign: string
"""
# Check if there's a number at the end
new_sign, num = self.... | Converts number registered in get_number_from_sign.
input = ["a2", "☉", "be3"]
output = ["a₂", "☉", "be₃"]
:param sign: string
:return sign: string |
def _start(self, my_task, force=False):
"""Returns False when successfully fired, True otherwise"""
# Deserialize async call if necessary
if not hasattr(my_task, 'async_call') and \
my_task._get_internal_data('task_id') is not None:
task_id = my_task._get_internal_da... | Returns False when successfully fired, True otherwise |
def Parse(self, stat, file_object, knowledge_base):
"""Parse the netgroup file and return User objects.
Lines are of the form:
group1 (-,user1,) (-,user2,) (-,user3,)
Groups are ignored, we return users in lines that match the filter regexes,
or all users in the file if no filters are specified.... | Parse the netgroup file and return User objects.
Lines are of the form:
group1 (-,user1,) (-,user2,) (-,user3,)
Groups are ignored, we return users in lines that match the filter regexes,
or all users in the file if no filters are specified.
We assume usernames are in the default regex format s... |
def get_shared_files_from_shake(self,
shake_id=None,
before=None,
after=None):
"""
Returns a list of SharedFile objects from a particular shake.
Args:
shake_id (int): Shake fr... | Returns a list of SharedFile objects from a particular shake.
Args:
shake_id (int): Shake from which to get a list of SharedFiles
before (str): get 10 SharedFile objects before (but not including)
the SharedFile given by `before` for the given Shake.
after (s... |
def assign_force_field(ampal_obj, ff):
"""Assigns force field parameters to Atoms in the AMPAL object.
Parameters
----------
ampal_obj : AMPAL Object
Any AMPAL object with a `get_atoms` method.
ff: BuffForceField
The force field to be used for scoring.
"""
if hasattr(ampal_o... | Assigns force field parameters to Atoms in the AMPAL object.
Parameters
----------
ampal_obj : AMPAL Object
Any AMPAL object with a `get_atoms` method.
ff: BuffForceField
The force field to be used for scoring. |
def show_content(self, with_content=False):
"""Checks if the state is a library with the `show_content` flag set
:param with_content: If this parameter is `True`, the method return only True if the library represents a
ContainerState
:return: Whether the content of a library state is ... | Checks if the state is a library with the `show_content` flag set
:param with_content: If this parameter is `True`, the method return only True if the library represents a
ContainerState
:return: Whether the content of a library state is shown |
def setup_cmd_parser(cls):
"""Returns the GitLab argument parser."""
parser = BackendCommandArgumentParser(cls.BACKEND.CATEGORIES,
from_date=True,
token_auth=True,
a... | Returns the GitLab argument parser. |
def smoother(self):
"""Backward recursion: compute mean/variance of marginal smoother.
Performs the filter step in a preliminary step if needed.
"""
if not self.filt:
self.filter()
self.smth = [self.filt[-1]]
for t, f in reversed(list(enumerate(self.filt[:-1... | Backward recursion: compute mean/variance of marginal smoother.
Performs the filter step in a preliminary step if needed. |
def memoize(f):
"""
A decorator that memoizes a function result based on its parameters. For example, this can be
used in place of lazy initialization. If the decorating function is invoked by multiple
threads, the decorated function may be called more than once with the same arguments.
"""
# TO... | A decorator that memoizes a function result based on its parameters. For example, this can be
used in place of lazy initialization. If the decorating function is invoked by multiple
threads, the decorated function may be called more than once with the same arguments. |
def construct_from(cls, values, **kwargs):
"""Used to create a new object from an HTTP response"""
instance = cls(values.get(cls.ID_ATTR), **kwargs)
instance.refresh_from(values)
return instance | Used to create a new object from an HTTP response |
def tokens(self):
"""Return a list of token Spans for this sentence."""
spans = self.word_tokenizer.span_tokenize(self.text)
toks = [Token(
text=self.text[span[0]:span[1]],
start=span[0] + self.start,
end=span[1] + self.start,
lexicon=self.lexicon
... | Return a list of token Spans for this sentence. |
def patch_docs(subclass, superclass):
"""
Apply the documentation from ``superclass`` to ``subclass`` by filling
in all overridden member function docstrings with those from the
parent class
"""
funcs0 = inspect.getmembers(subclass, predicate=inspect.ismethod)
funcs1 = inspect.getmembers(sup... | Apply the documentation from ``superclass`` to ``subclass`` by filling
in all overridden member function docstrings with those from the
parent class |
def setupModule(
self):
"""
*The setupModule method*
**Return:**
- ``log`` -- a logger
- ``dbConn`` -- a database connection to a test database (details from yaml settings file)
- ``pathToInputDir`` -- path to modules own test input directory
... | *The setupModule method*
**Return:**
- ``log`` -- a logger
- ``dbConn`` -- a database connection to a test database (details from yaml settings file)
- ``pathToInputDir`` -- path to modules own test input directory
- ``pathToOutputDir`` -- path to modules own tes... |
def find_domain(session, name):
"""Find a domain.
Find a domain by its domain name using the given `session`.
When the domain does not exist the function will
return `None`.
:param session: database session
:param name: name of the domain to find
:returns: a domain object; `None` when the... | Find a domain.
Find a domain by its domain name using the given `session`.
When the domain does not exist the function will
return `None`.
:param session: database session
:param name: name of the domain to find
:returns: a domain object; `None` when the domain
does not exist |
def matches_ordering(self, other):
"""
Compares the magnetic orderings of one structure with another.
:param other: Structure
:return (bool):
"""
a = CollinearMagneticStructureAnalyzer(
self.structure, overwrite_magmom_mode="normalize"
).get_structure... | Compares the magnetic orderings of one structure with another.
:param other: Structure
:return (bool): |
def run(self):
'''
Bind the pub and pull sockets for events
'''
salt.utils.process.appendproctitle(self.__class__.__name__)
self.io_loop = tornado.ioloop.IOLoop()
with salt.utils.asynchronous.current_ioloop(self.io_loop):
if self.opts['ipc_mode'] == 'tcp':
... | Bind the pub and pull sockets for events |
def _find_calls(self, ast_tree, called_module, called_func):
'''
scan the abstract source tree looking for possible ways to call the called_module
and called_func
since -- 7-2-12 -- Jay
example --
# import the module a couple ways:
import pout
... | scan the abstract source tree looking for possible ways to call the called_module
and called_func
since -- 7-2-12 -- Jay
example --
# import the module a couple ways:
import pout
from pout import v
from pout import v as voom
import p... |
def _set_ieee_bpdu(self, v, load=False):
"""
Setter method for ieee_bpdu, mapped from YANG variable /rbridge_id/spanning_tree/ieee_bpdu (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_ieee_bpdu is considered as a private
method. Backends looking to popula... | Setter method for ieee_bpdu, mapped from YANG variable /rbridge_id/spanning_tree/ieee_bpdu (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_ieee_bpdu is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj... |
def load_path(obj, file_type=None, **kwargs):
"""
Load a file to a Path object.
Parameters
-----------
obj : One of the following:
- Path, Path2D, or Path3D objects
- open file object (dxf or svg)
- file name (dxf or svg)
- shapely.geometry.Polygon
- sha... | Load a file to a Path object.
Parameters
-----------
obj : One of the following:
- Path, Path2D, or Path3D objects
- open file object (dxf or svg)
- file name (dxf or svg)
- shapely.geometry.Polygon
- shapely.geometry.MultiLineString
- dict with kwargs ... |
def create_key(key_type='RSA',
key_length=1024,
name_real='Autogenerated Key',
name_comment='Generated by SaltStack',
name_email=None,
subkey_type=None,
subkey_length=None,
expire_date=None,
use_passp... | Create a key in the GPG keychain
.. note::
GPG key generation requires *a lot* of entropy and randomness.
Difficult to do over a remote connection, consider having
another process available which is generating randomness for
the machine. Also especially difficult on virtual machin... |
def compose_mbox(projects):
""" Compose projects.json only for mbox, but using the mailing_lists lists
change: 'https://dev.eclipse.org/mailman/listinfo/emft-dev'
to: 'emfg-dev /home/bitergia/mboxes/emft-dev.mbox/emft-dev.mbox
:param projects: projects.json
:return: projects.json with mbox
"""... | Compose projects.json only for mbox, but using the mailing_lists lists
change: 'https://dev.eclipse.org/mailman/listinfo/emft-dev'
to: 'emfg-dev /home/bitergia/mboxes/emft-dev.mbox/emft-dev.mbox
:param projects: projects.json
:return: projects.json with mbox |
def ma_bias_ratio(self, day1, day2):
"""Calculate moving average bias ratio"""
data1 = self.moving_average(self.price, day1)
data2 = self.moving_average(self.price, day2)
result = [data1[-i] - data2[-i] for i in range(1, min(len(data1), len(data2)) + 1)]
return result[::-1] | Calculate moving average bias ratio |
def recover(y):
""" given a value y, recover the preimage x """
p = (y*y - 1) * inverse(D*y*y + 1)
x = powmod(p, (PRIME+3) // 8, PRIME)
if (x*x - p) % PRIME != 0:
i = powmod(2, (PRIME-1) // 4, PRIME)
x = (x*i) % PRIME
if x % 2 != 0:
x = PRIME - x
return x | given a value y, recover the preimage x |
def update_wsnum_in_files(self, vernum):
"""
With the given version number ```vernum```,
update the source's version number, and replace in the file hashmap.
the version number is in the CHECKSUMS file.
:param vernum:
:return:
"""
self.version_num = vernu... | With the given version number ```vernum```,
update the source's version number, and replace in the file hashmap.
the version number is in the CHECKSUMS file.
:param vernum:
:return: |
def integrate(self, fluxunits='photlam'):
"""Integrate the flux in given unit.
Integration is done using :meth:`~Integrator.trapezoidIntegration`
with ``x=wave`` and ``y=flux``, where flux has been
convert to given unit first.
.. math::
\\textnormal{result} = \\int... | Integrate the flux in given unit.
Integration is done using :meth:`~Integrator.trapezoidIntegration`
with ``x=wave`` and ``y=flux``, where flux has been
convert to given unit first.
.. math::
\\textnormal{result} = \\int F_{\\lambda} d\\lambda
Parameters
-... |
def assign_bins(x, breaks, weight=None, pad=False, closed='right'):
"""
Assign value in x to bins demacated by the break points
Parameters
----------
x : array_like
Values to be binned.
breaks : array_like
Sequence of break points.
weight : array_like
Weight of each ... | Assign value in x to bins demacated by the break points
Parameters
----------
x : array_like
Values to be binned.
breaks : array_like
Sequence of break points.
weight : array_like
Weight of each value in `x`. Used in creating the frequency
table. If `None`, then each... |
def nodes(self):
"""Set of all currently connected servers.
.. warning:: When connected to a replica set the value of :attr:`nodes`
can change over time as :class:`MongoClient`'s view of the replica
set changes. :attr:`nodes` can also be an empty set when
:class:`MongoClie... | Set of all currently connected servers.
.. warning:: When connected to a replica set the value of :attr:`nodes`
can change over time as :class:`MongoClient`'s view of the replica
set changes. :attr:`nodes` can also be an empty set when
:class:`MongoClient` is first instantiated an... |
def run(self, *args):
"""
You can choose whether to use lock method when running threads.
"""
if self.running:
return self
self._mut_finished(False) # in case of recovery from a disaster.
self._mut_running(True)
stream = self.target(*args)
... | You can choose whether to use lock method when running threads. |
def convert_squeeze(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert squeeze operation.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: diction... | Convert squeeze operation.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
weights: pytorch state_dict
names: use short names for... |
def symlinks(self):
"""Known symlinks of the block device."""
if not self._P.Block.Symlinks:
return []
return [decode_ay(path) for path in self._P.Block.Symlinks] | Known symlinks of the block device. |
def remote(self):
"""
Return the remote for this partition
:return:
"""
from ambry.exc import NotFoundError
ds = self.dataset
if 'remote_name' not in ds.data:
raise NotFoundError('Could not determine remote for partition: {}'.format(self.identity.f... | Return the remote for this partition
:return: |
def run(self):
self._scheduler_thread.start()
self.irc_bot.create_connection()
self.irc_bot.add_signal_handlers()
event_loop = asyncio.get_event_loop()
"""
handle_close = _handle_close(messaging,
event_loop)
signal.signal(sign... | handle_close = _handle_close(messaging,
event_loop)
signal.signal(signal.SIGINT, handle_close)
signal.signal(signal.SIGTERM, handle_close) |
def close(self):
"""If a connection is open, close its transport."""
if self._local.conn:
self._local.conn.transport.close()
self._local.conn = None | If a connection is open, close its transport. |
def list_dvportgroups(dvs=None, portgroup_names=None, service_instance=None):
'''
Returns a list of distributed virtual switch portgroups.
The list can be filtered by the portgroup names or by the DVS.
dvs
Name of the DVS containing the portgroups.
Default value is None.
portgroup_... | Returns a list of distributed virtual switch portgroups.
The list can be filtered by the portgroup names or by the DVS.
dvs
Name of the DVS containing the portgroups.
Default value is None.
portgroup_names
List of portgroup names to look for. If None, all portgroups are
ret... |
def output_aliases(aliases):
"""Display git aliases"""
for alias in aliases:
cmd = '!legit ' + alias
click.echo(columns([colored.yellow('git ' + alias), 20], [cmd, None])) | Display git aliases |
def add_cluster(self, info):
""" Handles adding a Cluster to the main graph. """
if not info.initialized:
return
graph = self._request_graph(info.ui.control)
if graph is not None:
cluster = Cluster()#root=graph, parent=graph)
retval = cluster.edit_t... | Handles adding a Cluster to the main graph. |
def decode(image, timeout=None, gap_size=None, shrink=1, shape=None,
deviation=None, threshold=None, min_edge=None, max_edge=None,
corrections=None, max_count=None):
"""Decodes datamatrix barcodes in `image`.
Args:
image: `numpy.ndarray`, `PIL.Image` or tuple (pixels, width, heigh... | Decodes datamatrix barcodes in `image`.
Args:
image: `numpy.ndarray`, `PIL.Image` or tuple (pixels, width, height)
timeout (int): milliseconds
gap_size (int):
shrink (int):
shape (int):
deviation (int):
threshold (int):
min_edge (int):
max_edg... |
def filter_search(self, search):
"""Filter given search by the filter parameter given in request.
:param search: ElasticSearch query object
"""
builder = QueryBuilder(
self.filtering_fields,
self.filtering_map,
self
)
search, unmatche... | Filter given search by the filter parameter given in request.
:param search: ElasticSearch query object |
def copy_neg(self):
""" Return a copy of self with the opposite sign bit.
Unlike -self, this does not make use of the context: the result
has the same precision as the original.
"""
result = mpfr.Mpfr_t.__new__(BigFloat)
mpfr.mpfr_init2(result, self.precision)
... | Return a copy of self with the opposite sign bit.
Unlike -self, this does not make use of the context: the result
has the same precision as the original. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.