code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def build_kitchen_sink():
"""All settings set"""
from sendgrid.helpers.mail import (
Mail, From, To, Cc, Bcc, Subject, PlainTextContent,
HtmlContent, SendGridException, Substitution,
Header, CustomArg, SendAt, Content, MimeType, Attachment,
FileName, FileContent, FileType, Disp... | All settings set |
def ageostrophic_wind(heights, f, dx, dy, u, v, dim_order='yx'):
r"""Calculate the ageostrophic wind given from the heights or geopotential.
Parameters
----------
heights : (M, N) ndarray
The height field.
f : array_like
The coriolis parameter. This can be a scalar to be applied
... | r"""Calculate the ageostrophic wind given from the heights or geopotential.
Parameters
----------
heights : (M, N) ndarray
The height field.
f : array_like
The coriolis parameter. This can be a scalar to be applied
everywhere or an array of values.
dx : float or ndarray
... |
def build_class(name, basenames=(), doc=None):
"""create and initialize an astroid ClassDef node"""
node = nodes.ClassDef(name, doc)
for base in basenames:
basenode = nodes.Name()
basenode.name = base
node.bases.append(basenode)
basenode.parent = node
return node | create and initialize an astroid ClassDef node |
def emitCurrentRecordChanged(self, item):
"""
Emits the record changed signal for the given item, provided the
signals are not currently blocked.
:param item | <QTreeWidgetItem>
"""
if self.signalsBlocked():
return
# em... | Emits the record changed signal for the given item, provided the
signals are not currently blocked.
:param item | <QTreeWidgetItem> |
def create_like(self, repository_id, pull_request_id, thread_id, comment_id, project=None):
"""CreateLike.
[Preview API] Add a like on a comment.
:param str repository_id: The repository ID of the pull request's target branch.
:param int pull_request_id: ID of the pull request.
:... | CreateLike.
[Preview API] Add a like on a comment.
:param str repository_id: The repository ID of the pull request's target branch.
:param int pull_request_id: ID of the pull request.
:param int thread_id: The ID of the thread that contains the comment.
:param int comment_id: The... |
def compile_dependencies(self, sourcepath, include_self=False):
"""
Apply compile on all dependencies
Args:
sourcepath (string): Sass source path to compile to its
destination using project settings.
Keyword Arguments:
include_self (bool): If ``T... | Apply compile on all dependencies
Args:
sourcepath (string): Sass source path to compile to its
destination using project settings.
Keyword Arguments:
include_self (bool): If ``True`` the given sourcepath is add to
items to compile, else only its... |
def _get_sts_token(self):
"""
Assume a role via STS and return the credentials.
First connect to STS via :py:func:`boto3.client`, then
assume a role using `boto3.STS.Client.assume_role <https://boto3.readthe
docs.org/en/latest/reference/services/sts.html#STS.Client.assume_role>`... | Assume a role via STS and return the credentials.
First connect to STS via :py:func:`boto3.client`, then
assume a role using `boto3.STS.Client.assume_role <https://boto3.readthe
docs.org/en/latest/reference/services/sts.html#STS.Client.assume_role>`_
using ``self.account_id`` and ``self... |
def check_existing_vr_tag(self):
"""
Checks if version-release tag (primary not floating tag) exists already,
and fails plugin if it does.
"""
primary_images = get_primary_images(self.workflow)
if not primary_images:
return
vr_image = None
fo... | Checks if version-release tag (primary not floating tag) exists already,
and fails plugin if it does. |
def validate_instance(cls, opts):
"""Validates an instance of global options for cases that are not prohibited via registration.
For example: mutually exclusive options may be registered by passing a `mutually_exclusive_group`,
but when multiple flags must be specified together, it can be necessary to spec... | Validates an instance of global options for cases that are not prohibited via registration.
For example: mutually exclusive options may be registered by passing a `mutually_exclusive_group`,
but when multiple flags must be specified together, it can be necessary to specify post-parse
checks.
Raises pa... |
def addStencilBranch(self, disp, weight):
"""
Set or overwrite the stencil weight for the given direction
@param disp displacement vector
@param weight stencil weight
"""
self.stencil[tuple(disp)] = weight
self.__setPartionLogic(disp) | Set or overwrite the stencil weight for the given direction
@param disp displacement vector
@param weight stencil weight |
def set_ontime(self, ontime):
"""Set duration th switch stays on when toggled. """
try:
ontime = float(ontime)
except Exception as err:
LOG.debug("SwitchPowermeter.set_ontime: Exception %s" % (err,))
return False
self.actionNodeData("ON_TIME", ontime) | Set duration th switch stays on when toggled. |
def close(self):
"""Close the channel to the queue."""
self.cancel()
self.backend.close()
self._closed = True | Close the channel to the queue. |
def delete_local_file(file_name):
"""
Deletes the file associated with the file_name passed from local storage.
:param str file_name: Filename of the file to be deleted
:return str: Filename of the file that was just deleted
"""
try:
os.remove(file_name)
log.info(f"Deletion... | Deletes the file associated with the file_name passed from local storage.
:param str file_name: Filename of the file to be deleted
:return str: Filename of the file that was just deleted |
def integrate_data(xdata, ydata, xmin=None, xmax=None, autozero=0):
"""
Numerically integrates up the ydata using the trapezoid approximation.
estimate the bin width (scaled by the specified amount).
Returns (xdata, integrated ydata).
autozero is the number of data points to use as an estimate of t... | Numerically integrates up the ydata using the trapezoid approximation.
estimate the bin width (scaled by the specified amount).
Returns (xdata, integrated ydata).
autozero is the number of data points to use as an estimate of the background
(then subtracted before integrating). |
def delete(self, ids):
"""
Method to delete ipv6's by their ids
:param ids: Identifiers of ipv6's
:return: None
"""
url = build_uri_with_ids('api/v4/ipv6/%s/', ids)
return super(ApiV4IPv6, self).delete(url) | Method to delete ipv6's by their ids
:param ids: Identifiers of ipv6's
:return: None |
def query(self, query=None):
"""
If query is given, modify the URL correspondingly, return the current
query otherwise.
"""
if query is None:
return self.url.query
self.url.query = query | If query is given, modify the URL correspondingly, return the current
query otherwise. |
def sitemap(self):
"""Return the sitemap URI based on maps or explicit settings."""
if (self.sitemap_name is not None):
return(self.sitemap_name)
return(self.sitemap_uri(self.resource_list_name)) | Return the sitemap URI based on maps or explicit settings. |
def Append(self, component=None, **kwarg):
"""Append a new pathspec component to this pathspec."""
if component is None:
component = self.__class__(**kwarg)
if self.HasField("pathtype"):
self.last.nested_path = component
else:
for k, v in iteritems(kwarg):
setattr(self, k, v)
... | Append a new pathspec component to this pathspec. |
def getPlayAreaRect(self):
"""
Returns the 4 corner positions of the Play Area (formerly named Soft Bounds).
Corners are in counter-clockwise order.
Standing center (0,0,0) is the center of the Play Area.
It's a rectangle.
2 sides are parallel to the X axis and 2 sides ar... | Returns the 4 corner positions of the Play Area (formerly named Soft Bounds).
Corners are in counter-clockwise order.
Standing center (0,0,0) is the center of the Play Area.
It's a rectangle.
2 sides are parallel to the X axis and 2 sides are parallel to the Z axis.
Height of eve... |
def list_vpnservices(retrieve_all=True, profile=None, **kwargs):
'''
Fetches a list of all configured VPN services for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_vpnservices
:param retrieve_all: True or False, default: True (Optional)
:param profile: Profile to ... | Fetches a list of all configured VPN services for a tenant
CLI Example:
.. code-block:: bash
salt '*' neutron.list_vpnservices
:param retrieve_all: True or False, default: True (Optional)
:param profile: Profile to build on (Optional)
:return: List of VPN service |
def join_tags(tags):
"""
Given list of ``Tag`` instances, creates a string representation of
the list suitable for editing by the user, such that submitting the
given string representation back without changing it will give the
same list of tags.
Tag names which contain DELIMITER will be double... | Given list of ``Tag`` instances, creates a string representation of
the list suitable for editing by the user, such that submitting the
given string representation back without changing it will give the
same list of tags.
Tag names which contain DELIMITER will be double quoted.
Adapted from Taggit... |
def variations(word):
"""Create variations of the word based on letter combinations like oo,
sh, etc."""
if len(word) == 1:
return [[word[0]]]
elif word == 'aa':
return [['A']]
elif word == 'ee':
return [['i']]
elif word == 'ei':
return [['ei']]
elif word in ['oo... | Create variations of the word based on letter combinations like oo,
sh, etc. |
def get_canvas_image(self):
"""Get canvas image object.
Returns
-------
imgobj : `~ginga.canvas.types.image.NormImage`
Normalized image sitting on the canvas.
"""
if self._imgobj is not None:
return self._imgobj
try:
# See if... | Get canvas image object.
Returns
-------
imgobj : `~ginga.canvas.types.image.NormImage`
Normalized image sitting on the canvas. |
def returns(self) -> T.Optional[DocstringReturns]:
"""Return return information indicated in docstring."""
try:
return next(
DocstringReturns.from_meta(meta)
for meta in self.meta
if meta.args[0] in {"return", "returns", "yield", "yields"}
... | Return return information indicated in docstring. |
async def get_next_opponent(self):
""" Get the opponent of the potential next match. See :func:`get_next_match`
|methcoro|
Raises:
APIException
"""
next_match = await self.get_next_match()
if next_match is not None:
opponent_id = next_match.play... | Get the opponent of the potential next match. See :func:`get_next_match`
|methcoro|
Raises:
APIException |
def print_fields(bf, *args, **kwargs):
"""
Print all the fields of a Bitfield object to stdout. This is
primarly a diagnostic aid during debugging.
"""
vals = {k: hex(v) for k, v in bf.items()}
print(bf.base, vals, *args, **kwargs) | Print all the fields of a Bitfield object to stdout. This is
primarly a diagnostic aid during debugging. |
def ensure_ndarray(ndarray_or_adjusted_array):
"""
Return the input as a numpy ndarray.
This is a no-op if the input is already an ndarray. If the input is an
adjusted_array, this extracts a read-only view of its internal data buffer.
Parameters
----------
ndarray_or_adjusted_array : nump... | Return the input as a numpy ndarray.
This is a no-op if the input is already an ndarray. If the input is an
adjusted_array, this extracts a read-only view of its internal data buffer.
Parameters
----------
ndarray_or_adjusted_array : numpy.ndarray | zipline.data.adjusted_array
Returns
--... |
def get_darker_image(self):
"""Returns an icon 80% more dark"""
icon_pressed = self.icon.copy()
for x in range(self.w):
for y in range(self.h):
r, g, b, *_ = tuple(self.icon.get_at((x, y)))
const = 0.8
r = int(const * r)
... | Returns an icon 80% more dark |
def get_ISI_ratio(sorting, sampling_frequency, unit_ids=None, save_as_property=True):
'''This function calculates the ratio between the frequency of spikes present
within 0- to 2-ms (refractory period) interspike interval (ISI) and those at 0- to 20-ms
interval. It then returns the ratios and also adds a pr... | This function calculates the ratio between the frequency of spikes present
within 0- to 2-ms (refractory period) interspike interval (ISI) and those at 0- to 20-ms
interval. It then returns the ratios and also adds a property, ISI_ratio, for
the passed in sorting extractor. Taken from:
"Large-scale, h... |
def execution_context(self):
"""
Access the execution_context
:returns: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextList
:rtype: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextList
"""
if self._execution_context is None:... | Access the execution_context
:returns: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextList
:rtype: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextList |
def audio(audio, sample_rate, name=None, out=None, subdir='', timeout=5,
**kwargs):
"""summary audio files to listen on a browser.
An sampled array is converted as WAV audio file, saved to output directory,
and reported to the ChainerUI server. The audio file is saved every called
this functi... | summary audio files to listen on a browser.
An sampled array is converted as WAV audio file, saved to output directory,
and reported to the ChainerUI server. The audio file is saved every called
this function. The audio file will be listened on `assets` endpoint
vertically. If need to aggregate audio f... |
def size():
"""Determines the height and width of the console window
Returns:
tuple of int: The height in lines, then width in characters
"""
try:
assert os != 'nt' and sys.stdout.isatty()
rows, columns = os.popen('stty size', 'r').read().split()
except (AssertionErr... | Determines the height and width of the console window
Returns:
tuple of int: The height in lines, then width in characters |
def start_element(self, name, attrs):
"""Set tag status for start element."""
self.in_tag = (name == self.tag)
self.url = u"" | Set tag status for start element. |
def iter_commit_activity(self, number=-1, etag=None):
"""Iterate over last year of commit activity by week.
See: http://developer.github.com/v3/repos/statistics/
:param int number: (optional), number of weeks to return. Default -1
will return all of the weeks.
:param str et... | Iterate over last year of commit activity by week.
See: http://developer.github.com/v3/repos/statistics/
:param int number: (optional), number of weeks to return. Default -1
will return all of the weeks.
:param str etag: (optional), ETag from a previous request to the same
... |
def find_closest_match(target_track, tracks):
"""
Return closest match to target track
"""
track = None
# Get a list of (track, artist match ratio, name match ratio)
tracks_with_match_ratio = [(
track,
get_similarity(target_track.artist, track.artist),
get_similarity(targ... | Return closest match to target track |
def tap_hold(self, x, y, duration=1.0):
"""
Tap and hold for a moment
Args:
- x, y(int): position
- duration(float): seconds of hold time
[[FBRoute POST:@"/wda/touchAndHold"] respondWithTarget:self action:@selector(handleTouchAndHoldCoordinate:)],
"""
... | Tap and hold for a moment
Args:
- x, y(int): position
- duration(float): seconds of hold time
[[FBRoute POST:@"/wda/touchAndHold"] respondWithTarget:self action:@selector(handleTouchAndHoldCoordinate:)], |
def save():
'''save is a view to save data. We might want to adjust this to allow for
updating saved data, but given single file is just one post for now
'''
if request.method == 'POST':
exp_id = session.get('exp_id')
app.logger.debug('Saving data for %s' %exp_id)
fields = ge... | save is a view to save data. We might want to adjust this to allow for
updating saved data, but given single file is just one post for now |
def write(self) -> None:
"""Call method |NetCDFFile.write| of all handled |NetCDFFile| objects.
"""
if self.folders:
init = hydpy.pub.timegrids.init
timeunits = init.firstdate.to_cfunits('hours')
timepoints = init.to_timepoints('hours')
for folder ... | Call method |NetCDFFile.write| of all handled |NetCDFFile| objects. |
def getAnalogType(self,num):
"""
Returns the type of the channel 'num' based
on its unit stored in the Comtrade header file.
Returns 'V' for a voltage channel and 'I' for a current channel.
"""
listidx = self.An.index(num)
unit = self.uu[listidx]
... | Returns the type of the channel 'num' based
on its unit stored in the Comtrade header file.
Returns 'V' for a voltage channel and 'I' for a current channel. |
def create_helper_trans_node(op_name, input_node, node_name):
"""create extra transpose node for dot operator"""
node_name = op_name + "_" + node_name
trans_node = onnx.helper.make_node(
'Transpose',
inputs=[input_node],
outputs=[node_name],
name=node_name
)
return tr... | create extra transpose node for dot operator |
def normalize(seq):
"""
Scales each number in the sequence so that the sum of all numbers equals 1.
"""
s = float(sum(seq))
return [v/s for v in seq] | Scales each number in the sequence so that the sum of all numbers equals 1. |
def iter_links(self, file, encoding=None, context=False):
'''Return the links.
This function is a convenience function for calling :meth:`iter_text`
and returning only the links.
'''
if context:
return [item for item in self.iter_text(file, encoding) if item[1]]
... | Return the links.
This function is a convenience function for calling :meth:`iter_text`
and returning only the links. |
def get(self, sid):
"""
Constructs a DocumentContext
:param sid: The sid
:returns: twilio.rest.preview.sync.service.document.DocumentContext
:rtype: twilio.rest.preview.sync.service.document.DocumentContext
"""
return DocumentContext(self._version, service_sid=s... | Constructs a DocumentContext
:param sid: The sid
:returns: twilio.rest.preview.sync.service.document.DocumentContext
:rtype: twilio.rest.preview.sync.service.document.DocumentContext |
def make_phase_space_list():
"""
Extract all the phase space information (due to ``EMIT`` commands in the input
file), and create a list of PhaseSpace objects. The primary purpose of this
is for interactive explorations of the data produced during Pynac simulations.
"""
with open('dynac.short')... | Extract all the phase space information (due to ``EMIT`` commands in the input
file), and create a list of PhaseSpace objects. The primary purpose of this
is for interactive explorations of the data produced during Pynac simulations. |
def Bier(P, Pc, Te=None, q=None):
r'''Calculates heat transfer coefficient for a evaporator operating
in the nucleate boiling regime according to [1]_ .
Either heat flux or excess temperature is required.
With `Te` specified:
.. math::
h = \left(0.00417P_c^{0.69} \Delta Te^{0.7}\left[0.7 ... | r'''Calculates heat transfer coefficient for a evaporator operating
in the nucleate boiling regime according to [1]_ .
Either heat flux or excess temperature is required.
With `Te` specified:
.. math::
h = \left(0.00417P_c^{0.69} \Delta Te^{0.7}\left[0.7 + 2P_r\left(4 +
\frac{1}{1-P_r... |
def report_exception(self, filename, exc):
"""
This method is used when self.parser raises an Exception so that
we can report a customized :class:`EventReport` object with info the exception.
"""
# Build fake event.
event = AbinitError(src_file="Unknown", src_line=0, mess... | This method is used when self.parser raises an Exception so that
we can report a customized :class:`EventReport` object with info the exception. |
def set_global_permissions(self, global_permissions):
"""SetGlobalPermissions.
[Preview API] Set service-wide permissions that govern feed creation.
:param [GlobalPermission] global_permissions: New permissions for the organization.
:rtype: [GlobalPermission]
"""
content ... | SetGlobalPermissions.
[Preview API] Set service-wide permissions that govern feed creation.
:param [GlobalPermission] global_permissions: New permissions for the organization.
:rtype: [GlobalPermission] |
def _run_services(self, pants_services):
"""Service runner main loop."""
if not pants_services.services:
self._logger.critical('no services to run, bailing!')
return
service_thread_map = {service: self._make_thread(service)
for service in pants_services.services}
... | Service runner main loop. |
def fit_points_in_bounding_box(df_points, bounding_box, padding_fraction=0):
'''
Return data frame with ``x``, ``y`` columns scaled to fit points from
:data:`df_points` to fill :data:`bounding_box` while maintaining aspect
ratio.
Arguments
---------
df_points : pandas.DataFrame
A fr... | Return data frame with ``x``, ``y`` columns scaled to fit points from
:data:`df_points` to fill :data:`bounding_box` while maintaining aspect
ratio.
Arguments
---------
df_points : pandas.DataFrame
A frame with at least the columns ``x`` and ``y``, containing one row
per point.
... |
def _load_file(self):
"""
Reads the configured todo.txt file and loads it into the todo list
instance.
"""
self.todolist.erase()
self.todolist.add_list(self.todofile.read())
self.completer = PromptCompleter(self.todolist) | Reads the configured todo.txt file and loads it into the todo list
instance. |
def execute_cmd(self, *args, **kwargs):
"""Execute a given hpssacli/ssacli command on the controller.
This method executes a given command on the controller.
:params args: a tuple consisting of sub-commands to be appended
after specifying the controller in hpssacli/ssacli command.
... | Execute a given hpssacli/ssacli command on the controller.
This method executes a given command on the controller.
:params args: a tuple consisting of sub-commands to be appended
after specifying the controller in hpssacli/ssacli command.
:param kwargs: kwargs to be passed to execu... |
def _to_viewitem(self, prog_var):
"""
Convert a ProgramVariable instance to a DDGViewItem object.
:param ProgramVariable prog_var: The ProgramVariable object to convert.
:return: The converted DDGViewItem object.
:rtype: DDGViewIt... | Convert a ProgramVariable instance to a DDGViewItem object.
:param ProgramVariable prog_var: The ProgramVariable object to convert.
:return: The converted DDGViewItem object.
:rtype: DDGViewItem |
def get_InsideConvexPoly(self, RelOff=_def.TorRelOff, ZLim='Def',
Spline=True, Splprms=_def.TorSplprms,
NP=_def.TorInsideNP, Plot=False, Test=True):
""" Return a polygon that is a smaller and smoothed approximation of Ves.Poly, useful for excluding the d... | Return a polygon that is a smaller and smoothed approximation of Ves.Poly, useful for excluding the divertor region in a Tokamak
For some uses, it can be practical to approximate the polygon defining the Ves object (which can be non-convex, like with a divertor), by a simpler, sligthly smaller and convex polyg... |
def get_system_uptime_output_cmd_error(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_system_uptime = ET.Element("get_system_uptime")
config = get_system_uptime
output = ET.SubElement(get_system_uptime, "output")
cmd_error = ET.SubEl... | Auto Generated Code |
def status(self):
'''Allow custom status messages'''
message = self.status_message
if message is None:
message = STATUS[self.status_code]
return '%s %s' % (self.status_code, message) | Allow custom status messages |
def _getDocstringLineno(self, node_type, node):
"""
Get line number of the docstring.
@param node_type: type of node_type
@param node: node of currently checking
@return: line number
"""
docstringStriped = node.as_string().strip()
linenoDocstring = (node.... | Get line number of the docstring.
@param node_type: type of node_type
@param node: node of currently checking
@return: line number |
def reset_generation(self):
"""Reset the generation and memberId because we have fallen out of the group."""
with self._lock:
self._generation = Generation.NO_GENERATION
self.rejoin_needed = True
self.state = MemberState.UNJOINED | Reset the generation and memberId because we have fallen out of the group. |
def handleEvent(self, eventObj):
"""This method should be called every time through the main loop.
It handles showing the up, over, and down states of the button.
Parameters:
| eventObj - the event object obtained by calling pygame.event.get()
Returns:
... | This method should be called every time through the main loop.
It handles showing the up, over, and down states of the button.
Parameters:
| eventObj - the event object obtained by calling pygame.event.get()
Returns:
| False most of the time
| True... |
def create(vm_, call=None):
'''Create an lxc Container.
This function is idempotent and will try to either provision
or finish the provision of an lxc container.
NOTE: Most of the initialization code has been moved and merged
with the lxc runner and lxc.init functions
'''
prov = get_configu... | Create an lxc Container.
This function is idempotent and will try to either provision
or finish the provision of an lxc container.
NOTE: Most of the initialization code has been moved and merged
with the lxc runner and lxc.init functions |
def check_stat(self, path):
"""
Checks logfile stat information for excluding files not in datetime period.
On Linux it's possible to checks only modification time, because file creation info
are not available, so it's possible to exclude only older files.
In Unix BSD systems and... | Checks logfile stat information for excluding files not in datetime period.
On Linux it's possible to checks only modification time, because file creation info
are not available, so it's possible to exclude only older files.
In Unix BSD systems and windows information about file creation date an... |
def create_object(self, name, experiment_id, model_id, argument_defs, arguments=None, properties=None):
"""Create a model run object with the given list of arguments. The
initial state of the object is RUNNING.
Raises ValueError if given arguments are invalid.
Parameters
------... | Create a model run object with the given list of arguments. The
initial state of the object is RUNNING.
Raises ValueError if given arguments are invalid.
Parameters
----------
name : string
User-provided name for the model run
experiment_id : string
... |
def RegexLookup(fieldVal, db, fieldName, lookupType, histObj={}):
"""
Return a new field value based on match against regex queried from MongoDB
:param string fieldVal: input value to lookup
:param MongoClient db: MongoClient instance connected to MongoDB
:param string lookupType: Type of lookup to... | Return a new field value based on match against regex queried from MongoDB
:param string fieldVal: input value to lookup
:param MongoClient db: MongoClient instance connected to MongoDB
:param string lookupType: Type of lookup to perform/MongoDB collection name.
One of 'genericRegex', 'fieldSpe... |
def _cim_keybinding(key, value):
"""
Return a keybinding value, from dict item input (key+value).
Key may be None (for unnamed keys).
The returned value will be a CIM-typed value, except if it was provided as
Python number type (in which case it will remain that type).
Invalid types or values ... | Return a keybinding value, from dict item input (key+value).
Key may be None (for unnamed keys).
The returned value will be a CIM-typed value, except if it was provided as
Python number type (in which case it will remain that type).
Invalid types or values cause TypeError or ValueError to be raised. |
def set_frameworkcontroller_config(experiment_config, port, config_file_name):
'''set kubeflow configuration'''
frameworkcontroller_config_data = dict()
frameworkcontroller_config_data['frameworkcontroller_config'] = experiment_config['frameworkcontrollerConfig']
response = rest_put(cluster_metadata_ur... | set kubeflow configuration |
def from_file(cls, fname, form=None):
"""
Read an orthography profile from a metadata file or a default tab-separated profile file.
"""
try:
tg = TableGroup.from_file(fname)
opfname = None
except JSONDecodeError:
tg = TableGroup.fromvalue(cls.M... | Read an orthography profile from a metadata file or a default tab-separated profile file. |
def evaluatePotentials(Pot,R,z,phi=None,t=0.,dR=0,dphi=0):
"""
NAME:
evaluatePotentials
PURPOSE:
convenience function to evaluate a possible sum of potentials
INPUT:
Pot - potential or list of potentials (dissipative forces in such a list are ignored)
R - cylindrical Ga... | NAME:
evaluatePotentials
PURPOSE:
convenience function to evaluate a possible sum of potentials
INPUT:
Pot - potential or list of potentials (dissipative forces in such a list are ignored)
R - cylindrical Galactocentric distance (can be Quantity)
z - distance above the ... |
def _get_future_devices(self, context):
"""Return a generator yielding new devices."""
monitor = Monitor.from_netlink(context)
monitor.filter_by("hidraw")
monitor.start()
self._scanning_log_message()
for device in iter(monitor.poll, None):
if device.action ==... | Return a generator yielding new devices. |
def yearly(self):
"""
Access the yearly
:returns: twilio.rest.api.v2010.account.usage.record.yearly.YearlyList
:rtype: twilio.rest.api.v2010.account.usage.record.yearly.YearlyList
"""
if self._yearly is None:
self._yearly = YearlyList(self._version, account_s... | Access the yearly
:returns: twilio.rest.api.v2010.account.usage.record.yearly.YearlyList
:rtype: twilio.rest.api.v2010.account.usage.record.yearly.YearlyList |
def apply_driver_hacks(self, app, info, options):
"""
Set custom SQLAlchemy engine options:
- Teach it to encode and decode our node objects
- Enable pre-ping (i.e., test the DB connection before trying to use it)
"""
options.update(dict(
json_serializer=lambd... | Set custom SQLAlchemy engine options:
- Teach it to encode and decode our node objects
- Enable pre-ping (i.e., test the DB connection before trying to use it) |
def decrypt_report(self, device_id, root, data, **kwargs):
"""Decrypt a buffer of report data on behalf of a device.
Args:
device_id (int): The id of the device that we should encrypt for
root (int): The root key type that should be used to generate the report
data (... | Decrypt a buffer of report data on behalf of a device.
Args:
device_id (int): The id of the device that we should encrypt for
root (int): The root key type that should be used to generate the report
data (bytearray): The data that we should decrypt
**kwargs: Ther... |
def prompt(text, default=None, hide_input=False,
confirmation_prompt=False, type=None,
value_proc=None, prompt_suffix=': ',
show_default=True, err=False):
"""Prompts a user for input. This is a convenience function that can
be used to prompt a user for input later.
If the ... | Prompts a user for input. This is a convenience function that can
be used to prompt a user for input later.
If the user aborts the input by sending a interrupt signal, this
function will catch it and raise a :exc:`Abort` exception.
.. versionadded:: 6.0
Added unicode support for cmd.exe on Win... |
def grid_edges(shape, inds=None, return_directions=True):
"""
Get list of grid edges
:param shape:
:param inds:
:param return_directions:
:return:
"""
if inds is None:
inds = np.arange(np.prod(shape)).reshape(shape)
# if not self.segparams['use_boundary_penalties'] and \
... | Get list of grid edges
:param shape:
:param inds:
:param return_directions:
:return: |
def change_event_params(self, handler, **kwargs):
"""
This allows the client to change the parameters for an event, in the case that there is a desire for slightly different behavior, such as reasigning keys.
handler - the handler object that the desired changes are made to.
kwargs - t... | This allows the client to change the parameters for an event, in the case that there is a desire for slightly different behavior, such as reasigning keys.
handler - the handler object that the desired changes are made to.
kwargs - the variable number of keyword arguments for the parameters that must m... |
def geohash(self, key, member, *members, **kwargs):
"""Returns members of a geospatial index as standard geohash strings.
:rtype: list[str or bytes or None]
"""
return self.execute(
b'GEOHASH', key, member, *members, **kwargs
) | Returns members of a geospatial index as standard geohash strings.
:rtype: list[str or bytes or None] |
def _value_encode(cls, member, value):
"""
Internal method used to encode values into the hash.
:param member: str
:param value: multi
:return: bytes
"""
try:
field_validator = cls.fields[member]
except KeyError:
return cls.valuepa... | Internal method used to encode values into the hash.
:param member: str
:param value: multi
:return: bytes |
def replace_event_annotations(event, newanns):
"""Replace event annotations with the provided ones."""
_humilis = event.get("_humilis", {})
if not _humilis:
event["_humilis"] = {"annotation": newanns}
else:
event["_humilis"]["annotation"] = newanns | Replace event annotations with the provided ones. |
def get_client(self, service, region, public=True, cached=True,
client_class=None):
"""
Returns the client object for the specified service and region.
By default the public endpoint is used. If you wish to work with a
services internal endpoints, specify `public=False`.
... | Returns the client object for the specified service and region.
By default the public endpoint is used. If you wish to work with a
services internal endpoints, specify `public=False`.
By default, if a client has already been created for the given service,
region, and public values, tha... |
def extract_alzip (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a ALZIP archive."""
return [cmd, '-d', outdir, archive] | Extract a ALZIP archive. |
def node_type(node: astroid.node_classes.NodeNG) -> Optional[type]:
"""Return the inferred type for `node`
If there is more than one possible type, or if inferred type is Uninferable or None,
return None
"""
# check there is only one possible type for the assign node. Else we
# don't handle it ... | Return the inferred type for `node`
If there is more than one possible type, or if inferred type is Uninferable or None,
return None |
def maybe_download_and_extract(data_root: str, url: str) -> None:
"""
Maybe download the specified file to ``data_root`` and try to unpack it with ``shutil.unpack_archive``.
:param data_root: data root to download the files to
:param url: url to download from
"""
# make sure data_root exis... | Maybe download the specified file to ``data_root`` and try to unpack it with ``shutil.unpack_archive``.
:param data_root: data root to download the files to
:param url: url to download from |
def _get_domain(conn, *vms, **kwargs):
'''
Return a domain object for the named VM or return domain object for all VMs.
:params conn: libvirt connection object
:param vms: list of domain names to look for
:param iterable: True to return an array in all cases
'''
ret = list()
lookup_vms ... | Return a domain object for the named VM or return domain object for all VMs.
:params conn: libvirt connection object
:param vms: list of domain names to look for
:param iterable: True to return an array in all cases |
def _get_envelopes_centroid(envelopes):
"""
Returns the centroid of an inputted geometry column. Not currently in use, as this is now handled by this
library's CRS wrapper directly. Light wrapper over ``_get_envelopes_min_maxes``.
Parameters
----------
envelopes : GeoSeries
The envelope... | Returns the centroid of an inputted geometry column. Not currently in use, as this is now handled by this
library's CRS wrapper directly. Light wrapper over ``_get_envelopes_min_maxes``.
Parameters
----------
envelopes : GeoSeries
The envelopes of the given geometries, as would be returned by e... |
def _determine_slot(self, *args):
"""
figure out what slot based on command and args
"""
if len(args) <= 1:
raise RedisClusterException("No way to dispatch this command to Redis Cluster. Missing key.")
command = args[0]
if command in ['EVAL', 'EVALSHA']:
... | figure out what slot based on command and args |
def process_byte(self, tag):
"""Process byte type tags"""
tag.set_address(self.normal_register.current_address)
# each address needs 1 byte
self.normal_register.move_to_next_address(1) | Process byte type tags |
def add_task(self, task, func=None, **kwargs):
''' Add a task parser '''
if not self.__tasks:
raise Exception("Tasks subparsers is disabled")
if 'help' not in kwargs:
if func.__doc__:
kwargs['help'] = func.__doc__
task_parser = self.__tasks.add_par... | Add a task parser |
def get_states(self, dump_optimizer=False):
"""Gets updater states.
Parameters
----------
dump_optimizer : bool, default False
Whether to also save the optimizer itself. This would also save optimizer
information such as learning rate and weight decay schedules.
... | Gets updater states.
Parameters
----------
dump_optimizer : bool, default False
Whether to also save the optimizer itself. This would also save optimizer
information such as learning rate and weight decay schedules. |
def parse_250_row(row: list) -> BasicMeterData:
""" Parse basic meter data record (250) """
return BasicMeterData(row[1], row[2], row[3], row[4], row[5],
row[6], row[7], float(row[8]),
parse_datetime(row[9]), row[10], row[11], row[12],
... | Parse basic meter data record (250) |
def _thread_loop(self):
"""Background thread used when Sender is in asynchronous/interval mode."""
last_check_time = time.time()
messages = []
while True:
# Get first message from queue, blocking until the next time we
# should be sending
time_since_la... | Background thread used when Sender is in asynchronous/interval mode. |
def __get_dynamic_attr(self, attname, arg, default=None):
"""
Gets "something" from self, which could be an attribute or
a callable with either 0 or 1 arguments (besides self).
Stolen from django.contrib.syntication.feeds.Feed.
"""
try:
attr = getattr... | Gets "something" from self, which could be an attribute or
a callable with either 0 or 1 arguments (besides self).
Stolen from django.contrib.syntication.feeds.Feed. |
def on_message(self, headers, message):
"""
Event method that gets called when this listener has received a JMS
message (representing an HMC notification).
Parameters:
headers (dict): JMS message headers, as described for `headers` tuple
item returned by the
... | Event method that gets called when this listener has received a JMS
message (representing an HMC notification).
Parameters:
headers (dict): JMS message headers, as described for `headers` tuple
item returned by the
:meth:`~zhmcclient.NotificationReceiver.notifications... |
def remove_role(self, databaseName, roleName, collectionName=None):
"""Remove one role
Args:
databaseName (str): Database Name
roleName (RoleSpecs): role
Keyword Args:
collectionName (str): Collection
"""
role = {"database... | Remove one role
Args:
databaseName (str): Database Name
roleName (RoleSpecs): role
Keyword Args:
collectionName (str): Collection |
def has_elem(elem_ref):
"""
Has element?
:param elem_ref:
:return:
"""
if not is_elem_ref(elem_ref):
return False
elif elem_ref[0] == ElemRefObj:
return hasattr(elem_ref[1], elem_ref[2])
elif elem_ref[0] == ElemRefArr:
return elem_ref[2] in elem_ref[1] | Has element?
:param elem_ref:
:return: |
def salm2map(salm, s, lmax, Ntheta, Nphi):
"""Convert mode weights of spin-weighted function to values on a grid
Parameters
----------
salm : array_like, complex, shape (..., (lmax+1)**2)
Input array representing mode weights of the spin-weighted function. This array may be
multi-dimen... | Convert mode weights of spin-weighted function to values on a grid
Parameters
----------
salm : array_like, complex, shape (..., (lmax+1)**2)
Input array representing mode weights of the spin-weighted function. This array may be
multi-dimensional, where initial dimensions may represent dif... |
def _get_streams(self):
"""
Finds the streams from tvcatchup.com.
"""
token = self.login(self.get_option("username"), self.get_option("password"))
m = self._url_re.match(self.url)
scode = m and m.group("scode") or self.get_option("station_code")
res = self.sessio... | Finds the streams from tvcatchup.com. |
def dependency_context(package_names, aggressively_remove=False):
"""
Install the supplied packages and yield. Finally, remove all packages
that were installed.
Currently assumes 'aptitude' is available.
"""
installed_packages = []
log = logging.getLogger(__name__)
try:
if not package_names:
logging.debug(... | Install the supplied packages and yield. Finally, remove all packages
that were installed.
Currently assumes 'aptitude' is available. |
def are_you_sure(msg=''):
r"""
Prompts user to accept or checks command line for -y
Args:
msg (str):
Returns:
bool: accept or not
"""
print(msg)
from utool import util_arg
from utool import util_str
override = util_arg.get_argflag(('--yes', '--y', '-y'))
if over... | r"""
Prompts user to accept or checks command line for -y
Args:
msg (str):
Returns:
bool: accept or not |
def EnumMissingModules():
"""Enumerate all modules which match the patterns MODULE_PATTERNS.
PyInstaller often fails to locate all dlls which are required at
runtime. We import all the client modules here, we simply introspect
all the modules we have loaded in our current running process, and
all the ones ma... | Enumerate all modules which match the patterns MODULE_PATTERNS.
PyInstaller often fails to locate all dlls which are required at
runtime. We import all the client modules here, we simply introspect
all the modules we have loaded in our current running process, and
all the ones matching the patterns are copied ... |
def move_wheel_files(
name, # type: str
req, # type: Requirement
wheeldir, # type: str
user=False, # type: bool
home=None, # type: Optional[str]
root=None, # type: Optional[str]
pycompile=True, # type: bool
scheme=None, # type: Optional[Mapping[str, str]]
isolated=False, # t... | Install a wheel |
def run(self, concurrency=0, outline=False,
tail=False, dump=False, *args, **kwargs):
"""Kicks off the build/update of the stacks in the stack_definitions.
This is the main entry point for the Builder.
"""
plan = self._generate_plan(tail=tail)
if not plan.keys():
... | Kicks off the build/update of the stacks in the stack_definitions.
This is the main entry point for the Builder. |
def enable_network(self, *hostnames):
"""
Enables real networking mode, optionally passing one or multiple
hostnames that would be used as filter.
If at least one hostname matches with the outgoing traffic, the
request will be executed via the real network.
Arguments:
... | Enables real networking mode, optionally passing one or multiple
hostnames that would be used as filter.
If at least one hostname matches with the outgoing traffic, the
request will be executed via the real network.
Arguments:
*hostnames: optional list of host names to enab... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.