code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def validate_request():
"""
Validates the incoming request
The following are invalid
1. The Request data is not json serializable
2. Query Parameters are sent to the endpoint
3. The Request Content-Type is not application/json
4. 'X-Amz-Log-Type' ... | Validates the incoming request
The following are invalid
1. The Request data is not json serializable
2. Query Parameters are sent to the endpoint
3. The Request Content-Type is not application/json
4. 'X-Amz-Log-Type' header is not 'None'
5. 'X-Amz-I... |
def _get_rate(self, mag):
"""
Calculate and return the annual occurrence rate for a specific bin.
:param mag:
Magnitude value corresponding to the center of the bin of interest.
:returns:
Float number, the annual occurrence rate for the :param mag value.
... | Calculate and return the annual occurrence rate for a specific bin.
:param mag:
Magnitude value corresponding to the center of the bin of interest.
:returns:
Float number, the annual occurrence rate for the :param mag value. |
def delete_refund_transaction_by_id(cls, refund_transaction_id, **kwargs):
"""Delete RefundTransaction
Delete an instance of RefundTransaction by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thr... | Delete RefundTransaction
Delete an instance of RefundTransaction by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_refund_transaction_by_id(refund_transaction_id, async=True)
>... |
def cores_orthogonalization_step(coresX, dim, left_to_right=True):
"""TT-Tensor X orthogonalization step.
The function can change the shape of some cores.
"""
cc = coresX[dim]
r1, n, r2 = cc.shape
if left_to_right:
# Left to right orthogonalization step.
assert(0 <= dim < len(co... | TT-Tensor X orthogonalization step.
The function can change the shape of some cores. |
def add_object_to_scope(self, obj):
"""Add an object to the appropriate scope block.
Args:
obj: JSSObject to add to scope. Accepted subclasses are:
Computer
ComputerGroup
Building
Department
Raises:
TypeErr... | Add an object to the appropriate scope block.
Args:
obj: JSSObject to add to scope. Accepted subclasses are:
Computer
ComputerGroup
Building
Department
Raises:
TypeError if invalid obj type is provided. |
def remove_breakpoint(self, py_db, filename, breakpoint_type, breakpoint_id):
'''
:param str filename:
Note: must be already translated for the server.
:param str breakpoint_type:
One of: 'python-line', 'django-line', 'jinja2-line'.
:param int breakpoint_id:
... | :param str filename:
Note: must be already translated for the server.
:param str breakpoint_type:
One of: 'python-line', 'django-line', 'jinja2-line'.
:param int breakpoint_id: |
def move_distance(self, distance_x_m, distance_y_m, distance_z_m,
velocity=VELOCITY):
"""
Move in a straight line.
positive X is forward
positive Y is left
positive Z is up
:param distance_x_m: The distance to travel along the X-axis (meters)
... | Move in a straight line.
positive X is forward
positive Y is left
positive Z is up
:param distance_x_m: The distance to travel along the X-axis (meters)
:param distance_y_m: The distance to travel along the Y-axis (meters)
:param distance_z_m: The distance to travel alon... |
def load_env(print_vars=False):
"""Load environment variables from a .env file, if present.
If an .env file is found in the working directory, and the listed
environment variables are not already set, they will be set according to
the values listed in the file.
"""
env_file = os.environ.get('EN... | Load environment variables from a .env file, if present.
If an .env file is found in the working directory, and the listed
environment variables are not already set, they will be set according to
the values listed in the file. |
def put(self, resource, **params):
"""
Generic TeleSign REST API PUT handler.
:param resource: The partial resource URI to perform the request against, as a string.
:param params: Body params to perform the PUT request with, as a dictionary.
:return: The RestClient Response obje... | Generic TeleSign REST API PUT handler.
:param resource: The partial resource URI to perform the request against, as a string.
:param params: Body params to perform the PUT request with, as a dictionary.
:return: The RestClient Response object. |
def update_ontology(ont_url, rdf_path):
"""Load an ontology formatted like Eidos' from github."""
yaml_root = load_yaml_from_url(ont_url)
G = rdf_graph_from_yaml(yaml_root)
save_hierarchy(G, rdf_path) | Load an ontology formatted like Eidos' from github. |
def from_localhost(self) -> bool:
"""True if :attr:`.peername` is a connection from a ``localhost``
address.
"""
sock_family = self.socket.family
if sock_family == _socket.AF_UNIX:
return True
elif sock_family not in (_socket.AF_INET, _socket.AF_INET6):
... | True if :attr:`.peername` is a connection from a ``localhost``
address. |
def create_explicit(bounds):
"""Creates a new instance of distribution with explicit buckets.
bounds is an iterable of ordered floats that define the explicit buckets
Args:
bounds (iterable[float]): initializes the bounds
Return:
:class:`endpoints_management.gen.servicecontrol_v1_messag... | Creates a new instance of distribution with explicit buckets.
bounds is an iterable of ordered floats that define the explicit buckets
Args:
bounds (iterable[float]): initializes the bounds
Return:
:class:`endpoints_management.gen.servicecontrol_v1_messages.Distribution`
Raises:
... |
def fit1d(samples, e, remove_zeros = False, **kw):
"""Fits a 1D distribution with splines.
Input:
samples: Array
Array of samples from a probability distribution
e: Array
Edges that define the events in the probability
distribution. For example, e[0] < x <= ... | Fits a 1D distribution with splines.
Input:
samples: Array
Array of samples from a probability distribution
e: Array
Edges that define the events in the probability
distribution. For example, e[0] < x <= e[1] is
the range of values that are associate... |
def association_pivot(self, association_resource):
"""Pivot point on association for this resource.
This method will return all *resources* (group, indicators, task, victims, etc) for this
resource that are associated with the provided resource.
**Example Endpoints URI's**
+--... | Pivot point on association for this resource.
This method will return all *resources* (group, indicators, task, victims, etc) for this
resource that are associated with the provided resource.
**Example Endpoints URI's**
+---------+------------------------------------------------------... |
def needs_manager_helps():
"""Help message for Batch Dialog.
.. versionadded:: 3.2.1
:returns: A message object containing helpful information.
:rtype: messaging.message.Message
"""
message = m.Message()
message.add(m.Brand())
message.add(heading())
message.add(content())
retu... | Help message for Batch Dialog.
.. versionadded:: 3.2.1
:returns: A message object containing helpful information.
:rtype: messaging.message.Message |
def key_absent(name, region=None, key=None, keyid=None, profile=None):
'''
Deletes a key pair
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}
}
exists = __salt__['boto_ec2.get_key'](name, region, key, keyid, profile)
if exists:
... | Deletes a key pair |
def titlecase(text, callback=None, small_first_last=True):
"""
Titlecases input text
This filter changes all words to Title Caps, and attempts to be clever
about *un*capitalizing SMALL words like a/an/the in the input.
The list of "SMALL words" which are not capped comes from
the New York Time... | Titlecases input text
This filter changes all words to Title Caps, and attempts to be clever
about *un*capitalizing SMALL words like a/an/the in the input.
The list of "SMALL words" which are not capped comes from
the New York Times Manual of Style, plus 'vs' and 'v'. |
def p_namelist(self,t):
"namelist : namelist ',' NAME \n | NAME"
if len(t)==2: t[0] = [t[1]]
elif len(t)==4: t[0] = t[1] + [t[3]]
else: raise NotImplementedError('unk_len',len(t)) # pragma: no cover | namelist : namelist ',' NAME \n | NAME |
def upgrade(refresh=True, **kwargs):
'''
Upgrade outdated, unpinned brews.
refresh
Fetch the newest version of Homebrew and all formulae from GitHub before installing.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
... | Upgrade outdated, unpinned brews.
refresh
Fetch the newest version of Homebrew and all formulae from GitHub before installing.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
... |
def create_tomodir(self, directory):
"""Create a tomodir subdirectory structure in the given directory
"""
pwd = os.getcwd()
if not os.path.isdir(directory):
os.makedirs(directory)
os.chdir(directory)
directories = (
'config',
'exe',
... | Create a tomodir subdirectory structure in the given directory |
def _GetMountpoints(only_physical=True):
"""Fetches a list of mountpoints.
Args:
only_physical: Determines whether only mountpoints for physical devices
(e.g. hard disks) should be listed. If false, mountpoints for things such
as memory partitions or `/dev/shm` will be returned as well.
Returns:... | Fetches a list of mountpoints.
Args:
only_physical: Determines whether only mountpoints for physical devices
(e.g. hard disks) should be listed. If false, mountpoints for things such
as memory partitions or `/dev/shm` will be returned as well.
Returns:
A set of mountpoints. |
def getaddress(self):
"""Parse the next address."""
self.commentlist = []
self.gotonext()
oldpos = self.pos
oldcl = self.commentlist
plist = self.getphraselist()
self.gotonext()
returnlist = []
if self.pos >= len(self.field):
# Bad e... | Parse the next address. |
def count_lines_in_file(self, fname=''):
""" you wont believe what this method does """
i = 0
if fname == '':
fname = self.fullname
try:
#with open(fname, encoding="utf8") as f:
with codecs.open(fname, "r",encoding='utf8', errors='ignore') as f:
... | you wont believe what this method does |
def write_default_config(self, filename):
"""Write the default config file.
"""
try:
with open(filename, 'wt') as file:
file.write(DEFAULT_CONFIG)
return True
except (IOError, OSError) as e:
print('Error writing %s: %s' % (filename, e.s... | Write the default config file. |
def report(self, score_map, type="valid", epoch=-1, new_best=False):
"""
Report the scores and record them in the log.
"""
type_str = type
if len(type_str) < 5:
type_str += " " * (5 - len(type_str))
info = " ".join("%s=%.2f" % el for el in score_map.items())
... | Report the scores and record them in the log. |
def resize(self, width, height, **kwargs):
"""Resizes the image to the supplied width/height. Returns the
instance. Supports the following optional keyword arguments:
mode - The resizing mode to use, see Image.MODES
filter - The filter to use: see Image.FILTERS
background - The ... | Resizes the image to the supplied width/height. Returns the
instance. Supports the following optional keyword arguments:
mode - The resizing mode to use, see Image.MODES
filter - The filter to use: see Image.FILTERS
background - The hexadecimal background fill color, RGB or ARGB
... |
def MobileDeviceApplication(self, data=None, subset=None):
"""{dynamic_docstring}"""
return self.factory.get_object(jssobjects.MobileDeviceApplication,
data, subset) | {dynamic_docstring} |
def get_string_resources(self, package_name, locale='\x00\x00'):
"""
Get the XML (as string) of all resources of type 'string'.
Read more about string resources:
https://developer.android.com/guide/topics/resources/string-resource.html
:param package_name: the package name to g... | Get the XML (as string) of all resources of type 'string'.
Read more about string resources:
https://developer.android.com/guide/topics/resources/string-resource.html
:param package_name: the package name to get the resources for
:param locale: the locale to get the resources for (defa... |
def _get_data_by_field(self, field_number):
"""Return a data field by field number.
This is a useful method to get the values for fields that Ladybug
currently doesn't import by default. You can find list of fields by typing
EPWFields.fields
Args:
field_number: a va... | Return a data field by field number.
This is a useful method to get the values for fields that Ladybug
currently doesn't import by default. You can find list of fields by typing
EPWFields.fields
Args:
field_number: a value between 0 to 34 for different available epw fields.... |
def check_messages(*messages: str) -> Callable:
"""decorator to store messages that are handled by a checker method"""
def store_messages(func):
func.checks_msgs = messages
return func
return store_messages | decorator to store messages that are handled by a checker method |
def create(self):
"""Deploy a cluster on Amazon's EKS Service configured
for Jupyterhub Deployments.
"""
steps = [
(self.create_role, (), {}),
(self.create_vpc, (), {}),
(self.create_cluster, (), {}),
(self.create_node_group, (), {}),
... | Deploy a cluster on Amazon's EKS Service configured
for Jupyterhub Deployments. |
def _submit_metrics(self, metrics, metric_name_and_type_by_property):
"""
Resolve metric names and types and submit it.
"""
for metric in metrics:
if (
metric.name not in metric_name_and_type_by_property
and metric.name.lower() not in metric_na... | Resolve metric names and types and submit it. |
def netconf_config_change_changed_by_server_or_user_server_server(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
netconf_config_change = ET.SubElement(config, "netconf-config-change", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-notifications")
chang... | Auto Generated Code |
def hr_dp996(self, value=None):
""" Corresponds to IDD Field `hr_dp996`
humidity ratio, calculated at standard atmospheric pressure
at elevation of station, corresponding to
Dew-point temperature corresponding to 99.6% annual cumulative
frequency of occurrence (cold conditions)
... | Corresponds to IDD Field `hr_dp996`
humidity ratio, calculated at standard atmospheric pressure
at elevation of station, corresponding to
Dew-point temperature corresponding to 99.6% annual cumulative
frequency of occurrence (cold conditions)
Args:
value (float): val... |
def items(self):
"""
On Python 2.7+:
D.items() -> a set-like object providing a view on D's items
On Python 2.6:
D.items() -> an iterator over D's items
"""
if ver == (2, 7):
return self.viewitems()
elif ver == (2, 6):
retur... | On Python 2.7+:
D.items() -> a set-like object providing a view on D's items
On Python 2.6:
D.items() -> an iterator over D's items |
def _read_image_slice(self, arg):
"""
workhorse to read a slice
"""
if 'ndims' not in self._info:
raise ValueError("Attempt to slice empty extension")
if isinstance(arg, slice):
# one-dimensional, e.g. 2:20
return self._read_image_slice((arg,)... | workhorse to read a slice |
def _push_condition(predicate):
"""As we enter new conditions, this pushes them on the predicate stack."""
global _depth
_check_under_condition()
_depth += 1
if predicate is not otherwise and len(predicate) > 1:
raise PyrtlError('all predicates for conditional assignments must wirevectors of... | As we enter new conditions, this pushes them on the predicate stack. |
def validate(self, ticket=None):
"""
Validates all receipts matching this queryset.
Note that, due to how AFIP implements its numbering, this method is not
thread-safe, or even multiprocess-safe.
Because of this, it is possible that not all instances matching this
query... | Validates all receipts matching this queryset.
Note that, due to how AFIP implements its numbering, this method is not
thread-safe, or even multiprocess-safe.
Because of this, it is possible that not all instances matching this
queryset are validated properly. Obviously, only successfu... |
def ssh_check_mic(self, mic_token, session_id, username=None):
"""
Verify the MIC token for a SSH2 message.
:param str mic_token: The MIC token received from the client
:param str session_id: The SSH session ID
:param str username: The name of the user who attempts to login
... | Verify the MIC token for a SSH2 message.
:param str mic_token: The MIC token received from the client
:param str session_id: The SSH session ID
:param str username: The name of the user who attempts to login
:return: None if the MIC check was successful
:raises: ``sspi.error`` -... |
def check_roles(self, account, aws_policies, aws_roles):
"""Iterate through the roles of a specific account and create or update the roles if they're missing or
does not match the roles from Git.
Args:
account (:obj:`Account`): The account to check roles on
aws_policies ... | Iterate through the roles of a specific account and create or update the roles if they're missing or
does not match the roles from Git.
Args:
account (:obj:`Account`): The account to check roles on
aws_policies (:obj:`dict` of `str`: `dict`): A dictionary containing all the poli... |
def updateCurrentValue(self, value):
"""
Disables snapping during the current value update to ensure a smooth
transition for node animations. Since this can only be called via
code, we don't need to worry about snapping to the grid for a user.
"""
xsnap = None
ys... | Disables snapping during the current value update to ensure a smooth
transition for node animations. Since this can only be called via
code, we don't need to worry about snapping to the grid for a user. |
def min_rank(series, ascending=True):
"""
Equivalent to `series.rank(method='min', ascending=ascending)`.
Args:
series: column to rank.
Kwargs:
ascending (bool): whether to rank in ascending order (default is `True`).
"""
ranks = series.rank(method='min', ascending=ascending)
... | Equivalent to `series.rank(method='min', ascending=ascending)`.
Args:
series: column to rank.
Kwargs:
ascending (bool): whether to rank in ascending order (default is `True`). |
def parse_sidebar(self, user_page):
"""Parses the DOM and returns user attributes in the sidebar.
:type user_page: :class:`bs4.BeautifulSoup`
:param user_page: MAL user page's DOM
:rtype: dict
:return: User attributes
:raises: :class:`.InvalidUserError`, :class:`.MalformedUserPageError`
"... | Parses the DOM and returns user attributes in the sidebar.
:type user_page: :class:`bs4.BeautifulSoup`
:param user_page: MAL user page's DOM
:rtype: dict
:return: User attributes
:raises: :class:`.InvalidUserError`, :class:`.MalformedUserPageError` |
def process_request(self, request, client_address):
"""
Call finish_request.
"""
self.finish_request(request, client_address)
self.shutdown_request(request) | Call finish_request. |
def get_start_and_end_time(self, ref=None):
"""Specific function to get start time and end time for MonthWeekDayDaterange
:param ref: time in seconds
:type ref: int | None
:return: tuple with start and end time
:rtype: tuple
"""
now = time.localtime(ref)
... | Specific function to get start time and end time for MonthWeekDayDaterange
:param ref: time in seconds
:type ref: int | None
:return: tuple with start and end time
:rtype: tuple |
def cmd(send, msg, args):
"""Clears the verified admin list
Syntax: {command}
"""
args['db'].query(Permissions).update({"registered": False})
args['handler'].get_admins()
send("Verified admins reset.") | Clears the verified admin list
Syntax: {command} |
def get_context(self, url, expiration):
"""
Build template context with formatted feed content
"""
self._feed = self.get(url, expiration)
return {
self.feed_context_name: self.format_feed_content(self._feed),
} | Build template context with formatted feed content |
def gdaldem_mem_ma(ma, ds=None, res=None, extent=None, srs=None, processing='hillshade', returnma=False, computeEdges=False):
"""
Wrapper to allow gdaldem calculations for arbitrary NumPy masked array input
Untested, work in progress placeholder
Should only need to specify res, can caluclate local gt, c... | Wrapper to allow gdaldem calculations for arbitrary NumPy masked array input
Untested, work in progress placeholder
Should only need to specify res, can caluclate local gt, cartesian srs |
def check_file(self, filename):
# type: (str) -> bool
"""
Overrides :py:meth:`.Config.check_file`
"""
can_read = super(SecuredConfig, self).check_file(filename)
if not can_read:
return False
mode = get_stat(filename).st_mode
if (mode & stat.S_... | Overrides :py:meth:`.Config.check_file` |
def get_subnets_count(context, filters=None):
"""Return the number of subnets.
The result depends on the identity of the user making the request
(as indicated by the context) as well as any filters.
: param context: neutron api request context
: param filters: a dictionary with keys that are valid ... | Return the number of subnets.
The result depends on the identity of the user making the request
(as indicated by the context) as well as any filters.
: param context: neutron api request context
: param filters: a dictionary with keys that are valid keys for
a network as listed in the RESOURCE_... |
def fix_repeat_dt(dt_list, offset_s=0.001):
"""Add some small offset to remove duplicate times
Needed for xarray interp, which expects monotonically increasing times
"""
idx = (np.diff(dt_list) == timedelta(0))
while np.any(idx):
dt_list[idx.nonzero()[0] + 1] += timedelta(seconds=offset_s)
... | Add some small offset to remove duplicate times
Needed for xarray interp, which expects monotonically increasing times |
def run_timeit(self, stmt, setup):
""" Create the function call statement as a string used for timeit. """
_timer = timeit.Timer(stmt=stmt, setup=setup)
trials = _timer.repeat(self.timeit_repeat, self.timeit_number)
self.time_average_seconds = sum(trials) / len(trials) / self.timeit_numb... | Create the function call statement as a string used for timeit. |
def password_get(username=None):
"""
Retrieves a password from the keychain based on the environment and
configuration parameter pair.
If this fails, None is returned.
"""
password = keyring.get_password('supernova', username)
if password is None:
split_username = tuple(username.spl... | Retrieves a password from the keychain based on the environment and
configuration parameter pair.
If this fails, None is returned. |
def status_line(self):
"""
Returns a status line for an item.
Only really interesting when called for a draft
item as it can tell you if the draft is the same as
another version.
"""
date = self.date_published
status = self.state.title()
if self.... | Returns a status line for an item.
Only really interesting when called for a draft
item as it can tell you if the draft is the same as
another version. |
def autoparal_run(self):
"""
Find an optimal set of parameters for the execution of the task
This method can change the ABINIT input variables and/or the
submission parameters e.g. the number of CPUs for MPI and OpenMp.
Set:
self.pconfs where pconfs is a :class:`Paral... | Find an optimal set of parameters for the execution of the task
This method can change the ABINIT input variables and/or the
submission parameters e.g. the number of CPUs for MPI and OpenMp.
Set:
self.pconfs where pconfs is a :class:`ParalHints` object with the configuration reported... |
def from_pubkey(cls: Type[CRCPubkeyType], pubkey: str) -> CRCPubkeyType:
"""
Return CRCPubkey instance from public key string
:param pubkey: Public key
:return:
"""
hash_root = hashlib.sha256()
hash_root.update(base58.b58decode(pubkey))
hash_squared = has... | Return CRCPubkey instance from public key string
:param pubkey: Public key
:return: |
def get_output(src):
"""
parse lines looking for commands
"""
output = ''
lines = open(src.path, 'rU').readlines()
for line in lines:
m = re.match(config.import_regex,line)
if m:
include_path = os.path.abspath(src.dir + '/' + m.group('script'));
if include... | parse lines looking for commands |
def do_transition_for(brain_or_object, transition):
"""Performs a workflow transition for the passed in object.
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: The object where the transtion was performed
... | Performs a workflow transition for the passed in object.
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: The object where the transtion was performed |
def as_string(value):
"""Convert a value to a Unicode object for matching with a query.
None becomes the empty string. Bytestrings are silently decoded.
"""
if six.PY2:
buffer_types = buffer, memoryview # noqa: F821
else:
buffer_types = memoryview
if value is None:
retu... | Convert a value to a Unicode object for matching with a query.
None becomes the empty string. Bytestrings are silently decoded. |
def expand_cause_repertoire(self, new_purview=None):
"""See |Subsystem.expand_repertoire()|."""
return self.subsystem.expand_cause_repertoire(
self.cause.repertoire, new_purview) | See |Subsystem.expand_repertoire()|. |
def visibleCount(self):
"""
Returns the number of visible items in this list.
:return <int>
"""
return sum(int(not self.item(i).isHidden()) for i in range(self.count())) | Returns the number of visible items in this list.
:return <int> |
def fit_predict(self, y, exogenous=None, n_periods=10, **fit_args):
"""Fit an ARIMA to a vector, ``y``, of observations with an
optional matrix of ``exogenous`` variables, and then generate
predictions.
Parameters
----------
y : array-like or iterable, shape=(n_samples,)... | Fit an ARIMA to a vector, ``y``, of observations with an
optional matrix of ``exogenous`` variables, and then generate
predictions.
Parameters
----------
y : array-like or iterable, shape=(n_samples,)
The time-series to which to fit the ``ARIMA`` estimator. This may
... |
def REV(self, params):
"""
REV Ra, Rb
Reverse the byte order in register Rb and store the result in Ra
"""
Ra, Rb = self.get_two_parameters(self.TWO_PARAMETER_COMMA_SEPARATED, params)
self.check_arguments(low_registers=(Ra, Rb))
def REV_func():
self... | REV Ra, Rb
Reverse the byte order in register Rb and store the result in Ra |
def get_schema_input_format(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_schema = ET.Element("get_schema")
config = get_schema
input = ET.SubElement(get_schema, "input")
format = ET.SubElement(input, "format")
format.text =... | Auto Generated Code |
def execute(self, points, *args, **kwargs):
# TODO array of Points, (x, y) pairs of shape (N, 2)
"""
Parameters
----------
points: dict
Returns:
-------
Prediction array
Variance array
"""
if isinstance(self.model, OrdinaryKriging)... | Parameters
----------
points: dict
Returns:
-------
Prediction array
Variance array |
def call_ck(i):
"""
Input: {
Input for CK
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
(stdout) - stdout, if available
... | Input: {
Input for CK
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
(stdout) - stdout, if available
(stderr) - std... |
def instanceStarted(self, *args, **kwargs):
"""
Report an instance starting
An instance will report in by giving its instance id as well
as its security token. The token is given and checked to ensure
that it matches a real token that exists to ensure that random
machin... | Report an instance starting
An instance will report in by giving its instance id as well
as its security token. The token is given and checked to ensure
that it matches a real token that exists to ensure that random
machines do not check in. We could generate a different token
... |
def instancelist(obj_list, check=False, shared_attrs=None):
"""
Executes methods and attribute calls on a list of objects of the same type
Bundles a list of object of the same type into a single object.
The new object contains the same functions as each original object
but applies them to each elem... | Executes methods and attribute calls on a list of objects of the same type
Bundles a list of object of the same type into a single object.
The new object contains the same functions as each original object
but applies them to each element of the list independantly when called.
CommandLine:
pyt... |
def _head(self, uri):
"""
Handles the communication with the API when performing a HEAD request
on a specific resource managed by this class. Returns the headers
contained in the response.
"""
resp, resp_body = self.api.method_head(uri)
return resp | Handles the communication with the API when performing a HEAD request
on a specific resource managed by this class. Returns the headers
contained in the response. |
def _get_and_assert_slice_param(url_dict, param_name, default_int):
"""Return ``param_str`` converted to an int.
If str cannot be converted to int or int is not zero or positive, raise
InvalidRequest.
"""
param_str = url_dict['query'].get(param_name, default_int)
try:
n = int(param_str... | Return ``param_str`` converted to an int.
If str cannot be converted to int or int is not zero or positive, raise
InvalidRequest. |
def inputs(ctx, client, revision, paths):
r"""Show inputs files in the repository.
<PATHS> Files to show. If no files are given all input files are shown.
"""
from renku.models.provenance import ProcessRun
graph = Graph(client)
paths = set(paths)
nodes = graph.build(revision=revision)
... | r"""Show inputs files in the repository.
<PATHS> Files to show. If no files are given all input files are shown. |
def _expon_solve_lam_from_mu(mu, b):
"""
For the expon_uptrunc, given mu and b, return lam.
Similar to geom_uptrunc
"""
def lam_eq(lam, mu, b):
# Small offset added to denominator to avoid 0/0 erors
lam, mu, b = Decimal(lam), Decimal(mu), Decimal(b)
return ( (1 - (lam*b + 1)... | For the expon_uptrunc, given mu and b, return lam.
Similar to geom_uptrunc |
def GaussianLogDensity(x, mu, log_var, name='GaussianLogDensity', EPSILON = 1e-6):
'''GaussianLogDensity loss calculation for layer wise loss
'''
c = mx.sym.ones_like(log_var)*2.0 * 3.1416
c = mx.symbol.log(c)
var = mx.sym.exp(log_var)
x_mu2 = mx.symbol.square(x - mu) # [Issue] not sure the di... | GaussianLogDensity loss calculation for layer wise loss |
def size(self):
"""The size of the schema. If the underlying data source changes, it may be outdated.
"""
if self._size is None:
self._size = 0
for csv_file in self.files:
self._size += sum(1 if line else 0 for line in _util.open_local_or_gcs(csv_file, 'r'))
return self._size | The size of the schema. If the underlying data source changes, it may be outdated. |
def reflectance(self, band):
"""
:param band: An optical band, i.e. 1-5, 7
:return: At satellite reflectance, [-]
"""
if band == 6:
raise ValueError('LT5 reflectance must be other than band 6')
rad = self.radiance(band)
esun = self.ex_atm_irrad[band... | :param band: An optical band, i.e. 1-5, 7
:return: At satellite reflectance, [-] |
def _scrollView( self, value ):
"""
Updates the gantt view scrolling to the inputed value.
:param value | <int>
"""
if self._scrolling:
return
view_bar = self.uiGanttVIEW.verticalScrollBar()
self._scrolling = True
... | Updates the gantt view scrolling to the inputed value.
:param value | <int> |
def _init_db(self):
"""Creates the database tables."""
with self._get_db() as db:
with open(self.schemapath) as f:
db.cursor().executescript(f.read())
db.commit() | Creates the database tables. |
def timestampFormat(self, timestampFormat):
"""
Setter to _timestampFormat. Formatting string for conversion of timestamps to QtCore.QDateTime
Raises:
AssertionError: if timestampFormat is not of type unicode.
Args:
timestampFormat (unicode): assign timestampFor... | Setter to _timestampFormat. Formatting string for conversion of timestamps to QtCore.QDateTime
Raises:
AssertionError: if timestampFormat is not of type unicode.
Args:
timestampFormat (unicode): assign timestampFormat to _timestampFormat.
Formatting string for c... |
def WriteSignedBinaryBlobs(binary_urn,
blobs,
token = None):
"""Saves signed blobs to the datastore.
If a signed binary with the given URN already exists, its contents will get
overwritten.
Args:
binary_urn: RDFURN that should serve as a unique identif... | Saves signed blobs to the datastore.
If a signed binary with the given URN already exists, its contents will get
overwritten.
Args:
binary_urn: RDFURN that should serve as a unique identifier for the binary.
blobs: An Iterable of signed blobs to write to the datastore.
token: ACL token to use with t... |
def list_to_string(input, delimiter):
"""converts list to string recursively so that nested lists are supported
:param input: a list of strings and lists of strings (and so on recursive)
:type input: list
:param delimiter: the deimiter to use when joining the items
:type delimiter: str
:returns... | converts list to string recursively so that nested lists are supported
:param input: a list of strings and lists of strings (and so on recursive)
:type input: list
:param delimiter: the deimiter to use when joining the items
:type delimiter: str
:returns: the recursively joined list
:rtype: str |
def get_axes(process_or_domain):
"""Returns a dictionary of all Axis in a domain or dictionary of domains.
:param process_or_domain: a process or a domain object
:type process_or_domain: :class:`~climlab.process.process.Process` or
:class:`~climlab.domain.domain._Domain... | Returns a dictionary of all Axis in a domain or dictionary of domains.
:param process_or_domain: a process or a domain object
:type process_or_domain: :class:`~climlab.process.process.Process` or
:class:`~climlab.domain.domain._Domain`
:raises: :exc: `TypeE... |
def findall(obj, prs, forced_type=None,
cls=anyconfig.models.processor.Processor):
"""
:param obj:
a file path, file, file-like object, pathlib.Path object or an
'anyconfig.globals.IOInfo` (namedtuple) object
:param prs: A list of :class:`anyconfig.models.processor.Processor` cla... | :param obj:
a file path, file, file-like object, pathlib.Path object or an
'anyconfig.globals.IOInfo` (namedtuple) object
:param prs: A list of :class:`anyconfig.models.processor.Processor` classes
:param forced_type:
Forced processor type of the data to process or ID of the processor
... |
def find_file(folder, filename):
"""
Find a file given folder and filename. If the filename can be
resolved directly returns otherwise walks the supplied folder.
"""
matches = []
if os.path.isabs(filename) and os.path.isfile(filename):
return filename
for root, _, filenames in os.wal... | Find a file given folder and filename. If the filename can be
resolved directly returns otherwise walks the supplied folder. |
def define_snowflake_config():
'''Snowflake configuration.
See the Snowflake documentation for reference:
https://docs.snowflake.net/manuals/user-guide/python-connector-api.html
'''
account = Field(
String,
description='Your Snowflake account name. For more details, see https:... | Snowflake configuration.
See the Snowflake documentation for reference:
https://docs.snowflake.net/manuals/user-guide/python-connector-api.html |
def stack_decoders(self, *layers):
"""
Stack decoding layers.
"""
self.stack(*layers)
self.decoding_layers.extend(layers) | Stack decoding layers. |
def parse(text: str) -> Docstring:
"""
Parse the Google-style docstring into its components.
:returns: parsed docstring
"""
ret = Docstring()
if not text:
return ret
# Clean according to PEP-0257
text = inspect.cleandoc(text)
# Find first title and split on its position
... | Parse the Google-style docstring into its components.
:returns: parsed docstring |
def from_pandas(df, value='value', x='x', y='y', cellx=None, celly=None, xmin=None, ymax=None,
geot=None, nodata_value=None, projection=None, datatype=None):
"""
Creates a GeoRaster from a Pandas DataFrame. Useful to plot or export data to rasters.
Usage:
raster = from_pandas(df, val... | Creates a GeoRaster from a Pandas DataFrame. Useful to plot or export data to rasters.
Usage:
raster = from_pandas(df, value='value', x='x', y='y', cellx= cellx, celly=celly,
xmin=xmin, ymax=ymax, geot=geot, nodata_value=ndv,
projection=projection, d... |
def rget(d, key):
"""Recursively get keys from dict, for example:
'a.b.c' --> d['a']['b']['c'], return None if not exist.
"""
if not isinstance(d, dict):
return None
assert isinstance(key, str) or isinstance(key, list)
keys = key.split('.') if isinstance(key, str) else key
cdrs = cd... | Recursively get keys from dict, for example:
'a.b.c' --> d['a']['b']['c'], return None if not exist. |
def make_app(config=None):
"""
Factory function that creates a new `CoolmagicApplication`
object. Optional WSGI middlewares should be applied here.
"""
config = config or {}
app = CoolMagicApplication(config)
# static stuff
app = SharedDataMiddleware(
app, {"/public": path.join(... | Factory function that creates a new `CoolmagicApplication`
object. Optional WSGI middlewares should be applied here. |
def verify_tree_consistency(self, old_tree_size: int, new_tree_size: int,
old_root: bytes, new_root: bytes,
proof: Sequence[bytes]):
"""Verify the consistency between two root hashes.
old_tree_size must be <= new_tree_size.
Args:
... | Verify the consistency between two root hashes.
old_tree_size must be <= new_tree_size.
Args:
old_tree_size: size of the older tree.
new_tree_size: size of the newer_tree.
old_root: the root hash of the older tree.
new_root: the root hash of the newer tr... |
def get_firewall_rules(self, server):
"""
Return all FirewallRule objects based on a server instance or uuid.
"""
server_uuid, server_instance = uuid_and_instance(server)
url = '/server/{0}/firewall_rule'.format(server_uuid)
res = self.get_request(url)
return [
... | Return all FirewallRule objects based on a server instance or uuid. |
def registerPolling(self, fd, options = POLLING_IN|POLLING_OUT, daemon = False):
'''
register a polling file descriptor
:param fd: file descriptor or socket object
:param options: bit mask flags. Polling object should ignore the incompatible flag.
'''
se... | register a polling file descriptor
:param fd: file descriptor or socket object
:param options: bit mask flags. Polling object should ignore the incompatible flag. |
def _add_docstring(format_dict):
"""
Format a doc-string on the fly.
@arg format_dict: A dictionary to format the doc-strings
Example:
@add_docstring({'context': __doc_string_context})
def predict(x):
'''
{context}
>> model.predict(data)
'... | Format a doc-string on the fly.
@arg format_dict: A dictionary to format the doc-strings
Example:
@add_docstring({'context': __doc_string_context})
def predict(x):
'''
{context}
>> model.predict(data)
'''
return x |
def _execute(job, f, o=None):
"""
Executes a librsync "job" by reading bytes from `f` and writing results to
`o` if provided. If `o` is omitted, the output is ignored.
"""
# Re-use the same buffer for output, we will read from it after each
# iteration.
out = ctypes.create_string_buffer(RS_J... | Executes a librsync "job" by reading bytes from `f` and writing results to
`o` if provided. If `o` is omitted, the output is ignored. |
def _complete_exit(self, cmd, args, text):
"""Find candidates for the 'exit' command."""
if args:
return
return [ x for x in { 'root', 'all', } \
if x.startswith(text) ] | Find candidates for the 'exit' command. |
def pointwise_free_energies(self, therm_state=None):
r"""
Computes the pointwise free energies :math:`-\log(\mu^k(x))` for all points x.
:math:`\mu^k(x)` is the optimal estimate of the Boltzmann distribution
of the k'th ensemble defined on the set of all samples.
Parameters
... | r"""
Computes the pointwise free energies :math:`-\log(\mu^k(x))` for all points x.
:math:`\mu^k(x)` is the optimal estimate of the Boltzmann distribution
of the k'th ensemble defined on the set of all samples.
Parameters
----------
therm_state : int or None, default=No... |
def warning(f, *args, **kwargs):
"""Automatically log progress on function entry and exit. Default logging
value: warning.
*Logging with values contained in the parameters of the decorated function*
Message (args[0]) may be a string to be formatted with parameters passed to
the decorated function. ... | Automatically log progress on function entry and exit. Default logging
value: warning.
*Logging with values contained in the parameters of the decorated function*
Message (args[0]) may be a string to be formatted with parameters passed to
the decorated function. Each '{varname}' will be replaced by the... |
def get_mcu_definition(self, project_file):
""" Parse project file to get mcu definition """
project_file = join(getcwd(), project_file)
coproj_dic = xmltodict.parse(file(project_file), dict_constructor=dict)
mcu = MCU_TEMPLATE
IROM1_index = self._coproj_find_option(coproj_dic[... | Parse project file to get mcu definition |
def close (self, force=True): # File-like object.
"""This closes the connection with the child application. Note that
calling close() more than once is valid. This emulates standard Python
behavior with files. Set force to True if you want to make sure that
the child is terminated (SI... | This closes the connection with the child application. Note that
calling close() more than once is valid. This emulates standard Python
behavior with files. Set force to True if you want to make sure that
the child is terminated (SIGKILL is sent if the child ignores SIGHUP
and SIGINT). |
def warn_with_traceback(message, category, filename, lineno, file=None, line=None):
"""Get full tracebacks when warning is raised by setting
warnings.showwarning = warn_with_traceback
See also
--------
http://stackoverflow.com/questions/22373927/get-traceback-of-warnings
"""
import traceba... | Get full tracebacks when warning is raised by setting
warnings.showwarning = warn_with_traceback
See also
--------
http://stackoverflow.com/questions/22373927/get-traceback-of-warnings |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.