code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def dump_stats(self, fdump, close=True):
"""
Dump the logged data to a file.
The argument `file` can be either a filename or an open file object
that requires write access. `close` controls if the file is closed
before leaving this method (the default behaviour).
"""
... | Dump the logged data to a file.
The argument `file` can be either a filename or an open file object
that requires write access. `close` controls if the file is closed
before leaving this method (the default behaviour). |
def read_byte(self, address):
"""Reads unadressed byte from a device. """
LOGGER.debug("Reading byte from device %s!", hex(address))
return self.driver.read_byte(address) | Reads unadressed byte from a device. |
def merge_translations(localization_bundle_path):
""" Merges the new translation with the old one.
The translated files are saved as '.translated' file, and are merged with old translated file.
Args:
localization_bundle_path (str): The path to the localization bundle.
"""
logging.info("Me... | Merges the new translation with the old one.
The translated files are saved as '.translated' file, and are merged with old translated file.
Args:
localization_bundle_path (str): The path to the localization bundle. |
def create_oqhazardlib_source(self, tom, mesh_spacing, use_defaults=False):
"""
Creates an instance of the source model as :class:
openquake.hazardlib.source.complex_fault.ComplexFaultSource
"""
if not self.mfd:
raise ValueError("Cannot write to hazardlib without MFD"... | Creates an instance of the source model as :class:
openquake.hazardlib.source.complex_fault.ComplexFaultSource |
def best_model(self):
"""Rebuilds the top scoring model from an optimisation.
Returns
-------
model: AMPAL
Returns an AMPAL model of the top scoring parameters.
Raises
------
AttributeError
Raises a name error if the optimiser has not bee... | Rebuilds the top scoring model from an optimisation.
Returns
-------
model: AMPAL
Returns an AMPAL model of the top scoring parameters.
Raises
------
AttributeError
Raises a name error if the optimiser has not been run. |
def GetTagDescription(tag_name):
"""
Gets the current description of a point configured in a real-time eDNA
service.
:param tag_name: fully-qualified (site.service.tag) eDNA tag
:return: tag description
"""
# Check if the point even exists
if not DoesIDExist(tag_name):
... | Gets the current description of a point configured in a real-time eDNA
service.
:param tag_name: fully-qualified (site.service.tag) eDNA tag
:return: tag description |
def init_app(self, app, configstore):
"""Initialize the extension for the given application and store.
Parse the configuration values stored in the database obtained from
the ``WAFFLE_CONFS`` value of the configuration.
Arguments:
app: Flask application instance
... | Initialize the extension for the given application and store.
Parse the configuration values stored in the database obtained from
the ``WAFFLE_CONFS`` value of the configuration.
Arguments:
app: Flask application instance
configstore (WaffleStore): database store. |
def buyQuestItems(self):
""" Attempts to buy all quest items, returns result
Returns
bool - True if successful, otherwise False
"""
for item in self.items:
us = UserShopFront(self.usr, item.owner, item.id, str(item.price))
us.loadInventory()... | Attempts to buy all quest items, returns result
Returns
bool - True if successful, otherwise False |
def update_instance(
self, model_name, pk, instance=None, version=None,
update_only=False):
"""Create or update a cached instance.
Keyword arguments are:
model_name - The name of the model
pk - The primary key of the instance
instance - The Django model i... | Create or update a cached instance.
Keyword arguments are:
model_name - The name of the model
pk - The primary key of the instance
instance - The Django model instance, or None to load it
versions - Version to update, or None for all
update_only - If False (default), the... |
def get_port_profile_for_intf_input_rbridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_port_profile_for_intf = ET.Element("get_port_profile_for_intf")
config = get_port_profile_for_intf
input = ET.SubElement(get_port_profile_for_intf,... | Auto Generated Code |
def _parse_bbox_grid(bbox_grid):
""" Helper method for parsing bounding box grid. It will try to parse it into `BBoxCollection`
"""
if isinstance(bbox_grid, BBoxCollection):
return bbox_grid
if isinstance(bbox_grid, list):
return BBoxCollection(bbox_grid)
... | Helper method for parsing bounding box grid. It will try to parse it into `BBoxCollection` |
def recent(self, include=None):
"""
Retrieve the most recent tickets
"""
return self._query_zendesk(self.endpoint.recent, 'ticket', id=None, include=include) | Retrieve the most recent tickets |
def render(self, request, collect_render_data=True, **kwargs):
"""
Render this view. This will call the render method
on the render class specified.
:param request: The request object
:param collect_render_data: If True we will call \
the get_render_data method to pass a... | Render this view. This will call the render method
on the render class specified.
:param request: The request object
:param collect_render_data: If True we will call \
the get_render_data method to pass a complete context \
to the renderer.
:param kwargs: Any other keywo... |
def DownloadResource(url, path):
'''Downloads resources from s3 by url and unzips them to the provided path'''
import requests
from six import BytesIO
import zipfile
print("Downloading... {} to {}".format(url, path))
r = requests.get(url, stream=True)
z = zipfile.ZipFile(BytesIO(r.content))
... | Downloads resources from s3 by url and unzips them to the provided path |
def is_separator(self, char):
"""
Test if a character is a separator.
Parameters
----------
char : str
The character to test.
Returns
-------
ret : bool
True if character is a separator, False otherwise.
"""
if le... | Test if a character is a separator.
Parameters
----------
char : str
The character to test.
Returns
-------
ret : bool
True if character is a separator, False otherwise. |
def is_valid_url(self, url, non_blocking=True):
"""Check if url is valid."""
logger.debug(str((url)))
if non_blocking:
method = self._is_valid_url
return self._create_worker(method, url)
else:
return self._is_valid_url(url) | Check if url is valid. |
def wcomplex(wave):
r"""
Convert a waveform's dependent variable vector to complex.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for
... | r"""
Convert a waveform's dependent variable vector to complex.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for
.. peng.wave_function... |
def expand(cls, match, expand):
"""
If use expand directly, the url-decoded context will be decoded again, which create a security
issue. Hack expand to quote the text before expanding
"""
return re._expand(match.re, cls._EncodedMatch(match), expand) | If use expand directly, the url-decoded context will be decoded again, which create a security
issue. Hack expand to quote the text before expanding |
def get_rows_by_cols(self, matching_dict):
"""Return all rows where the cols match the elements given in the matching_dict
Parameters
----------
matching_dict: :obj:'dict'
Desired dictionary of col values.
Returns
-------
:obj:`list`
A li... | Return all rows where the cols match the elements given in the matching_dict
Parameters
----------
matching_dict: :obj:'dict'
Desired dictionary of col values.
Returns
-------
:obj:`list`
A list of rows that satisfy the matching_dict |
def server_factory(global_conf, host, port, **options):
"""Server factory for paste.
Options are:
* proactor: class name to use from cogen.core.proactors
(default: DefaultProactor - best available proactor for current platform)
* proactor_resolution: float
* sched_default_priority: int (se... | Server factory for paste.
Options are:
* proactor: class name to use from cogen.core.proactors
(default: DefaultProactor - best available proactor for current platform)
* proactor_resolution: float
* sched_default_priority: int (see cogen.core.util.priority)
* sched_default_timeout: floa... |
def sample_annealed_importance_chain(
num_steps,
proposal_log_prob_fn,
target_log_prob_fn,
current_state,
make_kernel_fn,
parallel_iterations=10,
name=None):
"""Runs annealed importance sampling (AIS) to estimate normalizing constants.
This function uses an MCMC transition operator (e.g... | Runs annealed importance sampling (AIS) to estimate normalizing constants.
This function uses an MCMC transition operator (e.g., Hamiltonian Monte Carlo)
to sample from a series of distributions that slowly interpolates between
an initial "proposal" distribution:
`exp(proposal_log_prob_fn(x) - proposal_log_no... |
def plot_grouped_gos(self, fout_img=None, exclude_hdrs=None, **kws_usr):
"""One Plot containing all user GOs (yellow or green) and header GO IDs(green or purple)."""
# kws_plt -> go2color go2bordercolor
kws_plt, kws_dag = self._get_kws_plt(self.grprobj.usrgos, **kws_usr)
pltgosusr = self... | One Plot containing all user GOs (yellow or green) and header GO IDs(green or purple). |
def password_hash(password, password_salt=None):
"""Hashes a specified password"""
password_salt = password_salt or oz.settings["session_salt"]
salted_password = password_salt + password
return "sha256!%s" % hashlib.sha256(salted_password.encode("utf-8")).hexdigest() | Hashes a specified password |
def _plot_weights_heatmap(self, index=None, figsize=None, **kwargs):
"""Plot weights as a heatmap
index = can be a particular index or a list of indicies
**kwargs - additional arguments to concise.utils.plot.heatmap
"""
W = self.get_weights()[0]
if index is None:
... | Plot weights as a heatmap
index = can be a particular index or a list of indicies
**kwargs - additional arguments to concise.utils.plot.heatmap |
def ensure_compliance(self):
"""Ensure that the all registered files comply to registered criteria.
"""
for p in self.paths:
if os.path.exists(p):
if self.is_compliant(p):
continue
log('File %s is not in compliance.' % p, level=INF... | Ensure that the all registered files comply to registered criteria. |
def enter_maintenance_mode(self):
"""
Put the cluster in maintenance mode.
@return: Reference to the completed command.
@since: API v2
"""
cmd = self._cmd('enterMaintenanceMode')
if cmd.success:
self._update(get_cluster(self._get_resource_root(), self.name))
return cmd | Put the cluster in maintenance mode.
@return: Reference to the completed command.
@since: API v2 |
def getProperty(self, prop, *args, **kwargs):
"""
Get the value of a property. See the corresponding method for the
required arguments. For example, for the property _NET_WM_STATE, look
for :meth:`getWmState`
"""
f = self.__getAttrs.get(prop)
if not f:
... | Get the value of a property. See the corresponding method for the
required arguments. For example, for the property _NET_WM_STATE, look
for :meth:`getWmState` |
def dispatch_event(self, event: "Event") -> None:
"""
Dispatches the given event.
It is the duty of this method to set the target of the dispatched event by calling
`event.set_target(self)`.
Args:
event (Event): The event to dispatch. Must not be `None`.
... | Dispatches the given event.
It is the duty of this method to set the target of the dispatched event by calling
`event.set_target(self)`.
Args:
event (Event): The event to dispatch. Must not be `None`.
Raises:
TypeError: If the event is `None` or its ty... |
def _resolve_dependencies(self, cur, dependencies):
"""
Function checks if dependant packages are installed in DB
"""
list_of_deps_ids = []
_list_of_deps_unresolved = []
_is_deps_resolved = True
for k, v in dependencies.items():
pgpm.lib.utils.db.SqlSc... | Function checks if dependant packages are installed in DB |
def getHosts(filename=None, hostlist=None):
"""Return a list of hosts depending on the environment"""
if filename:
return getHostsFromFile(filename)
elif hostlist:
return getHostsFromList(hostlist)
elif getEnv() == "SLURM":
return getHostsFromSLURM()
elif getEnv() == "PBS":
... | Return a list of hosts depending on the environment |
def __feed_arthur(self):
""" Feed Ocean with backend data collected from arthur redis queue"""
with self.ARTHUR_FEED_LOCK:
# This is a expensive operation so don't do it always
if (time.time() - self.ARTHUR_LAST_MEMORY_CHECK) > 5 * self.ARTHUR_LAST_MEMORY_CHECK_TIME:
... | Feed Ocean with backend data collected from arthur redis queue |
def title(self, category):
""" Return the total printed length of this category item.
"""
return sum(
[self.getWidth(category, x) for x in self.fields]) | Return the total printed length of this category item. |
def estimate_ride(api_client):
"""Use an UberRidesClient to fetch a ride estimate and print the results.
Parameters
api_client (UberRidesClient)
An authorized UberRidesClient with 'request' scope.
"""
try:
estimate = api_client.estimate_ride(
product_id=SURGE_PRO... | Use an UberRidesClient to fetch a ride estimate and print the results.
Parameters
api_client (UberRidesClient)
An authorized UberRidesClient with 'request' scope. |
def _reset_em(self):
"""Resets self.em and the shared instances."""
self.em = _ExtendedManager(self.addr, self.authkey, mode=self.mode, start=False)
self.em.start()
self._set_shared_instances() | Resets self.em and the shared instances. |
def get_bool_relative(strings: Sequence[str],
prefix1: str,
delta: int,
prefix2: str,
ignoreleadingcolon: bool = False) -> Optional[bool]:
"""
Fetches a boolean parameter via :func:`get_string_relative`.
"""
return g... | Fetches a boolean parameter via :func:`get_string_relative`. |
def hostapi_info(index=None):
"""Return a generator with information about each host API.
If index is given, only one dictionary for the given host API is
returned.
"""
if index is None:
return (hostapi_info(i) for i in range(_pa.Pa_GetHostApiCount()))
else:
info = _pa.Pa_GetHo... | Return a generator with information about each host API.
If index is given, only one dictionary for the given host API is
returned. |
def _eval_call(self, node):
"""
Evaluate a function call
:param node: Node to eval
:return: Result of node
"""
try:
func = self.functions[node.func.id]
except KeyError:
raise NameError(node.func.id)
value = func(
*(sel... | Evaluate a function call
:param node: Node to eval
:return: Result of node |
def _iiOfAny(instance, classes):
"""
Returns true, if `instance` is instance of any (_iiOfAny) of the `classes`.
This function doesn't use :func:`isinstance` check, it just compares the
class names.
This can be generally dangerous, but it is really useful when you are
comparing class serialize... | Returns true, if `instance` is instance of any (_iiOfAny) of the `classes`.
This function doesn't use :func:`isinstance` check, it just compares the
class names.
This can be generally dangerous, but it is really useful when you are
comparing class serialized in one module and deserialized in another.
... |
def blame(self, rev='HEAD', committer=True, by='repository', ignore_globs=None, include_globs=None):
"""
Returns the blame from the current HEAD of the repository as a DataFrame. The DataFrame is grouped by committer
name, so it will be the sum of all contributions to the repository by each com... | Returns the blame from the current HEAD of the repository as a DataFrame. The DataFrame is grouped by committer
name, so it will be the sum of all contributions to the repository by each committer. As with the commit history
method, extensions and ignore_dirs parameters can be passed to exclude certain... |
def build_gemini_query(self, query, extra_info):
"""Append sql to a gemini query
Args:
query(str): The gemini query
extra_info(str): The text that should be added
Return:
extended_query(str)
"""
if 'WHERE' in query:
return "{0} AN... | Append sql to a gemini query
Args:
query(str): The gemini query
extra_info(str): The text that should be added
Return:
extended_query(str) |
def webhoneypotbytype(date, return_format=None):
"""API data for `Webhoneypot: Attack By Type
<https://isc.sans.edu/webhoneypot/types.html>`_. We currently use a set
of regular expressions to determine the type of attack used to attack the
honeypot. Output is the top 30 attacks for the last month.
... | API data for `Webhoneypot: Attack By Type
<https://isc.sans.edu/webhoneypot/types.html>`_. We currently use a set
of regular expressions to determine the type of attack used to attack the
honeypot. Output is the top 30 attacks for the last month.
:param date: string or datetime.date() (required) |
def T_sigma(self, sigma):
"""
Given a policy `sigma`, return the T_sigma operator.
Parameters
----------
sigma : array_like(int, ndim=1)
Policy vector, of length n.
Returns
-------
callable
The T_sigma operator.
"""
... | Given a policy `sigma`, return the T_sigma operator.
Parameters
----------
sigma : array_like(int, ndim=1)
Policy vector, of length n.
Returns
-------
callable
The T_sigma operator. |
def findnextmatch(self, startkey, find_string, flags, search_result=True):
""" Returns a tuple with the position of the next match of find_string
Returns None if string not found.
Parameters:
-----------
startkey: Start position of search
find_string:String to be sear... | Returns a tuple with the position of the next match of find_string
Returns None if string not found.
Parameters:
-----------
startkey: Start position of search
find_string:String to be searched for
flags: List of strings, out of
["UP" xor "DOW... |
def get_flow(self, name, options=None):
""" Get a primed and readytogo flow coordinator. """
config = self.project_config.get_flow(name)
callbacks = self.callback_class()
coordinator = FlowCoordinator(
self.project_config,
config,
name=name,
... | Get a primed and readytogo flow coordinator. |
def plot_time_freq(self, mindB=-100, maxdB=None, norm=True,
yaxis_label_position="right"):
"""Plotting method to plot both time and frequency domain results.
See :meth:`plot_frequencies` for the optional arguments.
.. plot::
:width: 80%
:include-source:
... | Plotting method to plot both time and frequency domain results.
See :meth:`plot_frequencies` for the optional arguments.
.. plot::
:width: 80%
:include-source:
from spectrum.window import Window
w = Window(64, name='hamming')
w.plot_time_fre... |
def rsky_lhood(self,rsky,**kwargs):
"""
Evaluates Rsky likelihood at provided position(s)
:param rsky:
position
:param **kwargs:
Keyword arguments passed to :func:`BinaryPopulation.rsky_distribution`
"""
dist = self.rsky_distribution(**kwargs)
... | Evaluates Rsky likelihood at provided position(s)
:param rsky:
position
:param **kwargs:
Keyword arguments passed to :func:`BinaryPopulation.rsky_distribution` |
def get_limits(self):
"""
Return all known limits for this service, as a dict of their names
to :py:class:`~.AwsLimit` objects.
:returns: dict of limit names to :py:class:`~.AwsLimit` objects
:rtype: dict
"""
logger.debug("Gathering %s's limits from AWS", self.se... | Return all known limits for this service, as a dict of their names
to :py:class:`~.AwsLimit` objects.
:returns: dict of limit names to :py:class:`~.AwsLimit` objects
:rtype: dict |
def instr(str, substr):
"""
Locate the position of the first occurrence of substr column in the given string.
Returns null if either of the arguments are null.
.. note:: The position is not zero based, but 1 based index. Returns 0 if substr
could not be found in str.
>>> df = spark.createD... | Locate the position of the first occurrence of substr column in the given string.
Returns null if either of the arguments are null.
.. note:: The position is not zero based, but 1 based index. Returns 0 if substr
could not be found in str.
>>> df = spark.createDataFrame([('abcd',)], ['s',])
>>... |
def home(self):
""" Homes the robot.
"""
self._log.debug("home")
self._location_cache = None
self._hw_manager.hardware.home() | Homes the robot. |
def read_dynamic_inasafe_field(inasafe_fields, dynamic_field, black_list=None):
"""Helper to read inasafe_fields using a dynamic field.
:param inasafe_fields: inasafe_fields keywords to use.
:type inasafe_fields: dict
:param dynamic_field: The dynamic field to use.
:type dynamic_field: safe.defini... | Helper to read inasafe_fields using a dynamic field.
:param inasafe_fields: inasafe_fields keywords to use.
:type inasafe_fields: dict
:param dynamic_field: The dynamic field to use.
:type dynamic_field: safe.definitions.fields
:param black_list: A list of fields which are conflicting with the dy... |
def init(self, left_end_needle, right_end_needle):
"""Initialize the StartRequest with start and stop needle.
:raises TypeError: if the arguments are not integers
:raises ValueError: if the values do not match the
:ref:`specification <m4-01>`
"""
if not isinstance(left... | Initialize the StartRequest with start and stop needle.
:raises TypeError: if the arguments are not integers
:raises ValueError: if the values do not match the
:ref:`specification <m4-01>` |
def wwpn_free_if_allocated(self, wwpn):
"""
Free a WWPN allocated with :meth:`wwpn_alloc`.
If the WWPN is not currently allocated or not in the pool
range, nothing happens.
Parameters:
WWPN (string): The WWPN as 16 hexadecimal digits.
"""
wwpn_int = i... | Free a WWPN allocated with :meth:`wwpn_alloc`.
If the WWPN is not currently allocated or not in the pool
range, nothing happens.
Parameters:
WWPN (string): The WWPN as 16 hexadecimal digits. |
def s(*members: T, meta=None) -> Set[T]:
"""Creates a new set from members."""
return Set(pset(members), meta=meta) | Creates a new set from members. |
def calc_mean_std(c0, c1=[], nonStdZero=False):
""" Calculates both the mean of the data. """
mi = calc_mean(c0, c1)
std = calc_std(c0, c1)
if (nonStdZero):
std[std == 0] = 1
return mi, std | Calculates both the mean of the data. |
def parse_otu_list(lines, precision=0.0049):
"""Parser for mothur *.list file
To ensure all distances are of type float, the parser returns a
distance of 0.0 for the unique groups. However, if some sequences
are very similar, mothur may return a grouping at zero distance.
What Mothur really means ... | Parser for mothur *.list file
To ensure all distances are of type float, the parser returns a
distance of 0.0 for the unique groups. However, if some sequences
are very similar, mothur may return a grouping at zero distance.
What Mothur really means by this, however, is that the clustering
is at t... |
def _get_sghead(expnum):
"""
Use the data web service to retrieve the stephen's astrometric header.
:param expnum: CFHT exposure number you want the header for
:rtype : list of astropy.io.fits.Header objects.
"""
version = 'p'
key = "{}{}".format(expnum, version)
if key in sgheaders:
... | Use the data web service to retrieve the stephen's astrometric header.
:param expnum: CFHT exposure number you want the header for
:rtype : list of astropy.io.fits.Header objects. |
def mutate_add_connection(self, config):
"""
Attempt to add a new connection, the only restriction being that the output
node cannot be one of the network input pins.
"""
possible_outputs = list(iterkeys(self.nodes))
out_node = choice(possible_outputs)
possible_i... | Attempt to add a new connection, the only restriction being that the output
node cannot be one of the network input pins. |
def is_bare(self):
"""
:data:`True` if the repository has no working tree, :data:`False` if it does.
The value of this property is computed by running the ``hg id`` command
to check whether the special global revision id ``000000000000`` is
reported.
"""
# Make s... | :data:`True` if the repository has no working tree, :data:`False` if it does.
The value of this property is computed by running the ``hg id`` command
to check whether the special global revision id ``000000000000`` is
reported. |
def set_time_function(self, function):
"""
Set time function to be used.
:param function: callable function
:return: Nothing
:raises: ValueError if function is not types.FunctionType.
"""
if isinstance(function, types.FunctionType):
self.get_time = fu... | Set time function to be used.
:param function: callable function
:return: Nothing
:raises: ValueError if function is not types.FunctionType. |
def _match(names):
'''
Since pkg_delete requires the full "pkgname-version" string, this function
will attempt to match the package name with its version. Returns a list of
partial matches and package names that match the "pkgname-version" string
required by pkg_delete, and a list of errors encounte... | Since pkg_delete requires the full "pkgname-version" string, this function
will attempt to match the package name with its version. Returns a list of
partial matches and package names that match the "pkgname-version" string
required by pkg_delete, and a list of errors encountered. |
def CaptureVariableInternal(self, value, depth, limits, can_enqueue=True):
"""Captures a single nameless object into Variable message.
TODO(vlif): safely evaluate iterable types.
TODO(vlif): safely call str(value)
Args:
value: data to capture
depth: nested depth of dictionaries and vectors... | Captures a single nameless object into Variable message.
TODO(vlif): safely evaluate iterable types.
TODO(vlif): safely call str(value)
Args:
value: data to capture
depth: nested depth of dictionaries and vectors so far.
limits: Per-object limits for capturing variable data.
can_en... |
def _new_stream(self, idx):
"""Activate a new stream, given the index into the stream pool.
BaseMux's _new_stream simply chooses a new stream and activates it.
For special behavior (ie Weighted streams), you must override this
in a child class.
Parameters
----------
... | Activate a new stream, given the index into the stream pool.
BaseMux's _new_stream simply chooses a new stream and activates it.
For special behavior (ie Weighted streams), you must override this
in a child class.
Parameters
----------
idx : int, [0:n_streams - 1]
... |
def validate_reference(self, reference: ReferenceDefinitionType) -> Optional[Path]:
""" Converts reference to :class:`Path <pathlib.Path>`
:raise ValueError: If ``reference`` can't be converted to :class:`Path <pathlib.Path>`.
"""
if reference is not None:
if isinstance(refe... | Converts reference to :class:`Path <pathlib.Path>`
:raise ValueError: If ``reference`` can't be converted to :class:`Path <pathlib.Path>`. |
def attack_batch(self, imgs, labs):
"""
Run the attack on a batch of instance and labels.
"""
def compare(x, y):
if not isinstance(x, (float, int, np.int64)):
x = np.copy(x)
if self.TARGETED:
x[y] -= self.CONFIDENCE
else:
x[y] += self.CONFIDENCE
... | Run the attack on a batch of instance and labels. |
def write_classes(self, diagram):
"""write a class diagram"""
# sorted to get predictable (hence testable) results
for i, obj in enumerate(sorted(diagram.objects, key=lambda x: x.title)):
self.printer.emit_node(i, **self.get_values(obj))
obj.fig_id = i
# inheritan... | write a class diagram |
def interpolation_bilinear(x, y, x1, x2, y1, y2, z11, z21, z22, z12):
'''
The points (x_i, y_i) and values z_ij are connected as follows:
Starting from lower left going in mathematically positive direction, i.e. counter clockwise.
Therefore: (x1,y1,z11), (x2,y1,z21), (x2,y2,z22), (x1,y2,z12).
'''
... | The points (x_i, y_i) and values z_ij are connected as follows:
Starting from lower left going in mathematically positive direction, i.e. counter clockwise.
Therefore: (x1,y1,z11), (x2,y1,z21), (x2,y2,z22), (x1,y2,z12). |
def rebind(self, column=None, brew='GnBu'):
"""Bind a new column to the data map
Parameters
----------
column: str, default None
Pandas DataFrame column name
brew: str, default None
Color brewer abbreviation. See colors.py
"""
self.data['... | Bind a new column to the data map
Parameters
----------
column: str, default None
Pandas DataFrame column name
brew: str, default None
Color brewer abbreviation. See colors.py |
def make_gaussian_prf_sources_image(shape, source_table):
"""
Make an image containing 2D Gaussian sources.
Parameters
----------
shape : 2-tuple of int
The shape of the output 2D image.
source_table : `~astropy.table.Table`
Table of parameters for the Gaussian sources. Each r... | Make an image containing 2D Gaussian sources.
Parameters
----------
shape : 2-tuple of int
The shape of the output 2D image.
source_table : `~astropy.table.Table`
Table of parameters for the Gaussian sources. Each row of the
table corresponds to a Gaussian source whose paramet... |
def list_secrets(self, secure_data_path):
"""Return json secrets based on the secure_data_path, this will list keys in a folder"""
# Because of the addition of versionId and the way URLs are constructed, secure_data_path should
# always end in a '/'.
secure_data_path = self._add_slash(... | Return json secrets based on the secure_data_path, this will list keys in a folder |
def run_simulations(self, parameter_list, data_folder):
"""
This function runs multiple simulations in parallel.
Args:
parameter_list (list): list of parameter combinations to simulate.
data_folder (str): folder in which to create output folders.
"""
self... | This function runs multiple simulations in parallel.
Args:
parameter_list (list): list of parameter combinations to simulate.
data_folder (str): folder in which to create output folders. |
def walk(self):
"""Return view on configured steps slice.
Other Parameters:
conf.core.snapshots: the slice of snapshots.
conf.core.timesteps: the slice of timesteps.
"""
if conf.core.snapshots is not None:
return self.snaps[conf.core.snapshots]
... | Return view on configured steps slice.
Other Parameters:
conf.core.snapshots: the slice of snapshots.
conf.core.timesteps: the slice of timesteps. |
def get_nve_vni_switch_bindings(vni, switch_ip):
"""Return the nexus nve binding(s) per switch."""
LOG.debug("get_nve_vni_switch_bindings() called")
session = bc.get_reader_session()
try:
return (session.query(nexus_models_v2.NexusNVEBinding).
filter_by(vni=vni, switch_ip=switch_... | Return the nexus nve binding(s) per switch. |
def MakeSuiteFromList(t, name=''):
"""Makes a suite from an unsorted sequence of values.
Args:
t: sequence of numbers
name: string name for this suite
Returns:
Suite object
"""
hist = MakeHistFromList(t)
d = hist.GetDict()
return MakeSuiteFromDict(d) | Makes a suite from an unsorted sequence of values.
Args:
t: sequence of numbers
name: string name for this suite
Returns:
Suite object |
def on_slice(self, node): # ():('lower', 'upper', 'step')
"""Simple slice."""
return slice(self.run(node.lower),
self.run(node.upper),
self.run(node.step)) | Simple slice. |
def exception_handler(exc, context):
"""
Returns the response that should be used for any given exception.
By default we handle the REST framework `APIException`, and also
Django's built-in `Http404` and `PermissionDenied` exceptions.
Any unhandled exceptions may return `None`, which will cause a ... | Returns the response that should be used for any given exception.
By default we handle the REST framework `APIException`, and also
Django's built-in `Http404` and `PermissionDenied` exceptions.
Any unhandled exceptions may return `None`, which will cause a 500 error
to be raised. |
def _is_compact_jws(self, jws):
"""
Check if we've got a compact signed JWT
:param jws: The message
:return: True/False
"""
try:
jwt = JWSig().unpack(jws)
except Exception as err:
logger.warning('Could not parse JWS: {}'.format(err))
... | Check if we've got a compact signed JWT
:param jws: The message
:return: True/False |
def serialize_parameters(self):
"""
Get the parameter data in its serialized form.
Data is serialized by each parameter's :meth:`Parameter.serialize`
implementation.
:return: serialized parameter data in the form: ``{<name>: <serial data>, ...}``
:rtype: :class:`dict`
... | Get the parameter data in its serialized form.
Data is serialized by each parameter's :meth:`Parameter.serialize`
implementation.
:return: serialized parameter data in the form: ``{<name>: <serial data>, ...}``
:rtype: :class:`dict` |
def get_comments_are_open(instance):
"""
Check if comments are open for the instance
"""
if not IS_INSTALLED:
return False
try:
# Get the moderator which is installed for this model.
mod = moderator._registry[instance.__class__]
except KeyError:
# No moderator = ... | Check if comments are open for the instance |
def create_timeline(self, timeline, scope_identifier, hub_name, plan_id):
"""CreateTimeline.
:param :class:`<Timeline> <azure.devops.v5_0.task.models.Timeline>` timeline:
:param str scope_identifier: The project GUID to scope the request
:param str hub_name: The name of the server hub: "... | CreateTimeline.
:param :class:`<Timeline> <azure.devops.v5_0.task.models.Timeline>` timeline:
:param str scope_identifier: The project GUID to scope the request
:param str hub_name: The name of the server hub: "build" for the Build server or "rm" for the Release Management server
:param ... |
def wait_until_done(self):
"""
This method will not return until the job is either complete or has
reached an error state. This queries the server periodically to check
for an update in status.
"""
wait = 1
while True:
time.sleep(wait)
self... | This method will not return until the job is either complete or has
reached an error state. This queries the server periodically to check
for an update in status. |
def get_config(self):
"""Save configurations of metric. Can be recreated
from configs with metric.create(``**config``)
"""
config = self._kwargs.copy()
config.update({
'metric': self.__class__.__name__,
'name': self.name,
'output_names': self.o... | Save configurations of metric. Can be recreated
from configs with metric.create(``**config``) |
def update_name(self, force=False, create_term=False, report_unchanged=True):
"""Generate the Root.Name term from DatasetName, Version, Origin, TIme and Space"""
updates = []
self.ensure_identifier()
name_term = self.find_first('Root.Name')
if not name_term:
if cr... | Generate the Root.Name term from DatasetName, Version, Origin, TIme and Space |
def get_container_host_config_kwargs(self, action, container_name, kwargs=None):
"""
Generates keyword arguments for the Docker client to set up the HostConfig or start a container.
:param action: Action configuration.
:type action: ActionConfig
:param container_name: Container ... | Generates keyword arguments for the Docker client to set up the HostConfig or start a container.
:param action: Action configuration.
:type action: ActionConfig
:param container_name: Container name or id. Set ``None`` when included in kwargs for ``create_container``.
:type container_na... |
def delete(self, path=None, method='DELETE', **options):
""" Equals :meth:`route` with a ``DELETE`` method parameter. """
return self.route(path, method, **options) | Equals :meth:`route` with a ``DELETE`` method parameter. |
def error_name(self) :
"the error name for a DBUS.MESSAGE_TYPE_ERROR message."
result = dbus.dbus_message_get_error_name(self._dbobj)
if result != None :
result = result.decode()
#end if
return \
result | the error name for a DBUS.MESSAGE_TYPE_ERROR message. |
def __create_file_name(self, message_no):
""" Create the filename to save to """
cwd = os.getcwd()
filename = '{0}_{1}.xml'.format(self.output_prefix, message_no)
return os.path.join(cwd, filename) | Create the filename to save to |
def trim_wav_sox(in_path: Path, out_path: Path,
start_time: int, end_time: int) -> None:
""" Crops the wav file at in_fn so that the audio between start_time and
end_time is output to out_fn. Measured in milliseconds.
"""
if out_path.is_file():
logger.info("Output path %s alrea... | Crops the wav file at in_fn so that the audio between start_time and
end_time is output to out_fn. Measured in milliseconds. |
def accept_moderator_invite(self, subreddit):
"""Accept a moderator invite to the given subreddit.
Callable upon an instance of Subreddit with no arguments.
:returns: The json response from the server.
"""
data = {'r': six.text_type(subreddit)}
# Clear moderated subred... | Accept a moderator invite to the given subreddit.
Callable upon an instance of Subreddit with no arguments.
:returns: The json response from the server. |
def class_logit(layer, label):
"""Like channel, but for softmax layers.
Args:
layer: A layer name string.
label: Either a string (refering to a label in model.labels) or an int
label position.
Returns:
Objective maximizing a logit.
"""
def inner(T):
if isinstance(label, int):
cla... | Like channel, but for softmax layers.
Args:
layer: A layer name string.
label: Either a string (refering to a label in model.labels) or an int
label position.
Returns:
Objective maximizing a logit. |
def equal_set(self, a, b):
"See if a and b have the same elements"
if len(a) != len(b):
return 0
if a == b:
return 1
return self.subset(a, b) and self.subset(b, a) | See if a and b have the same elements |
def _eb_env_tags(envs, session_factory, retry):
"""Augment ElasticBeanstalk Environments with their tags."""
client = local_session(session_factory).client('elasticbeanstalk')
def process_tags(eb_env):
try:
eb_env['Tags'] = retry(
client.list_tags_for_resource,
... | Augment ElasticBeanstalk Environments with their tags. |
def _encode_ids(*args):
"""
Do url-encode resource ids
"""
ids = []
for v in args:
if isinstance(v, basestring):
qv = v.encode('utf-8') if isinstance(v, unicode) else v
ids.append(urllib.quote(qv))
else:
qv = str(v)
ids.append(urllib.q... | Do url-encode resource ids |
def fft_propagate(fftfield, d, nm, res, method="helmholtz",
ret_fft=False):
"""Propagates a 1D or 2D Fourier transformed field
Parameters
----------
fftfield : 1-dimensional or 2-dimensional ndarray
Fourier transform of 1D Electric field component
d : float
Distan... | Propagates a 1D or 2D Fourier transformed field
Parameters
----------
fftfield : 1-dimensional or 2-dimensional ndarray
Fourier transform of 1D Electric field component
d : float
Distance to be propagated in pixels (negative for backwards)
nm : float
Refractive index of med... |
def bland_altman(x, y, interval=None, indep_conf=None, ax=None, c=None, **kwargs):
"""
Draw a Bland-Altman plot of x and y data.
https://en.wikipedia.org/wiki/Bland%E2%80%93Altman_plot
Parameters
----------
x, y : array-like
x and y data to compare.
interval : float
... | Draw a Bland-Altman plot of x and y data.
https://en.wikipedia.org/wiki/Bland%E2%80%93Altman_plot
Parameters
----------
x, y : array-like
x and y data to compare.
interval : float
Percentile band to draw on the residuals.
indep_conf : float
Independently determi... |
def _log_board_ports(self, ports):
"""
A board with no ports is allowed.
In the logfile, ports must be sorted
- ascending by tile identifier (primary)
- alphabetical by edge direction (secondary)
:param ports: list of catan.board.Port objects
"""
ports =... | A board with no ports is allowed.
In the logfile, ports must be sorted
- ascending by tile identifier (primary)
- alphabetical by edge direction (secondary)
:param ports: list of catan.board.Port objects |
def _get_binary_from_ipv4(self, ip_addr):
"""Converts IPv4 address to binary form."""
return struct.unpack("!L", socket.inet_pton(socket.AF_INET,
ip_addr))[0] | Converts IPv4 address to binary form. |
def gru_state_tuples(num_nodes, name):
"""Convenience so that the names of the vars are defined in the same file."""
if not isinstance(num_nodes, tf.compat.integral_types):
raise ValueError('num_nodes must be an integer: %s' % num_nodes)
return [(STATE_NAME % name + '_0', tf.float32, num_nodes)] | Convenience so that the names of the vars are defined in the same file. |
def register(self, src, trg, trg_mask=None, src_mask=None):
""" Implementation of pair-wise registration using thunder-registration
For more information on the model estimation, refer to https://github.com/thunder-project/thunder-registration
This function takes two 2D single channel images and... | Implementation of pair-wise registration using thunder-registration
For more information on the model estimation, refer to https://github.com/thunder-project/thunder-registration
This function takes two 2D single channel images and estimates a 2D translation that best aligns the pair. The
estim... |
def refresh_from_server(self):
"""Refresh the group from the server in place."""
group = self.manager.get(id=self.id)
self.__init__(self.manager, **group.data) | Refresh the group from the server in place. |
def prepped_value(self):
"""
Returns the value after being processed by the internationalized string
preparation as specified by RFC 5280
:return:
A unicode string
"""
if self._prepped is None:
self._prepped = self._ldap_string_prep(self['value']... | Returns the value after being processed by the internationalized string
preparation as specified by RFC 5280
:return:
A unicode string |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.