code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def _service_is_sysv(name):
'''
A System-V style service will have a control script in
/etc/init.d. We make sure to skip over symbolic links that point
to Upstart's /lib/init/upstart-job, and anything that isn't an
executable, like README or skeleton.
'''
script = '/etc/init.d/{0}'.format(na... | A System-V style service will have a control script in
/etc/init.d. We make sure to skip over symbolic links that point
to Upstart's /lib/init/upstart-job, and anything that isn't an
executable, like README or skeleton. |
def current(self):
"""
Currently active item on the _timeline Canvas
:rtype: str
"""
results = self._timeline.find_withtag(tk.CURRENT)
return results[0] if len(results) != 0 else None | Currently active item on the _timeline Canvas
:rtype: str |
def kde_peak(self, name, npoints=_npoints, **kwargs):
"""
Calculate peak of kernel density estimator
"""
data = self.get(name,**kwargs)
return kde_peak(data,npoints) | Calculate peak of kernel density estimator |
def pop_empty_columns(self, empty=None):
"""
This will pop columns from the printed columns if they only contain
'' or None
:param empty: list of values to treat as empty
"""
empty = ['', None] if empty is None else empty
if len(self) == 0:
ret... | This will pop columns from the printed columns if they only contain
'' or None
:param empty: list of values to treat as empty |
def get_join_cols(by_entry):
""" helper function used for joins
builds left and right join list for join function
"""
left_cols = []
right_cols = []
for col in by_entry:
if isinstance(col, str):
left_cols.append(col)
right_cols.append(col)
else:
left_cols.append(col[0])
right... | helper function used for joins
builds left and right join list for join function |
def recarray(self):
"""Returns data as :class:`numpy.recarray`."""
return numpy.rec.fromrecords(self.records, names=self.names) | Returns data as :class:`numpy.recarray`. |
def order_replicant_volume(self, volume_id, snapshot_schedule,
location, tier=None):
"""Places an order for a replicant file volume.
:param volume_id: The ID of the primary volume to be replicated
:param snapshot_schedule: The primary volume's snapshot
... | Places an order for a replicant file volume.
:param volume_id: The ID of the primary volume to be replicated
:param snapshot_schedule: The primary volume's snapshot
schedule to use for replication
:param location: The location for the ordered replicant volume
... |
def _lookup_user_data(self,*args,**kwargs):
"""
Generic function for looking up values in
a user-specific dictionary. Use as follows::
_lookup_user_data('path','to','desired','value','in','dictionary',
default = <default value>,
... | Generic function for looking up values in
a user-specific dictionary. Use as follows::
_lookup_user_data('path','to','desired','value','in','dictionary',
default = <default value>,
data_kind = 'customization'/'saved_searches') |
def mv_to_pypsa(network):
"""Translate MV grid topology representation to PyPSA format
MV grid topology translated here includes
* MV station (no transformer, see :meth:`~.grid.network.EDisGo.analyze`)
* Loads, Generators, Lines, Storages, Branch Tees of MV grid level as well
as LV stations. LV ... | Translate MV grid topology representation to PyPSA format
MV grid topology translated here includes
* MV station (no transformer, see :meth:`~.grid.network.EDisGo.analyze`)
* Loads, Generators, Lines, Storages, Branch Tees of MV grid level as well
as LV stations. LV stations do not have load and gen... |
async def answer(self, text: typing.Union[base.String, None] = None,
show_alert: typing.Union[base.Boolean, None] = None,
url: typing.Union[base.String, None] = None,
cache_time: typing.Union[base.Integer, None] = None):
"""
Use this method ... | Use this method to send answers to callback queries sent from inline keyboards.
The answer will be displayed to the user as a notification at the top of the chat screen or as an alert.
Alternatively, the user can be redirected to the specified Game URL.
For this option to work, you must first c... |
def start(port, root_directory, bucket_depth):
"""Starts the mock S3 server on the given port at the given path."""
application = S3Application(root_directory, bucket_depth)
http_server = httpserver.HTTPServer(application)
http_server.listen(port)
ioloop.IOLoop.current().start() | Starts the mock S3 server on the given port at the given path. |
def setup_sanitize_files(self):
"""
For each of the sanitize files that were specified as command line options
load the contents of the file into the sanitise patterns dictionary.
"""
for fname in self.get_sanitize_files():
with open(fname, 'r') as f:
... | For each of the sanitize files that were specified as command line options
load the contents of the file into the sanitise patterns dictionary. |
def lookup_genome_alignment_index(index_fh, indexed_fh, out_fh=sys.stdout,
key=None, verbose=False):
"""Load a GA index and its indexed file and extract one or more blocks.
:param index_fh: the index file to load. Can be a filename or a
stream-like object.
... | Load a GA index and its indexed file and extract one or more blocks.
:param index_fh: the index file to load. Can be a filename or a
stream-like object.
:param indexed_fh: the file that the index was built for,
:param key: A single key, iterable of keys, or None. This key will be
... |
def _create_client(base_url: str, tls: TLSConfig=False) -> Optional[APIClient]:
"""
Creates a Docker client with the given details.
:param base_url: the base URL of the Docker daemon
:param tls: the Docker daemon's TLS config (if any)
:return: the created client else None if unable to connect the cl... | Creates a Docker client with the given details.
:param base_url: the base URL of the Docker daemon
:param tls: the Docker daemon's TLS config (if any)
:return: the created client else None if unable to connect the client to the daemon |
def volume_percentage_used(self, volume):
"""Total used size in percentage for volume"""
volume = self._get_volume(volume)
if volume is not None:
total = int(volume["size"]["total"])
used = int(volume["size"]["used"])
if used is not None and used > 0 a... | Total used size in percentage for volume |
def get_theme(self):
"""
Gets theme settings from settings service. Falls back to default (LMS) theme
if settings service is not available, xblock theme settings are not set or does
contain mentoring theme settings.
"""
xblock_settings = self.get_xblock_settings(default={... | Gets theme settings from settings service. Falls back to default (LMS) theme
if settings service is not available, xblock theme settings are not set or does
contain mentoring theme settings. |
def add_to_queue(self, series):
"""Add a series to the queue
@param crunchyroll.models.Series series
@return bool
"""
result = self._android_api.add_to_queue(series_id=series.series_id)
return result | Add a series to the queue
@param crunchyroll.models.Series series
@return bool |
def MoveToAttributeNo(self, no):
"""Moves the position of the current instance to the attribute
with the specified index relative to the containing element. """
ret = libxml2mod.xmlTextReaderMoveToAttributeNo(self._o, no)
return ret | Moves the position of the current instance to the attribute
with the specified index relative to the containing element. |
def get_family_hierarchy_session(self, proxy):
"""Gets the ``OsidSession`` associated with the family hierarchy service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.relationship.FamilyHierarchySession) - a
``FamilyHierarchySession`` for families
raise: NullA... | Gets the ``OsidSession`` associated with the family hierarchy service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.relationship.FamilyHierarchySession) - a
``FamilyHierarchySession`` for families
raise: NullArgument - ``proxy`` is ``null``
raise: OperationF... |
def _write(self, _new=False):
"""Writes the values of the attributes to the datastore.
This method also creates the indices and saves the lists
associated to the object.
"""
pipeline = self.db.pipeline()
self._create_membership(pipeline)
self._update_indices(pipe... | Writes the values of the attributes to the datastore.
This method also creates the indices and saves the lists
associated to the object. |
def handle_delete(self):
"""Handle a graduated user being deleted."""
from intranet.apps.eighth.models import EighthScheduledActivity
EighthScheduledActivity.objects.filter(eighthsignup_set__user=self).update(
archived_member_count=F('archived_member_count')+1) | Handle a graduated user being deleted. |
def find_stream(self, **kwargs):
"""
Finds a single stream with the given meta data values. Useful for debugging purposes.
:param kwargs: The meta data as keyword arguments
:return: The stream found
"""
found = list(self.find_streams(**kwargs).values())
if not fo... | Finds a single stream with the given meta data values. Useful for debugging purposes.
:param kwargs: The meta data as keyword arguments
:return: The stream found |
def box_plot(x, y, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT):
"""
Plots the data in `x` on the X axis and the data in `y` on the Y axis
in a 2d box and whiskers plot, and returns the resulting Plot object.
The function x as SArray of dtype str and y as SArray of dtype: int, f... | Plots the data in `x` on the X axis and the data in `y` on the Y axis
in a 2d box and whiskers plot, and returns the resulting Plot object.
The function x as SArray of dtype str and y as SArray of dtype: int, float.
Parameters
----------
x : SArray
The data to plot on the X axis of the b... |
def set_tolerance(self, tolerance):
"""Sets the tolerance used when converting paths into trapezoids.
Curved segments of the path will be subdivided
until the maximum deviation between the original path
and the polygonal approximation is less than tolerance.
The default value is ... | Sets the tolerance used when converting paths into trapezoids.
Curved segments of the path will be subdivided
until the maximum deviation between the original path
and the polygonal approximation is less than tolerance.
The default value is 0.1.
A larger value will give better pe... |
def create_device_enrollment(self, enrollment_identity, **kwargs): # noqa: E501
"""Place an enrollment claim for one or several devices. # noqa: E501
When the device connects to the bootstrap server and provides the enrollment ID, it will be assigned to your account. <br> **Example usage:** ``` curl ... | Place an enrollment claim for one or several devices. # noqa: E501
When the device connects to the bootstrap server and provides the enrollment ID, it will be assigned to your account. <br> **Example usage:** ``` curl -X POST \\ -H 'Authorization: Bearer <valid access token>' \\ -H 'content-type: application/... |
def workflow_get_details(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /workflow-xxxx/getDetails API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Details-and-Links#API-method%3A-%2Fclass-xxxx%2FgetDetails
"""
return DXHTTPRequest('/%s/ge... | Invokes the /workflow-xxxx/getDetails API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Details-and-Links#API-method%3A-%2Fclass-xxxx%2FgetDetails |
def cleanup():
"""Delete standard installation directories."""
for install_dir in linters.INSTALL_DIRS:
try:
shutil.rmtree(install_dir, ignore_errors=True)
except Exception:
print(
"{0}\nFailed to delete {1}".format(
... | Delete standard installation directories. |
def strip_lastharaka(text):
"""Strip the last Haraka from arabic word except Shadda.
The striped marks are :
- FATHA, DAMMA, KASRA
- SUKUN
- FATHATAN, DAMMATAN, KASRATAN
@param text: arabic text.
@type text: unicode.
@return: return a striped text.
@rtype: unicode.
... | Strip the last Haraka from arabic word except Shadda.
The striped marks are :
- FATHA, DAMMA, KASRA
- SUKUN
- FATHATAN, DAMMATAN, KASRATAN
@param text: arabic text.
@type text: unicode.
@return: return a striped text.
@rtype: unicode. |
def _get_table_cells(table):
"""Helper function with caching for table cells and the cells' sentences.
This function significantly improves the speed of `get_row_ngrams`
primarily by reducing the number of queries that are made (which were
previously the bottleneck. Rather than taking a single mention,... | Helper function with caching for table cells and the cells' sentences.
This function significantly improves the speed of `get_row_ngrams`
primarily by reducing the number of queries that are made (which were
previously the bottleneck. Rather than taking a single mention, then its
sentence, then its tab... |
def load_bytes(self,
bytes_data,
key,
bucket_name=None,
replace=False,
encrypt=False):
"""
Loads bytes to S3
This is provided as a convenience to drop a string in S3. It uses the
boto infrastr... | Loads bytes to S3
This is provided as a convenience to drop a string in S3. It uses the
boto infrastructure to ship a file to s3.
:param bytes_data: bytes to set as content for the key.
:type bytes_data: bytes
:param key: S3 key that will point to the file
:type key: st... |
def from_string(s):
"""Deserializes a token from a string like one returned by
`to_string()`."""
if not len(s):
raise ValueError("Invalid parameter string.")
params = parse_qs(u(s), keep_blank_values=False)
if not len(params):
raise ValueError("Invalid p... | Deserializes a token from a string like one returned by
`to_string()`. |
def get_ip_address_list(list_name):
'''
Retrieves a specific IP address list.
list_name(str): The name of the specific policy IP address list to retrieve.
CLI Example:
.. code-block:: bash
salt '*' bluecoat_sslv.get_ip_address_list MyIPAddressList
'''
payload = {"jsonrpc": "2.0"... | Retrieves a specific IP address list.
list_name(str): The name of the specific policy IP address list to retrieve.
CLI Example:
.. code-block:: bash
salt '*' bluecoat_sslv.get_ip_address_list MyIPAddressList |
def _get_or_insert_async(*args, **kwds):
"""Transactionally retrieves an existing entity or creates a new one.
This is the asynchronous version of Model._get_or_insert().
"""
# NOTE: The signature is really weird here because we want to support
# models with properties named e.g. 'cls' or 'name'.
... | Transactionally retrieves an existing entity or creates a new one.
This is the asynchronous version of Model._get_or_insert(). |
def __get_container_path(self, host_path):
""" A simple helper function to determine the path of a host library
inside the container
:param host_path: The path of the library on the host
:type host_path: str
"""
libname = os.path.split(host_path)[1]
return os.path.join(_container_lib_locati... | A simple helper function to determine the path of a host library
inside the container
:param host_path: The path of the library on the host
:type host_path: str |
def exec(self, *command_tokens, command_context=None, **command_env):
""" Execute command
:param command_tokens: command tokens to execute
:param command_context: command context
:param command_env: command environment
:return: WCommandResultProto
"""
if self.adapter().match(command_context, **command_en... | Execute command
:param command_tokens: command tokens to execute
:param command_context: command context
:param command_env: command environment
:return: WCommandResultProto |
def main():
"""
process the main task
"""
args = get_args()
args.start = date_parser.parse(args.start)
args.end = date_parser.parse(args.end)
args.step = timedelta(args.step)
config = Config(args.config)
times = [args.start + i * args.step for i in range(int((args.end - args.start) ... | process the main task |
def recv(self, size = None):
""" Receive a buffer. The default size is 1500, the
classical MTU.
"""
size = size if size is not None else 1500
return os.read(self.fd, size) | Receive a buffer. The default size is 1500, the
classical MTU. |
def execute_update(self, update, safe=False):
''' Execute an update expression. Should generally only be called implicitly.
'''
# safe = self.safe
# if update.safe is not None:
# safe = remove.safe
assert len(update.update_data) > 0
self.queue.append(UpdateOp(self.transaction_id, self, update.query... | Execute an update expression. Should generally only be called implicitly. |
def series(self, x: str, y: list, title: str = '') -> object:
"""
This method plots a series of x,y coordinates. You can provide a list of y columns for multiple line plots.
:param x: the x axis variable; generally a time or continuous variable.
:param y: the y axis variable(s), you can... | This method plots a series of x,y coordinates. You can provide a list of y columns for multiple line plots.
:param x: the x axis variable; generally a time or continuous variable.
:param y: the y axis variable(s), you can specify a single column or a list of columns
:param title: an optional Ti... |
def add_volume(self, hostpath, contpath, options=None):
'''Add a volume (bind-mount) to the docker run invocation
'''
if options is None:
options = []
self.volumes.append((hostpath, contpath, options)) | Add a volume (bind-mount) to the docker run invocation |
def forwards(apps, schema_editor):
"""
Create sample events.
"""
starts = timeutils.round_datetime(
when=timezone.now(),
precision=timedelta(days=1),
rounding=timeutils.ROUND_DOWN)
ends = starts + appsettings.DEFAULT_ENDS_DELTA
recurrence_rules = dict(
Recurrence... | Create sample events. |
def PopState(self, **_):
"""Pop the previous state from the stack."""
try:
self.state = self.state_stack.pop()
if self.verbose:
logging.debug("Returned state to %s", self.state)
return self.state
except IndexError:
self.Error("Tried to pop the state but failed - possible rec... | Pop the previous state from the stack. |
def read_annotations(path_or_file, separator='\t', reset=True):
"""
Read all annotations from the specified file.
>>> annotations = read_annotations(path_or_file, separator)
>>> colnames = annotations['Column Name']
>>> types = annotations['Type']
>>> annot_row = annotations['Annot. row nam... | Read all annotations from the specified file.
>>> annotations = read_annotations(path_or_file, separator)
>>> colnames = annotations['Column Name']
>>> types = annotations['Type']
>>> annot_row = annotations['Annot. row name']
:param path_or_file: Path or file-like object
:param separator:... |
def get_data(self) -> bytes:
"""Return a compressed datablob representing this object.
To restore the object, use :func:`fints.client.NeedRetryResponse.from_data`.
"""
data = {
"_class_name": self.__class__.__name__,
"version": 1,
"segments_bi... | Return a compressed datablob representing this object.
To restore the object, use :func:`fints.client.NeedRetryResponse.from_data`. |
def get_remote(self, key, default=None, scope=None):
"""
Get data from the remote end(s) of the :class:`Conversation` with the given scope.
In Python, this is equivalent to::
relation.conversation(scope).get_remote(key, default)
See :meth:`conversation` and :meth:`Conversa... | Get data from the remote end(s) of the :class:`Conversation` with the given scope.
In Python, this is equivalent to::
relation.conversation(scope).get_remote(key, default)
See :meth:`conversation` and :meth:`Conversation.get_remote`. |
def report(self):
"""
Report usage of training parameters.
"""
if self.logger:
self.logger.info("accessed parameters:")
for key in self.used_parameters:
self.logger.info(" - %s %s" % (key, "(undefined)" if key in self.undefined_parameters else "")) | Report usage of training parameters. |
def _add_tag(self, tag):
# type: (str) -> bool
"""Add a tag
Args:
tag (str): Tag to add
Returns:
bool: True if tag added or False if tag already present
"""
tags = self.data.get('tags', None)
if tags:
if tag in [x['name'] for ... | Add a tag
Args:
tag (str): Tag to add
Returns:
bool: True if tag added or False if tag already present |
def parse_time(val, fmt=None):
"""Returns a time object parsed from :val:.
:param val: a string to be parsed as a time
:param fmt: a format string, a tuple of format strings, or None. If None a built in list of format
strings will be used to try to parse the time.
"""
if isinstance(val, time):
... | Returns a time object parsed from :val:.
:param val: a string to be parsed as a time
:param fmt: a format string, a tuple of format strings, or None. If None a built in list of format
strings will be used to try to parse the time. |
def speed(self, factor, use_semitones=False):
"""speed takes 2 parameters: factor and use-semitones (True or False).
When use-semitones = False, a factor of 2 doubles the speed and raises the pitch an octave. The same result is achieved with factor = 1200 and use semitones = True.
"""
s... | speed takes 2 parameters: factor and use-semitones (True or False).
When use-semitones = False, a factor of 2 doubles the speed and raises the pitch an octave. The same result is achieved with factor = 1200 and use semitones = True. |
def close(self):
"""close()
Disconnects the object from the bus.
"""
os.close(self._fd)
self._fd = -1
self._addr = -1
self._pec = 0 | close()
Disconnects the object from the bus. |
def from_bam(pysam_samfile, loci, normalized_contig_names=True):
'''
Create a PileupCollection for a set of loci from a BAM file.
Parameters
----------
pysam_samfile : `pysam.Samfile` instance, or filename string
to a BAM file. The BAM file must be indexed.
... | Create a PileupCollection for a set of loci from a BAM file.
Parameters
----------
pysam_samfile : `pysam.Samfile` instance, or filename string
to a BAM file. The BAM file must be indexed.
loci : list of Locus instances
Loci to collect pileups for.
norm... |
def get_connection_by_node(self, node):
"""
get a connection by node
"""
self._checkpid()
self.nodes.set_node_name(node)
try:
# Try to get connection from existing pool
connection = self._available_connections.get(node["name"], []).pop()
e... | get a connection by node |
def unwrap_or_else(self, op: Callable[[E], U]) -> Union[T, U]:
"""
Returns the sucess value in the :class:`Result` or computes a default
from the error value.
Args:
op: The function to computes default with.
Returns:
The success value in the :class:`Resu... | Returns the sucess value in the :class:`Result` or computes a default
from the error value.
Args:
op: The function to computes default with.
Returns:
The success value in the :class:`Result` if it is
a :meth:`Result.Ok` value, otherwise ``op(E)``.
... |
def _execute(self, stmt, *values):
"""
Gets a cursor, executes `stmt` and closes the cursor,
fetching one row afterwards and returning its result.
"""
c = self._cursor()
try:
return c.execute(stmt, values).fetchone()
finally:
c.close() | Gets a cursor, executes `stmt` and closes the cursor,
fetching one row afterwards and returning its result. |
def optimize(self, commit=True, waitFlush=None, waitSearcher=None, maxSegments=None, handler='update'):
"""
Tells Solr to streamline the number of segments used, essentially a
defragmentation operation.
Optionally accepts ``maxSegments``. Default is ``None``.
Optionally accepts... | Tells Solr to streamline the number of segments used, essentially a
defragmentation operation.
Optionally accepts ``maxSegments``. Default is ``None``.
Optionally accepts ``waitFlush``. Default is ``None``.
Optionally accepts ``waitSearcher``. Default is ``None``.
Usage::
... |
def get_broadcast_events(cls, script):
"""Return a Counter of event-names that were broadcast.
The Count will contain the key True if any of the broadcast blocks
contain a parameter that is a variable.
"""
events = Counter()
for name, _, block in cls.iter_blocks(script)... | Return a Counter of event-names that were broadcast.
The Count will contain the key True if any of the broadcast blocks
contain a parameter that is a variable. |
def mcmc_CH(self, walkerRatio, n_run, n_burn, mean_start, sigma_start, threadCount=1, init_pos=None, mpi=False):
"""
runs mcmc on the parameter space given parameter bounds with CosmoHammerSampler
returns the chain
"""
lowerLimit, upperLimit = self.lower_limit, self.upper_limit
... | runs mcmc on the parameter space given parameter bounds with CosmoHammerSampler
returns the chain |
def sample(self, num_samples=1000, hmc_iters=20):
"""
Sample the (unfixed) model parameters.
:param num_samples: the number of samples to draw (1000 by default)
:type num_samples: int
:param hmc_iters: the number of leap-frog iterations (20 by default)
:type hmc_... | Sample the (unfixed) model parameters.
:param num_samples: the number of samples to draw (1000 by default)
:type num_samples: int
:param hmc_iters: the number of leap-frog iterations (20 by default)
:type hmc_iters: int
:return: the list of parameters samples with the si... |
def less_strict_bool(x):
"""Idempotent and None-safe version of strict_bool."""
if x is None:
return False
elif x is True or x is False:
return x
else:
return strict_bool(x) | Idempotent and None-safe version of strict_bool. |
def invoke(self, script_hash, params, **kwargs):
""" Invokes a contract with given parameters and returns the result.
It should be noted that the name of the function invoked in the contract should be part of
paramaters.
:param script_hash: contract script hash
:param params: l... | Invokes a contract with given parameters and returns the result.
It should be noted that the name of the function invoked in the contract should be part of
paramaters.
:param script_hash: contract script hash
:param params: list of paramaters to be passed in to the smart contract
... |
def send(self, message):
"""Adds a message to the list, returning a fake 'ok' response
:returns: A response message with ``ok = True``
"""
for event in message.events:
self.events.append(event)
reply = riemann_client.riemann_pb2.Msg()
reply.ok = True
... | Adds a message to the list, returning a fake 'ok' response
:returns: A response message with ``ok = True`` |
def get_resource_component_children(self, resource_component_id):
"""
Given a resource component, fetches detailed metadata for it and all of its children.
This is implemented using ArchivesSpaceClient.get_resource_component_children and uses its default options when fetching children.
... | Given a resource component, fetches detailed metadata for it and all of its children.
This is implemented using ArchivesSpaceClient.get_resource_component_children and uses its default options when fetching children.
:param string resource_component_id: The URL of the resource component from which to ... |
def buffered_read(fh, lock, offsets, bytecounts, buffersize=None):
"""Return iterator over segments read from file."""
if buffersize is None:
buffersize = 2**26
length = len(offsets)
i = 0
while i < length:
data = []
with lock:
size = 0
while size < bu... | Return iterator over segments read from file. |
def train_model(
self,
L_train,
Y_dev=None,
deps=[],
class_balance=None,
log_writer=None,
**kwargs,
):
"""Train the model (i.e. estimate mu) in one of two ways, depending on
whether source dependencies are provided or not:
Args:
... | Train the model (i.e. estimate mu) in one of two ways, depending on
whether source dependencies are provided or not:
Args:
L_train: An [n,m] scipy.sparse matrix with values in {0,1,...,k}
corresponding to labels from supervision sources on the
training set
... |
def config_start(self):
"""
Start a configuration session.
For managing router admin functionality (ie allowing/blocking devices)
"""
_LOGGER.info("Config start")
success, _ = self._make_request(
SERVICE_DEVICE_CONFIG, "ConfigurationStarted", {"NewSessionID":... | Start a configuration session.
For managing router admin functionality (ie allowing/blocking devices) |
def change_host_check_timeperiod(self, host, timeperiod):
"""Modify host check timeperiod
Format of the line that triggers function call::
CHANGE_HOST_CHECK_TIMEPERIOD;<host_name>;<timeperiod>
:param host: host to modify check timeperiod
:type host: alignak.objects.host.Host
... | Modify host check timeperiod
Format of the line that triggers function call::
CHANGE_HOST_CHECK_TIMEPERIOD;<host_name>;<timeperiod>
:param host: host to modify check timeperiod
:type host: alignak.objects.host.Host
:param timeperiod: timeperiod object
:type timeperiod: ... |
def request_time_facet(field, time_filter, time_gap, time_limit=100):
"""
time facet query builder
:param field: map the query to this field.
:param time_limit: Non-0 triggers time/date range faceting. This value is the maximum number of time ranges to
return when a.time.gap is unspecified. This is ... | time facet query builder
:param field: map the query to this field.
:param time_limit: Non-0 triggers time/date range faceting. This value is the maximum number of time ranges to
return when a.time.gap is unspecified. This is a soft maximum; less will usually be returned.
A suggested value is 100.
N... |
def _parse_myinfo(client, command, actor, args):
"""Parse MYINFO and update the Host object."""
_, server, version, usermodes, channelmodes = args.split(None, 5)[:5]
s = client.server
s.host = server
s.version = version
s.user_modes = set(usermodes)
s.channel_modes = set(channelmodes) | Parse MYINFO and update the Host object. |
def validate_reaction(self):
"""Ensure reaction is of a certain type.
Mainly for future expansion.
"""
if self.reaction not in self._reaction_valid_values:
raise ValueError("reaction should be one of: {valid}".format(
valid=", ".join(self._reaction_valid_valu... | Ensure reaction is of a certain type.
Mainly for future expansion. |
def call(self, inpt):
"""
Returns if the condition applies to the ``inpt``.
If the class ``inpt`` is an instance of is not the same class as the
condition's own ``argument``, then ``False`` is returned. This also
applies to the ``NONE`` input.
Otherwise, ``argument`` i... | Returns if the condition applies to the ``inpt``.
If the class ``inpt`` is an instance of is not the same class as the
condition's own ``argument``, then ``False`` is returned. This also
applies to the ``NONE`` input.
Otherwise, ``argument`` is called, with ``inpt`` as the instance an... |
def get_conn(self):
"""Returns a connection object
"""
db = self.get_connection(getattr(self, self.conn_name_attr))
return self.connector.connect(
host=db.host,
port=db.port,
username=db.login,
schema=db.schema) | Returns a connection object |
def validate_brain_requirements(connection, remote_dbs, requirements):
"""
validates the rethinkdb has the 'correct' databases and tables
should get remote_dbs from brain.connection.validate_get_dbs
:param connection: <rethinkdb.net.DefaultConnection>
:param remote_dbs: <set> database names present... | validates the rethinkdb has the 'correct' databases and tables
should get remote_dbs from brain.connection.validate_get_dbs
:param connection: <rethinkdb.net.DefaultConnection>
:param remote_dbs: <set> database names present in remote database
:param requirements: <dict> example(brain.connection.SELF_T... |
def _get_top_of_rupture_depth_term(self, C, imt, rup):
"""
Compute and return top of rupture depth term. See paragraph
'Depth-to-Top of Rupture Model', page 1042.
"""
if rup.ztor >= 20.0:
return C['a15']
else:
return C['a15'] * rup.ztor / 20.0 | Compute and return top of rupture depth term. See paragraph
'Depth-to-Top of Rupture Model', page 1042. |
def dropping(n):
"""Create a transducer which drops the first n items"""
if n < 0:
raise ValueError("Cannot drop fewer than zero ({}) items".format(n))
def dropping_transducer(reducer):
return Dropping(reducer, n)
return dropping_transducer | Create a transducer which drops the first n items |
def add_filter(self, filter_or_string, *args, **kwargs):
"""
Appends a filter.
"""
self.filters.append(build_filter(filter_or_string, *args, **kwargs))
return self | Appends a filter. |
def exit_with_error(msg='Aborted', details=None, code=-1, *args, **kwargs):
'''Exit with error'''
error(msg, details=details, *args, **kwargs)
sys.exit(code) | Exit with error |
def get(key, default=None):
'''
Get a (list of) value(s) from the minion datastore
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' data.get key
salt '*' data.get '["key1", "key2"]'
'''
store = load()
if isinstance(key, six.string_types):
... | Get a (list of) value(s) from the minion datastore
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' data.get key
salt '*' data.get '["key1", "key2"]' |
def setContentsMargins(self, left, top, right, bottom):
"""
Sets the contents margins for this node to the inputed values.
:param left | <int>
top | <int>
right | <int>
bottom | <int>
"""
self._ma... | Sets the contents margins for this node to the inputed values.
:param left | <int>
top | <int>
right | <int>
bottom | <int> |
def get_url(self, resource, params=None):
"""
Generate url for request
"""
# replace placeholders
pattern = r'\{(.+?)\}'
resource = re.sub(pattern, lambda t: str(params.get(t.group(1), '')), resource)
# build url
parts = (self.endpoint, '/api/', r... | Generate url for request |
def local_histogram_equalization(data, mask_to_equalize, valid_data_mask=None, number_of_bins=1000,
std_mult_cutoff=3.0,
do_zerotoone_normalization=True,
local_radius_px=300,
clip_limit=60... | Equalize the provided data (in the mask_to_equalize) using adaptive histogram equalization.
tiles of width/height (2 * local_radius_px + 1) will be calculated and results for each pixel will be bilinerarly
interpolated from the nearest 4 tiles when pixels fall near the edge of the image (there is no adjacent t... |
def parse_inventory_category(name, info, countable=True):
"""Parses every entry in an inventory category (CPU, memory, PCI, drives,
etc).
Expects the first byte to be a count of the number of entries, followed
by a list of elements to be parsed by a dedicated parser (below).
:param name: the name ... | Parses every entry in an inventory category (CPU, memory, PCI, drives,
etc).
Expects the first byte to be a count of the number of entries, followed
by a list of elements to be parsed by a dedicated parser (below).
:param name: the name of the parameter (e.g.: "cpu")
:param info: a list of integer... |
def as_cnpjcpf(numero):
"""Formata um número de CNPJ ou CPF. Se o número não for um CNPJ ou CPF
válidos apenas retorna o argumento sem qualquer modificação.
"""
if is_cnpj(numero):
return as_cnpj(numero)
elif is_cpf(numero):
return as_cpf(numero)
return numero | Formata um número de CNPJ ou CPF. Se o número não for um CNPJ ou CPF
válidos apenas retorna o argumento sem qualquer modificação. |
def loglike(self, y, f):
r"""
Poisson log likelihood.
Parameters
----------
y: ndarray
array of integer targets
f: ndarray
latent function from the GLM prior (:math:`\mathbf{f} =
\boldsymbol\Phi \mathbf{w}`)
Returns
--... | r"""
Poisson log likelihood.
Parameters
----------
y: ndarray
array of integer targets
f: ndarray
latent function from the GLM prior (:math:`\mathbf{f} =
\boldsymbol\Phi \mathbf{w}`)
Returns
-------
logp: ndarray
... |
def return_item(self, item, priority):
"""Complete work on an item from ``check_out_item()``.
If this instance no longer owns ``item``, raise ``LostLease``.
If ``priority`` is None, the item is removed from the queue;
otherwise it is re-added with the specified priority. Any
lo... | Complete work on an item from ``check_out_item()``.
If this instance no longer owns ``item``, raise ``LostLease``.
If ``priority`` is None, the item is removed from the queue;
otherwise it is re-added with the specified priority. Any
locked items associated with this item are unlocked. |
def get_description_by_type(self, type_p):
"""This is the same as :py:func:`get_description` except that you can specify which types
should be returned.
in type_p of type :class:`VirtualSystemDescriptionType`
out types of type :class:`VirtualSystemDescriptionType`
out refs of... | This is the same as :py:func:`get_description` except that you can specify which types
should be returned.
in type_p of type :class:`VirtualSystemDescriptionType`
out types of type :class:`VirtualSystemDescriptionType`
out refs of type str
out ovf_values of type str
... |
def __prepare_info_from_dicomdir_file(self, writedicomdirfile=True):
"""
Check if exists dicomdir file and load it or cerate it
dcmdir = get_dir(dirpath)
dcmdir: list with filenames, SeriesNumber and SliceLocation
"""
createdcmdir = True
dicomdirfile = os.path.... | Check if exists dicomdir file and load it or cerate it
dcmdir = get_dir(dirpath)
dcmdir: list with filenames, SeriesNumber and SliceLocation |
def build_columns(self, X, term=-1, verbose=False):
"""construct the model matrix columns for the term
Parameters
----------
X : array-like
Input dataset with n rows
verbose : bool
whether to show warnings
Returns
-------
scipy s... | construct the model matrix columns for the term
Parameters
----------
X : array-like
Input dataset with n rows
verbose : bool
whether to show warnings
Returns
-------
scipy sparse array with n rows |
def append_from_dict(self, the_dict):
"""
Creates a ``measurement.Measurement`` object from the supplied dict
and then appends it to the buffer
:param the_dict: dict
"""
m = Measurement.from_dict(the_dict)
self.append(m) | Creates a ``measurement.Measurement`` object from the supplied dict
and then appends it to the buffer
:param the_dict: dict |
def register(handler,
op,
safe_init = None,
at_start = None,
name = None,
at_stop = None,
static = False,
root = None,
replacement = None,
charset ... | Register a command
@handler: function to execute when the command is received
@op: http method(s)
@safe_init: called by the safe_init() function of this module
@at_start: called once just before the server starts
@at_stop: called once just before the server stops
@name: name of the command (if n... |
def _get_focused_item(self):
""" Returns the currently focused item """
focused_model = self._selection.focus
if not focused_model:
return None
return self.canvas.get_view_for_model(focused_model) | Returns the currently focused item |
def imag(self, newimag):
"""Set the imaginary part of this element to ``newimag``.
This method is invoked by ``x.imag = other``.
Parameters
----------
newimag : array-like or scalar
Values to be assigned to the imaginary part of this element.
Raises
... | Set the imaginary part of this element to ``newimag``.
This method is invoked by ``x.imag = other``.
Parameters
----------
newimag : array-like or scalar
Values to be assigned to the imaginary part of this element.
Raises
------
ValueError
... |
def load(self, module_name):
"""Returns source code and normalized module id of the given module.
Only supports source code files encoded as UTF-8
"""
module_name, path = self.lookup(module_name)
if path:
with open(path, 'rb') as f:
return module_name... | Returns source code and normalized module id of the given module.
Only supports source code files encoded as UTF-8 |
def get_shards(self, *args, full_response=False):
"""Get Shards"""
resp = self.request(shards=args, full_response=full_response)
return resp | Get Shards |
def _imm_new(cls):
'''
All immutable new classes use a hack to make sure the post-init cleanup occurs.
'''
imm = object.__new__(cls)
# Note that right now imm has a normal setattr method;
# Give any parameter that has one a default value
params = cls._pimms_immutable_data_['params']
for ... | All immutable new classes use a hack to make sure the post-init cleanup occurs. |
def fso_listdir(self, path):
'overlays os.listdir()'
path = self.deref(path)
if not stat.S_ISDIR(self._stat(path).st_mode):
raise OSError(20, 'Not a directory', path)
try:
ret = self.originals['os:listdir'](path)
except Exception:
# assuming that `path` was created within this FSO.... | overlays os.listdir() |
def unsubscribe(self, subscriber: 'Subscriber') -> None:
""" Unsubscribe the given subscriber
:param subscriber: subscriber to unsubscribe
:raises SubscriptionError: if subscriber is not subscribed (anymore)
"""
# here is a special implementation which is replacing the more
... | Unsubscribe the given subscriber
:param subscriber: subscriber to unsubscribe
:raises SubscriptionError: if subscriber is not subscribed (anymore) |
def tag_supplementary_material_sibling_ordinal(tag):
"""
Strategy is to count the previous supplementary-material tags
having the same asset value to get its sibling ordinal.
The result is its position inside any parent tag that
are the same asset type
"""
if hasattr(tag, 'name') and tag.nam... | Strategy is to count the previous supplementary-material tags
having the same asset value to get its sibling ordinal.
The result is its position inside any parent tag that
are the same asset type |
def _fake_closeenumeration(self, namespace, **params):
"""
Implements WBEM server responder for
:meth:`~pywbem.WBEMConnection.CloseEnumeration`
with data from the instance repository.
If the EnumerationContext is valid it removes it from the
context r... | Implements WBEM server responder for
:meth:`~pywbem.WBEMConnection.CloseEnumeration`
with data from the instance repository.
If the EnumerationContext is valid it removes it from the
context repository. Otherwise it returns an exception. |
def main(nodes, edges):
"""Generate a random graph, submit jobs, then validate that the
dependency order was enforced.
Finally, plot the graph, with time on the x-axis, and
in-degree on the y (just for spread). All arrows must
point at least slightly to the right if the graph is valid.
"""
... | Generate a random graph, submit jobs, then validate that the
dependency order was enforced.
Finally, plot the graph, with time on the x-axis, and
in-degree on the y (just for spread). All arrows must
point at least slightly to the right if the graph is valid. |
def get_user_config():
"""Get the user configuration filename.
If the user configuration file does not exist, copy it from the initial
configuration file, but only if this is not a portable installation.
Returns path to user config file (which might not exist due to copy
failures or on portable syst... | Get the user configuration filename.
If the user configuration file does not exist, copy it from the initial
configuration file, but only if this is not a portable installation.
Returns path to user config file (which might not exist due to copy
failures or on portable systems).
@return configuratio... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.