code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def take(self, indices, axis=0, convert=None, is_copy=True, **kwargs):
"""
Return the elements in the given *positional* indices along an axis.
This means that we are not indexing according to actual values in
the index attribute of the object. We are indexing according to the
a... | Return the elements in the given *positional* indices along an axis.
This means that we are not indexing according to actual values in
the index attribute of the object. We are indexing according to the
actual position of the element in the object.
Parameters
----------
... |
def update(context, id, etag, name, team_id, data, active):
"""update(context, id, etag, name, team_id, data, active)
Update a Feeder.
>>> dcictl feeder-update [OPTIONS]
:param string id: ID of the feeder [required]
:param string etag: Entity tag of the feeder resource [required]
:param strin... | update(context, id, etag, name, team_id, data, active)
Update a Feeder.
>>> dcictl feeder-update [OPTIONS]
:param string id: ID of the feeder [required]
:param string etag: Entity tag of the feeder resource [required]
:param string name: Name of the feeder
:param string team_id: ID of the tea... |
def process_win_streak(data):
"""
Convert "+++"/"---" formatted win/loss streak column into a +/- integer column
"""
#only do this if there are non-NANs in the column
if data['Streak'].count()>0:
data['Streak2'] = data['Streak'].str.len()
data.loc[data['Streak'].str[0]=='-','Streak2'... | Convert "+++"/"---" formatted win/loss streak column into a +/- integer column |
def split_resource_path(resource):
"""Split a path into segments and perform a sanity check. If it detects
'..' in the path it will raise a `TemplateNotFound` error.
"""
pieces = []
for piece in resource.split('/'):
if path.sep in piece \
or (path.altsep and path.altsep in piece)... | Split a path into segments and perform a sanity check. If it detects
'..' in the path it will raise a `TemplateNotFound` error. |
def convert_to_float_list(value):
""" Converts a comma separate string to a list
:param value:
the format must be 1.2,-3.5 (commas with no space)
:type value:
String
:returns:
List
:example:
>>> convert_to_integer_list('003,003,004,004')
[1.2, -3.5]
""... | Converts a comma separate string to a list
:param value:
the format must be 1.2,-3.5 (commas with no space)
:type value:
String
:returns:
List
:example:
>>> convert_to_integer_list('003,003,004,004')
[1.2, -3.5] |
def pospawn(self, pawn):
"""Position a :class:`Pawn` that is my child so as to reflect how far
its :class:`Thing` has gone along my :class:`Portal`.
"""
if self._turn < pawn.thing['arrival_time']:
# It's weird that the pawn is getting placed in me, but
# I'll do ... | Position a :class:`Pawn` that is my child so as to reflect how far
its :class:`Thing` has gone along my :class:`Portal`. |
def get_cli_profile():
"""Return a CLI profile class.
.. versionadded:: 1.1.6
:return: A CLI Profile
:rtype: azure.cli.core._profile.Profile
:raises: ImportError if azure-cli-core package is not available
"""
try:
from azure.cli.core._profile import Profile
from azure.cli.... | Return a CLI profile class.
.. versionadded:: 1.1.6
:return: A CLI Profile
:rtype: azure.cli.core._profile.Profile
:raises: ImportError if azure-cli-core package is not available |
def is_float(value, min=None, max=None):
"""
A check that tests that a given value is a float
(an integer will be accepted), and optionally - that it is between bounds.
If the value is a string, then the conversion is done - if possible.
Otherwise a VdtError is raised.
This can accept negative... | A check that tests that a given value is a float
(an integer will be accepted), and optionally - that it is between bounds.
If the value is a string, then the conversion is done - if possible.
Otherwise a VdtError is raised.
This can accept negative values.
>>> vtor = Validator()
>>> vtor.che... |
def update_cache(force=False, cache_file=None):
"""
Load a build cache, updating it if necessary.
A cache is considered outdated if any of its inputs have changed.
Arguments
force -- Consider a cache outdated regardless of whether its inputs have
been modified.
"""
if not cach... | Load a build cache, updating it if necessary.
A cache is considered outdated if any of its inputs have changed.
Arguments
force -- Consider a cache outdated regardless of whether its inputs have
been modified. |
def create_hotkey(self, folder, description, modifiers, key, contents):
"""
Create a text hotkey
Usage: C{engine.create_hotkey(folder, description, modifiers, key, contents)}
When the given hotkey is pressed, it will be replaced with the given
text. Modifiers mu... | Create a text hotkey
Usage: C{engine.create_hotkey(folder, description, modifiers, key, contents)}
When the given hotkey is pressed, it will be replaced with the given
text. Modifiers must be given as a list of strings, with the following
values permitted:
... |
def make_desktop_entry(d):
"""
Create a desktop entry that conforms to the format of the Desktop Entry
Specification by freedesktop.org. See:
http://freedesktop.org/Standards/desktop-entry-spec
These should work for both KDE and Gnome2
An entry is a .desktop file that includes the appl... | Create a desktop entry that conforms to the format of the Desktop Entry
Specification by freedesktop.org. See:
http://freedesktop.org/Standards/desktop-entry-spec
These should work for both KDE and Gnome2
An entry is a .desktop file that includes the application's type,
executable, name, e... |
def pt_shift(pt=(0.0, 0.0), shift=[0.0, 0.0]):
'''Return given point shifted in N dimensions.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for ... | Return given point shifted in N dimensions. |
def create_alter():
""" Create the grammar for the 'alter' statement """
alter = upkey("alter").setResultsName("action")
prim_or_star = primitive | "*"
set_throughput = (
Suppress(upkey("set"))
+ Optional(Suppress(upkey("index")) + var.setResultsName("index"))
+ create_throughpu... | Create the grammar for the 'alter' statement |
def groupby(df, *, group_cols: Union[str, List[str]],
aggregations: Dict[str, Union[str, List[str]]]):
"""
Aggregate values by groups.
---
### Parameters
*mandatory :*
- `group_cols` (*list*): list of columns used to group data
- `aggregations` (*dict*): dictionnary of values ... | Aggregate values by groups.
---
### Parameters
*mandatory :*
- `group_cols` (*list*): list of columns used to group data
- `aggregations` (*dict*): dictionnary of values columns to group as keys and aggregation
function to use as values (See the [list of aggregation functions](
https:... |
def set_callbacks(self, **kwargs):
''' Set callbacks for input events '''
for name in self.SUPPORTED_CALLBACKS:
func = kwargs.get(name, getattr(self, name))
setattr(self, name, func) | Set callbacks for input events |
def p_user_add_link(self):
'''
user add link.
'''
if self.check_post_role()['ADD']:
pass
else:
return False
post_data = self.get_post_data()
post_data['user_name'] = self.get_current_user()
cur_uid = tools.get_uudd(2)
whil... | user add link. |
def build_query(self, **filters):
"""
Creates a dict of dictionaries suitable for passing to the SearchQuerySet `facet`,
`date_facet` or `query_facet` method. All key word arguments should be wrapped in a list.
:param view: API View
:param dict[str, list[str]] filters: is an ex... | Creates a dict of dictionaries suitable for passing to the SearchQuerySet `facet`,
`date_facet` or `query_facet` method. All key word arguments should be wrapped in a list.
:param view: API View
:param dict[str, list[str]] filters: is an expanded QueryDict or a mapping
of keys to a lis... |
def _get(self, action, show, proxy, timeout):
"""
make HTTP request and cache response
"""
silent = self.flags['silent']
if action in self.cache:
if action != 'imageinfo' and action != 'labels':
utils.stderr("+ %s results in cache" % action, silent)
... | make HTTP request and cache response |
def keypoint_resize_random_crop(image, annos, mask=None, size=(368, 368)):
"""Reszie the image to make either its width or height equals to the given sizes.
Then randomly crop image without influence scales.
Resize the image match with the minimum size before cropping, this API will change the zoom scale of... | Reszie the image to make either its width or height equals to the given sizes.
Then randomly crop image without influence scales.
Resize the image match with the minimum size before cropping, this API will change the zoom scale of object.
Parameters
-----------
image : 3 channel image
The g... |
def _argsort_and_resolve_ties(time, random_state):
"""Like numpy.argsort, but resolves ties uniformly at random"""
n_samples = len(time)
order = numpy.argsort(time, kind="mergesort")
i = 0
while i < n_samples - 1:
inext = i + 1
while inext < n_samples and... | Like numpy.argsort, but resolves ties uniformly at random |
def minmax(self, minimum=None, maximum=None):
"""Min/Max
Sets or gets the minimum and maximum number of items for the Array
Arguments
minimum {uint} -- The minimum value
maximum {uint} -- The maximum value
Raises:
ValueError
Returns:
None
"""
# If neither minimum or maximum is set, this i... | Min/Max
Sets or gets the minimum and maximum number of items for the Array
Arguments
minimum {uint} -- The minimum value
maximum {uint} -- The maximum value
Raises:
ValueError
Returns:
None |
def get_composition_metadata(self):
"""Gets the metadata for linking this asset to a composition.
return: (osid.Metadata) - metadata for the composition
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.resource.ResourceForm.ge... | Gets the metadata for linking this asset to a composition.
return: (osid.Metadata) - metadata for the composition
*compliance: mandatory -- This method must be implemented.* |
def close(self):
"""Immediately close all connections and stop workers."""
if not self.is_running:
return
self._state = CLOSED
self.logger.debug('closing connection(s)')
while True:
try:
conn = self._connections.get(block=False)
... | Immediately close all connections and stop workers. |
def start_playing(self, on_exit, args):
"""
Runs the given args in subprocess.Popen, and then calls the function
on_exit when the subprocess completes.
on_exit is a callable object, and args is a lists/tuple of args
that would give to subprocess.Popen.
"""
# log.d... | Runs the given args in subprocess.Popen, and then calls the function
on_exit when the subprocess completes.
on_exit is a callable object, and args is a lists/tuple of args
that would give to subprocess.Popen. |
def _write_packet(self, final):
""" Writes single TDS packet into underlying transport.
Data for the packet is taken from internal buffer.
:param final: True means this is the final packet in substream.
"""
status = 1 if final else 0
_header.pack_into(self._buf, 0, self... | Writes single TDS packet into underlying transport.
Data for the packet is taken from internal buffer.
:param final: True means this is the final packet in substream. |
def where(boolean_expr, true_expr, false_null_expr):
"""
Equivalent to the ternary expression: if X then Y else Z
Parameters
----------
boolean_expr : BooleanValue (array or scalar)
true_expr : value
Values for each True value
false_null_expr : value
Values for False or NULL val... | Equivalent to the ternary expression: if X then Y else Z
Parameters
----------
boolean_expr : BooleanValue (array or scalar)
true_expr : value
Values for each True value
false_null_expr : value
Values for False or NULL values
Returns
-------
result : arity depending on inpu... |
def zremrangebyscore(self, key, min_score, max_score):
"""Removes all elements in the sorted set stored at key with a score
between min and max.
Intervals are described in :meth:`~tredis.RedisClient.zrangebyscore`.
Returns the number of elements removed.
.. note::
... | Removes all elements in the sorted set stored at key with a score
between min and max.
Intervals are described in :meth:`~tredis.RedisClient.zrangebyscore`.
Returns the number of elements removed.
.. note::
**Time complexity**: ``O(log(N)+M)`` with ``N`` being the number o... |
def get_initial_state_args(value_and_gradients_function,
initial_position,
grad_tolerance,
control_inputs=None):
"""Returns a dictionary to populate the initial state of the search procedure.
Performs an initial convergence check and ... | Returns a dictionary to populate the initial state of the search procedure.
Performs an initial convergence check and the first evaluation of the
objective function.
Args:
value_and_gradients_function: A Python callable that accepts a tensor and
returns a tuple of two tensors: the objective function v... |
def makeDoubleLinked(dom, parent=None):
"""
Standard output from `dhtmlparser` is single-linked tree. This will make it
double-linked.
Args:
dom (obj): :class:`.HTMLElement` instance.
parent (obj, default None): Don't use this, it is used in recursive
call.
"""
do... | Standard output from `dhtmlparser` is single-linked tree. This will make it
double-linked.
Args:
dom (obj): :class:`.HTMLElement` instance.
parent (obj, default None): Don't use this, it is used in recursive
call. |
def load(self):
"""Load the data from a file.
:rtype: io.BytesIO
"""
stream = self.fs.load()
stream = self.codec.decompress(stream)
return stream | Load the data from a file.
:rtype: io.BytesIO |
def get_more(collection_name, num_to_return, cursor_id):
"""Get a **getMore** message.
"""
data = __ZERO
data += bson._make_c_string(collection_name)
data += struct.pack("<i", num_to_return)
data += struct.pack("<q", cursor_id)
return __pack_message(2005, data) | Get a **getMore** message. |
def notice_stream(self, stream):
"""
When this parent is responsible for a new directly connected child
stream, we're also responsible for broadcasting DEL_ROUTE upstream
if/when that child disconnects.
"""
self._routes_by_stream[stream] = set([stream.remote_id])
... | When this parent is responsible for a new directly connected child
stream, we're also responsible for broadcasting DEL_ROUTE upstream
if/when that child disconnects. |
def check_order(self):
"""
Performs the check and store the violations in self.violations.
:return: boolean indicating the error state
"""
for feature, info in self.constraints.items():
self._check_feature(feature, info, 'before')
self._check_feature(feat... | Performs the check and store the violations in self.violations.
:return: boolean indicating the error state |
def _build_request_factory(cls, session: AppSession):
'''Create the request factory.
A request factory is any callable object that returns a
:class:`.http.Request`. The callable must accept the same
arguments to Request.
Returns:
A callable object
'''
... | Create the request factory.
A request factory is any callable object that returns a
:class:`.http.Request`. The callable must accept the same
arguments to Request.
Returns:
A callable object |
def error(self, message):
"""Override superclass to support customized error message.
Error message needs to be rewritten in order to display visible commands
only, when invalid command is called by user. Otherwise, hidden commands
will be displayed in stderr, which is not expected.
Refer the foll... | Override superclass to support customized error message.
Error message needs to be rewritten in order to display visible commands
only, when invalid command is called by user. Otherwise, hidden commands
will be displayed in stderr, which is not expected.
Refer the following argparse python documentati... |
def from_array(array):
"""
Deserialize a new InputLocationMessageContent from a given dictionary.
:return: new InputLocationMessageContent instance.
:rtype: InputLocationMessageContent
"""
if array is None or not array:
return None
# end if
as... | Deserialize a new InputLocationMessageContent from a given dictionary.
:return: new InputLocationMessageContent instance.
:rtype: InputLocationMessageContent |
def cli(context, mongodb, username, password, authdb, host, port, loglevel, config, demo):
"""scout: manage interactions with a scout instance."""
# log_format = "%(message)s" if sys.stdout.isatty() else None
log_format = None
coloredlogs.install(level=loglevel, fmt=log_format)
LOG.info("Running sco... | scout: manage interactions with a scout instance. |
def _packet_loop(self):
"""
Packet processing loop
:rtype: None
"""
while self._is_running:
# Only wait if there are no more packets in the inbox
if self.inbox.empty() \
and not self.new_packet.wait(self._packet_timeout):
... | Packet processing loop
:rtype: None |
def etau_madau(wave, z, **kwargs):
"""Madau 1995 extinction for a galaxy at given redshift.
This is the Lyman-alpha prescription from the photo-z code BPZ.
The Lyman-alpha forest approximately has an effective
"throughput" which is a function of redshift and
rest-frame wavelength.
One would mul... | Madau 1995 extinction for a galaxy at given redshift.
This is the Lyman-alpha prescription from the photo-z code BPZ.
The Lyman-alpha forest approximately has an effective
"throughput" which is a function of redshift and
rest-frame wavelength.
One would multiply the SEDs by this factor before
p... |
def has_predecessor(self, u, v, t=None):
"""Return True if node u has predecessor v at time t (optional).
This is true if graph has the edge u<-v.
Parameters
----------
u, v : nodes
Nodes can be, for example, strings or numbers.
Nodes must be hashable (a... | Return True if node u has predecessor v at time t (optional).
This is true if graph has the edge u<-v.
Parameters
----------
u, v : nodes
Nodes can be, for example, strings or numbers.
Nodes must be hashable (and not None) Python objects.
t : snapshot id... |
def make_logging_undefined(logger=None, base=None):
"""Given a logger object this returns a new undefined class that will
log certain failures. It will log iterations and printing. If no
logger is given a default logger is created.
Example::
logger = logging.getLogger(__name__)
Loggi... | Given a logger object this returns a new undefined class that will
log certain failures. It will log iterations and printing. If no
logger is given a default logger is created.
Example::
logger = logging.getLogger(__name__)
LoggingUndefined = make_logging_undefined(
logger=lo... |
def with_stmt__26(self, with_loc, context, with_var, colon_loc, body):
"""(2.6, 3.0) with_stmt: 'with' test [ with_var ] ':' suite"""
if with_var:
as_loc, optional_vars = with_var
item = ast.withitem(context_expr=context, optional_vars=optional_vars,
... | (2.6, 3.0) with_stmt: 'with' test [ with_var ] ':' suite |
def run_service(prediction_fxn, namespace, prediction_type, block=False):
"""
Supported prediction_type:
- hvac
- occupancy
"""
subscribe = '{0}/s.predictions/+/i.{1}/slot/request'.format(namespace, prediction_type)
if block:
print 'Blocking is True! This will loop forever and progra... | Supported prediction_type:
- hvac
- occupancy |
def cat(self, out_ndx=None):
"""Concatenate input index files.
Generate a new index file that contains the default Gromacs index
groups (if a structure file was defined) and all index groups from the
input index files.
:Arguments:
out_ndx : filename
Nam... | Concatenate input index files.
Generate a new index file that contains the default Gromacs index
groups (if a structure file was defined) and all index groups from the
input index files.
:Arguments:
out_ndx : filename
Name of the output index file; if ``None`` ... |
def launch(self, workflow_job_template=None, monitor=False, wait=False,
timeout=None, extra_vars=None, **kwargs):
"""Launch a new workflow job based on a workflow job template.
Creates a new workflow job in Ansible Tower, starts it, and
returns back an ID in order for its status ... | Launch a new workflow job based on a workflow job template.
Creates a new workflow job in Ansible Tower, starts it, and
returns back an ID in order for its status to be monitored.
=====API DOCS=====
Launch a new workflow job based on a workflow job template.
:param workflow_jo... |
def _collate_results(self, field=None):
"""For a list of objects associated with a classification result, return the results as a
DataFrame and dict of taxa info.
Parameters
----------
field : {'readcount_w_children', 'readcount', 'abundance'}
Which field to use for ... | For a list of objects associated with a classification result, return the results as a
DataFrame and dict of taxa info.
Parameters
----------
field : {'readcount_w_children', 'readcount', 'abundance'}
Which field to use for the abundance/count of a particular taxon in a samp... |
def check_input(input):
"""
:param input: ndarray or list of ndarray or JTensor or list of JTensor.
:return: (list of JTensor, isTable)
"""
def to_jtensor(i):
if isinstance(i, np.ndarray):
return JTensor.from_ndarray(i)
elif isinstance(i, J... | :param input: ndarray or list of ndarray or JTensor or list of JTensor.
:return: (list of JTensor, isTable) |
def roc_auc(fg_vals, bg_vals):
"""
Computes the ROC Area Under Curve (ROC AUC)
Parameters
----------
fg_vals : array_like
list of values for positive set
bg_vals : array_like
list of values for negative set
Returns
-------
score : float
ROC AUC score
... | Computes the ROC Area Under Curve (ROC AUC)
Parameters
----------
fg_vals : array_like
list of values for positive set
bg_vals : array_like
list of values for negative set
Returns
-------
score : float
ROC AUC score |
def data(self, rows=None):
"""Access a batch of episodes from the memory.
Padding elements after the length of each episode are unspecified and might
contain old data.
Args:
rows: Episodes to select, defaults to all.
Returns:
Tuple containing a tuple of transition quantities with batc... | Access a batch of episodes from the memory.
Padding elements after the length of each episode are unspecified and might
contain old data.
Args:
rows: Episodes to select, defaults to all.
Returns:
Tuple containing a tuple of transition quantities with batch and time
dimensions, and a... |
def write_color_old( text, attr=None):
u'''write text at current cursor position and interpret color escapes.
return the number of characters written.
'''
res = []
chunks = terminal_escape.split(text)
n = 0 # count the characters we actually write, omitting the escapes
if attr is No... | u'''write text at current cursor position and interpret color escapes.
return the number of characters written. |
def inputs(self, name):
"""List input names and types of a step in the steps library.
Args:
name (str): name of a step in the steps library.
"""
self._closed()
step = self._get_step(name, make_copy=False)
return step.list_inputs() | List input names and types of a step in the steps library.
Args:
name (str): name of a step in the steps library. |
def binarize(self, threshold=0):
"""
Binarize the pianoroll.
Parameters
----------
threshold : int or float
A threshold used to binarize the pianorolls. Defaults to zero.
"""
if not self.is_binarized():
self.pianoroll = (self.pianoroll > ... | Binarize the pianoroll.
Parameters
----------
threshold : int or float
A threshold used to binarize the pianorolls. Defaults to zero. |
def read(file, system):
"""read PSS/E RAW file v32 format"""
blocks = [
'bus', 'load', 'fshunt', 'gen', 'branch', 'transf', 'area',
'twotermdc', 'vscdc', 'impedcorr', 'mtdc', 'msline', 'zone',
'interarea', 'owner', 'facts', 'swshunt', 'gne', 'Q'
]
nol = [1, 1, 1, 1, 1, 4, 1, 0, ... | read PSS/E RAW file v32 format |
def dumps(value):
"""
Dumps a data structure to TOML source code.
The given value must be either a dict of dict values, a dict, or a TOML file constructed by this module.
"""
from contoml.file.file import TOMLFile
if not isinstance(value, TOMLFile):
raise RuntimeError("Can only dump a... | Dumps a data structure to TOML source code.
The given value must be either a dict of dict values, a dict, or a TOML file constructed by this module. |
def get(*args, **kwargs):
"""Get users."""
from invenio.modules.oauthclient.models import RemoteToken
q = RemoteToken.query
return q.count(), q.all() | Get users. |
def insert_chunk(self, id_):
"""Insert a new chunk at the end of the IFF file"""
if not isinstance(id_, text_type):
id_ = id_.decode('ascii')
if not is_valid_chunk_id(id_):
raise KeyError("AIFF key must be four ASCII characters.")
self.__fileobj.seek(self.__nex... | Insert a new chunk at the end of the IFF file |
def database_to_SimaPro_csv(self):
"""
Export the lcopt model as a SimaPro csv file.
The file will be called "<ModelName>_database_export.csv"
"""
self.parameter_scan()
csv_args = {}
csv_args['processes'] = []
db = self.database['items']
... | Export the lcopt model as a SimaPro csv file.
The file will be called "<ModelName>_database_export.csv" |
def loadVectors(self, filename, cols = None, everyNrows = 1,
delim = ' ', checkEven = 1, patterned = 0):
"""
Load a set of vectors from a file. Takes a filename, list of cols
you want (or None for all), get every everyNrows (or 1 for no
skipping), and a delimeter.
... | Load a set of vectors from a file. Takes a filename, list of cols
you want (or None for all), get every everyNrows (or 1 for no
skipping), and a delimeter. |
def append_multiple(self, data, segment=0):
"""
Append multiple rows to an SFrame.
Throws a RuntimeError if one or more column's type is incompatible with
a type appended.
Parameters
----------
data : iterable[iterable]
A collection of multiple iter... | Append multiple rows to an SFrame.
Throws a RuntimeError if one or more column's type is incompatible with
a type appended.
Parameters
----------
data : iterable[iterable]
A collection of multiple iterables, each representing a single row.
segment : int
... |
def match(elem, seq_expr):
"""
Return True if elem (an element of elem_list) matches seq_expr, an element in self.sequence
"""
if type(seq_expr) is str: # wild-card
if seq_expr == '.': # match any element
return True
elif seq_expr == '\d':
... | Return True if elem (an element of elem_list) matches seq_expr, an element in self.sequence |
def validate_num_assertions(self):
"""
Verifies that the document only contains a single Assertion (encrypted or not)
:returns: True if only 1 assertion encrypted or not
:rtype: bool
"""
encrypted_assertion_nodes = OneLogin_Saml2_XML.query(self.document, '//saml:Encrypte... | Verifies that the document only contains a single Assertion (encrypted or not)
:returns: True if only 1 assertion encrypted or not
:rtype: bool |
def _protected_inverse(x1):
"""Closure of log for zero arguments."""
with np.errstate(divide='ignore', invalid='ignore'):
return np.where(np.abs(x1) > 0.001, 1. / x1, 0.) | Closure of log for zero arguments. |
def encrypters(self):
"""A ``set`` containing all key ids (if any) to which this message was encrypted."""
return set(m.encrypter for m in self._sessionkeys if isinstance(m, PKESessionKey)) | A ``set`` containing all key ids (if any) to which this message was encrypted. |
def _non_reducing_slice(slice_):
"""
Ensurse that a slice doesn't reduce to a Series or Scalar.
Any user-paseed `subset` should have this called on it
to make sure we're always working with DataFrames.
"""
# default to column slice, like DataFrame
# ['A', 'B'] -> IndexSlices[:, ['A', 'B']]
... | Ensurse that a slice doesn't reduce to a Series or Scalar.
Any user-paseed `subset` should have this called on it
to make sure we're always working with DataFrames. |
def process(self, diagnostic):
"""
The default implementation of :meth:`process` renders non-fatal
diagnostics to ``sys.stderr``, and raises fatal ones as a :class:`Error`.
"""
diagnostic.notes += self._appended_notes
self.render_diagnostic(diagnostic)
if diagnost... | The default implementation of :meth:`process` renders non-fatal
diagnostics to ``sys.stderr``, and raises fatal ones as a :class:`Error`. |
def iterslice(iterable, start=0, stop=None, step=1):
# type: (Iterable[T], int, int, int) -> Iterable[T]
""" Like itertools.islice, but accept int and callables.
If `start` is a callable, start the slice after the first time
start(item) == True.
If `stop` is a callable, stop the slice ... | Like itertools.islice, but accept int and callables.
If `start` is a callable, start the slice after the first time
start(item) == True.
If `stop` is a callable, stop the slice after the first time
stop(item) == True. |
def set_bind(self):
"""
Sets key bindings.
"""
self.bind('<Button-1>', lambda e: self.add(0.1))
self.bind('<Button-3>', lambda e: self.sub(0.1))
self.bind('<Up>', lambda e: self.add(0.1))
self.bind('<Down>', lambda e: self.sub(0.1))
self.bind('<Shift-Up>',... | Sets key bindings. |
def as_nick(self, name):
"""
Set the nick for the duration of the context.
"""
orig = self.get_nickname()
self.nick(name)
try:
yield orig
finally:
self.nick(orig) | Set the nick for the duration of the context. |
def uuid_from_kronos_time(time, _type=UUIDType.RANDOM):
"""
Generate a UUID with the specified time.
If `lowest` is true, return the lexicographically first UUID for the specified
time.
"""
return timeuuid_from_time(int(time) + UUID_TIME_OFFSET, type=_type) | Generate a UUID with the specified time.
If `lowest` is true, return the lexicographically first UUID for the specified
time. |
def _sunos_memdata():
'''
Return the memory information for SunOS-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = '/usr/sbin/prtconf 2>/dev/null'
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = line.split(' ')
if comps[0].s... | Return the memory information for SunOS-like systems |
def upload(self, local_fn: str, remote_fn: str = '',
dont_overwrite: bool = False) -> None:
"""Uploads file to remote instance. If location not specified, dumps it
into default directory. If remote location has files or directories with the
same name, behavior is undefined."""
# support w... | Uploads file to remote instance. If location not specified, dumps it
into default directory. If remote location has files or directories with the
same name, behavior is undefined. |
def on_graph_def(self, graph_def, device_name, wall_time):
"""Implementation of the GraphDef-carrying Event proto callback.
Args:
graph_def: A GraphDef proto. N.B.: The GraphDef is from
the core runtime of a debugged Session::Run() call, after graph
partition. Therefore it may differ from... | Implementation of the GraphDef-carrying Event proto callback.
Args:
graph_def: A GraphDef proto. N.B.: The GraphDef is from
the core runtime of a debugged Session::Run() call, after graph
partition. Therefore it may differ from the GraphDef available to
the general TensorBoard. For ex... |
def send_messages(self, request, queryset, bulk=False):
"""
Provides error handling for DeviceAdmin send_message and send_bulk_message methods.
"""
ret = []
errors = []
r = ""
for device in queryset:
try:
if bulk:
r = queryset.send_message("Test bulk notification")
else:
r = device.s... | Provides error handling for DeviceAdmin send_message and send_bulk_message methods. |
def _calculate_correctedF3X4(self):
'''Calculate `phi` based on the empirical `e_pw` values'''
def F(phi):
phi_reshape = phi.reshape((3, N_NT))
functionList = []
stop_frequency = []
for x in range(N_STOP):
codonFrequency = STOP_CODON_TO_NT... | Calculate `phi` based on the empirical `e_pw` values |
def maybe_scheduled_sampling(self, features, logits, losses):
"""Scheduled sampling.
Performs forward inference again with "targets" feature replaced with values
sampled from the model.
This is the identity unless self.hparams.scheduled_sampling_prob > 0
(default).
**WARNING**: This is not a ... | Scheduled sampling.
Performs forward inference again with "targets" feature replaced with values
sampled from the model.
This is the identity unless self.hparams.scheduled_sampling_prob > 0
(default).
**WARNING**: This is not a faithful implementation of scheduled sampling.
This implementatio... |
def _de_casteljau_one_round(nodes, degree, lambda1, lambda2, lambda3):
r"""Performs one "round" of the de Casteljau algorithm for surfaces.
.. note::
There is also a Fortran implementation of this function, which
will be used if it can be built.
.. note::
This is a helper function, ... | r"""Performs one "round" of the de Casteljau algorithm for surfaces.
.. note::
There is also a Fortran implementation of this function, which
will be used if it can be built.
.. note::
This is a helper function, used by :func:`make_transform` and
:func:`_specialize_surface` (and ... |
def validate_input_source_config_source_url_url(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
validate = ET.Element("validate")
config = validate
input = ET.SubElement(validate, "input")
source = ET.SubElement(input, "source")
c... | Auto Generated Code |
def hume_process_jsonld():
"""Process Hume JSON-LD and return INDRA Statements."""
if request.method == 'OPTIONS':
return {}
response = request.body.read().decode('utf-8')
body = json.loads(response)
jsonld_str = body.get('jsonld')
jsonld = json.loads(jsonld_str)
hp = hume.process_js... | Process Hume JSON-LD and return INDRA Statements. |
def add_sign_transaction(self, signer: Account):
"""
This interface is used to add signature into the transaction.
:param signer: an Account object which will sign the transaction.
:return: a Transaction object which has been signed.
"""
if self.sig_list is None or len(s... | This interface is used to add signature into the transaction.
:param signer: an Account object which will sign the transaction.
:return: a Transaction object which has been signed. |
def change_scale(self, new_scale):
"""
Args:
new_scale (str)
Return:
Date
"""
offset = self.scale.offset(self._mjd, new_scale, self.eop)
result = self.datetime + timedelta(seconds=offset)
return self.__class__(result, scale=new_scale) | Args:
new_scale (str)
Return:
Date |
def prepare_user_module(self, user_module=None, user_ns=None):
"""Prepare the module and namespace in which user code will be run.
When IPython is started normally, both parameters are None: a new module
is created automatically, and its __dict__ used as the namespace.
... | Prepare the module and namespace in which user code will be run.
When IPython is started normally, both parameters are None: a new module
is created automatically, and its __dict__ used as the namespace.
If only user_module is provided, its __dict__ is used as the namespace.
... |
def _add_include_arg(arg_parser):
"""
Adds optional repeatable include parameter to a parser.
:param arg_parser: ArgumentParser parser to add this argument to.
"""
arg_parser.add_argument("--include",
metavar='Path',
action='append',
... | Adds optional repeatable include parameter to a parser.
:param arg_parser: ArgumentParser parser to add this argument to. |
def all_versions_equal(self, versions): # type: (Dict[str,str]) -> bool
"""
Verify that all the versions are the same.
:param versions:
:return:
"""
if len(versions) <= 1:
return True
semver = None
for key, version in versions.items():
... | Verify that all the versions are the same.
:param versions:
:return: |
def save(self, specfiles=None, compress=True, path=None):
"""Writes the specified specfiles to ``siic`` files on the hard disk.
.. note::
If ``.save()`` is called and no ``siic`` files are present in the
specified path new files are generated, otherwise old files are
... | Writes the specified specfiles to ``siic`` files on the hard disk.
.. note::
If ``.save()`` is called and no ``siic`` files are present in the
specified path new files are generated, otherwise old files are
replaced.
:param specfiles: the name of an ms-run file or a... |
def add_group_maintainer(self, name, user):
"""Add the given user to the named group.
Both group and user must already exist for this to succeed.
Args:
name (string): Name of group.
user (string): User to add to group.
version (optional[string]): Version of ... | Add the given user to the named group.
Both group and user must already exist for this to succeed.
Args:
name (string): Name of group.
user (string): User to add to group.
version (optional[string]): Version of the Boss API to use. Defaults to the latest supported ... |
def install():
"""Configure the twisted mainloop to be run using the select() reactor.
"""
reactor = ThreadedSelectReactor()
from twisted.internet.main import installReactor
installReactor(reactor)
return reactor | Configure the twisted mainloop to be run using the select() reactor. |
def join_time_series(serieses, ignore_year=False, T_s=None, aggregator='mean'):
"""Combine a dict of pd.Series objects into a single pd.DataFrame with optional downsampling
FIXME:
For ignore_year and multi-year data, the index (in seconds) is computed assuming
366 days per year (leap year). So 3 ou... | Combine a dict of pd.Series objects into a single pd.DataFrame with optional downsampling
FIXME:
For ignore_year and multi-year data, the index (in seconds) is computed assuming
366 days per year (leap year). So 3 out of 4 years will have a 1-day (86400 s) gap
Arguments:
series (dict of Seri... |
def getInfo(self, query=None, process=False, mode="phonefy", qURI=None):
"""
Method that checks the presence of a given query and recovers the first list of complains.
Args:
-----
query: Query to verify.
process: Calling the processing function.
mode:... | Method that checks the presence of a given query and recovers the first list of complains.
Args:
-----
query: Query to verify.
process: Calling the processing function.
mode: Mode to be executed.
qURI: A query to be checked.
Return:
-----... |
def debug_derivative(self, guess):
"""returns (explicit, auto)"""
from .lmmin import check_derivative
return check_derivative(self.component.npar, self.data.size,
self.lm_model, self.lm_deriv, guess) | returns (explicit, auto) |
def listen_for_updates(self):
"""Attach a callback on the group pubsub"""
self.toredis.subscribe(self.group_pubsub, callback=self.callback) | Attach a callback on the group pubsub |
def extract_props(self, settings):
'''
Extract all valuable properties to be displayed
'''
props = {}
for param in self.call_parameters:
if param in settings:
props[param] = settings[param]
else:
props[param] = None
... | Extract all valuable properties to be displayed |
def build_actions(self):
"""Create an ActionCollection that will perform sanity checks, copy the file,
create a database entry and perform cleanup actions and in case of a failure clean everything up.
:param work: the workfile
:type work: :class:`JB_File`
:param release: the rel... | Create an ActionCollection that will perform sanity checks, copy the file,
create a database entry and perform cleanup actions and in case of a failure clean everything up.
:param work: the workfile
:type work: :class:`JB_File`
:param release: the releasefile
:type release: :cla... |
def chat_post_message(self, text, room_id=None, channel=None, **kwargs):
"""Posts a new chat message."""
if room_id:
return self.__call_api_post('chat.postMessage', roomId=room_id, text=text, kwargs=kwargs)
elif channel:
return self.__call_api_post('chat.postMessage', cha... | Posts a new chat message. |
def rekey(dikt):
"""Rekey a dict that has been forced to use str keys where there should be
ints by json."""
for k in dikt.iterkeys():
if isinstance(k, basestring):
ik=fk=None
try:
ik = int(k)
except ValueError:
try:
... | Rekey a dict that has been forced to use str keys where there should be
ints by json. |
def parse_simple_duration(duration):
"""
Attepmt to parse an ISO8601 formatted duration, using a naive calculation.
Accepts a ``duration`` which must be an ISO8601 formatted string, and
assumes 365 days in a year and 30 days in a month for the calculation.
Returns a ``datetime.timedelta`` object.
... | Attepmt to parse an ISO8601 formatted duration, using a naive calculation.
Accepts a ``duration`` which must be an ISO8601 formatted string, and
assumes 365 days in a year and 30 days in a month for the calculation.
Returns a ``datetime.timedelta`` object. |
def db_query(self, client_id, msg):
"""Perform a raw query on the task record database."""
content = msg['content']
query = content.get('query', {})
keys = content.get('keys', None)
buffers = []
empty = list()
try:
records = self.db.find_records(query,... | Perform a raw query on the task record database. |
def validate_sign(xml, cert=None, fingerprint=None, fingerprintalg='sha1', validatecert=False, debug=False, xpath=None, multicerts=None):
"""
Validates a signature (Message or Assertion).
:param xml: The element we should validate
:type: string | Document
:param cert: The publi... | Validates a signature (Message or Assertion).
:param xml: The element we should validate
:type: string | Document
:param cert: The public cert
:type: string
:param fingerprint: The fingerprint of the public cert
:type: string
:param fingerprintalg: The algorit... |
def gabc(elem, doc):
"""Handle gabc file inclusion and gabc code block."""
if type(elem) == Code and "gabc" in elem.classes:
if doc.format == "latex":
if elem.identifier == "":
label = ""
else:
label = '\\label{' + elem.identifier + '}'
... | Handle gabc file inclusion and gabc code block. |
def cnst_A0T(self, Y0):
r"""Compute :math:`A_0^T \mathbf{y}_0` component of
:math:`A^T \mathbf{y}` (see :meth:`.ADMMTwoBlockCnstrnt.cnst_AT`).
"""
# This calculation involves non-negligible computational cost. It
# should be possible to disable relevant diagnostic information
... | r"""Compute :math:`A_0^T \mathbf{y}_0` component of
:math:`A^T \mathbf{y}` (see :meth:`.ADMMTwoBlockCnstrnt.cnst_AT`). |
def get_decoder(cls, config: DecoderConfig, prefix: str) -> 'Decoder':
"""
Creates decoder based on config type.
:param config: Decoder config.
:param prefix: Prefix to prepend for decoder.
:return: Decoder instance.
"""
config_type = type(config)
if con... | Creates decoder based on config type.
:param config: Decoder config.
:param prefix: Prefix to prepend for decoder.
:return: Decoder instance. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.