text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def get_maintenance_response(request):
"""
Return a '503 Service Unavailable' maintenance response.
"""
if settings.MAINTENANCE_MODE_REDIRECT_URL:
return redirect(settings.MAINTENANCE_MODE_REDIRECT_URL)
context = {}
if settings.MAINTENANCE_MODE_GET_TEMPLATE_CONTEXT:
try:
... | 0.000881 |
def delete(self, context):
"""
Undeploy application.
:param resort.engine.execution.Context context:
Current execution context.
"""
status_code, msg = self.__endpoint.delete(
"/applications/application/{}".format(self.__name)
)
self.__available = False | 0.06383 |
def frame_from_fsnative(arg):
"""Takes item from argv and returns ascii native str
or raises ValueError.
"""
assert isinstance(arg, fsnative)
text = fsn2text(arg, strict=True)
if PY2:
return text.encode("ascii")
else:
return text.encode("ascii").decode("ascii") | 0.003257 |
def reservation_reminder_24hrs(self):
"""
This method is for scheduler
every 1day scheduler will call this method to
find all tomorrow's reservations.
----------------------------------------------
@param self: The object pointer
@return: send a mail
"""
... | 0.001842 |
def aes_cbc_no_padding_decrypt(key, data, iv):
"""
Decrypts AES ciphertext in CBC mode using a 128, 192 or 256 bit key and no
padding.
:param key:
The encryption key - a byte string either 16, 24 or 32 bytes long
:param data:
The ciphertext - a byte string
:param iv:
T... | 0.000889 |
def checktext(sometext, interchange = ALL):
"""
Checks that some text is palindrome. Checking performs case-insensitive
:param str sometext:
It is some string that will be checked for palindrome as text.
What is the text see at help(palindromus.istext)
The text can be multiline.
... | 0.064122 |
def generate_dep_names(self, target: Target):
"""Generate names of all dependencies (descendants) of `target`."""
yield from sorted(get_descendants(self.target_graph, target.name)) | 0.010204 |
def _set_import_(self, v, load=False):
"""
Setter method for import_, mapped from YANG variable /rbridge_id/evpn_instance/route_target/import (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_import_ is considered as a private
method. Backends looking to populat... | 0.004092 |
def get_schema_path(schema, resolved=False):
"""Retrieve the installed path for the given schema.
Args:
schema(str): relative or absolute url of the schema to validate, for
example, 'records/authors.json' or 'jobs.json', or just the name of the
schema, like 'jobs'.
resol... | 0.002113 |
def get_lldp_neighbors_detail(self, interface=''):
"""
IOS implementation of get_lldp_neighbors_detail.
Calls get_lldp_neighbors.
"""
lldp = {}
lldp_neighbors = self.get_lldp_neighbors()
# Filter to specific interface
if interface:
lldp_data ... | 0.003545 |
def return_dat(self, chan, begsam, endsam):
"""Return the data as 2D numpy.ndarray.
Parameters
----------
chan : int or list
index (indices) of the channels to read
begsam : int
index of the first sample
endsam : int
index of the last ... | 0.002301 |
def cache(self):
"""
Persist this RDD with the default storage level (C{MEMORY_ONLY}).
"""
self.is_cached = True
self.persist(StorageLevel.MEMORY_ONLY)
return self | 0.009479 |
def parse_type(field):
"""
Function to pull a type from the binary payload.
"""
if field.type_id == 'string':
if 'size' in field.options:
return "parser.getString(%d)" % field.options['size'].value
else:
return "parser.getString()"
elif field.type_id in JAVA_TYPE_MAP:
# Primitive java ... | 0.013346 |
def get_limits(plottables,
xpadding=0,
ypadding=0.1,
xerror_in_padding=True,
yerror_in_padding=True,
snap=True,
logx=False,
logy=False,
logx_crop_value=1E-5,
logy_crop_value=1E-5,
... | 0.000163 |
def get():
"""Returns the current version without importing pymds."""
pkgnames = find_packages()
if len(pkgnames) == 0:
raise ValueError("Can't find any packages")
pkgname = pkgnames[0]
content = open(join(pkgname, '__init__.py')).read()
c = re.compile(r"__version__ *= *('[^']+'|\"[^\... | 0.002092 |
def get_soap_object(self, client):
""" Create and return a soap service type defined for this instance """
def to_soap_attribute(attr):
words = attr.split('_')
words = words[:1] + [word.capitalize() for word in words[1:]]
return ''.join(words)
soap_object = c... | 0.003795 |
def Instance(expected, message="Not an instance of {}"):
"""
Creates a validator that checks if the given value is an instance of
``expected``.
A custom message can be specified with ``message``.
"""
@wraps(Instance)
def built(value):
if not isinstance(value, expected):
... | 0.002475 |
def shorten_go_name_ptbl1(self, name):
"""Shorten GO name for tables in paper."""
if self._keep_this(name):
return name
name = name.replace("negative", "neg.")
name = name.replace("positive", "pos.")
name = name.replace("response", "rsp.")
name = name.replace(... | 0.004587 |
def system(**kwargs):
"""
Generally, this will automatically be added to a newly initialized
:class:`phoebe.frontend.bundle.Bundle`
:parameter **kwargs: defaults for the values of any of the parameters
:return: a :class:`phoebe.parameters.parameters.ParameterSet` of all newly
created :class... | 0.007181 |
def output_figure(array, as_subplot, output_path, output_filename, output_format):
"""Output the figure, either as an image on the screen or to the hard-disk as a .png or .fits file.
Parameters
-----------
array : ndarray
The 2D array of image to be output, required for outputting the image as ... | 0.005232 |
def gen_items_from_sql_csv(s: str) -> Generator[str, None, None]:
"""
Splits a comma-separated list of quoted SQL values, with ``'`` as the quote
character. Allows escaping of the quote character by doubling it. Returns
the quotes (and escaped quotes) as part of the result. Allows newlines etc.
with... | 0.000653 |
def decode_cursor(self, request):
"""
Given a request with a cursor, return a `Cursor` instance.
Differs from the standard CursorPagination to handle a tuple in the
position field.
"""
# Determine if we have a cursor, and if so then decode it.
encoded = request.q... | 0.001852 |
def get_symmetrized_structure(self):
"""
Get a symmetrized structure. A symmetrized structure is one where the
sites have been grouped into symmetrically equivalent groups.
Returns:
:class:`pymatgen.symmetry.structure.SymmetrizedStructure` object.
"""
ds = se... | 0.002817 |
def _GetAnalysisPlugins(self, analysis_plugins_string):
"""Retrieves analysis plugins.
Args:
analysis_plugins_string (str): comma separated names of analysis plugins
to enable.
Returns:
list[AnalysisPlugin]: analysis plugins.
"""
if not analysis_plugins_string:
return [... | 0.00361 |
def _avgConnectedSpanForColumn1D(self, columnIndex):
"""
The range of connected synapses for column. This is used to
calculate the inhibition radius. This variation of the function only
supports a 1 dimensional column topology.
Parameters:
----------------------------
:param columnIndex: ... | 0.004608 |
def object_patch_set_data(self, root, data, **kwargs):
"""Creates a new merkledag object based on an existing one.
The new object will have the same links as the old object but
with the provided data instead of the old object's data contents.
.. code-block:: python
>>> c.o... | 0.001847 |
def set_pubsub_channels(self, request, channels):
"""
Initialize the channels used for publishing and subscribing messages through the message queue.
"""
facility = request.path_info.replace(settings.WEBSOCKET_URL, '', 1)
# initialize publishers
audience = {
... | 0.003906 |
def _get_video_info(self):
"""
Returns basic information about the video as dictionary.
"""
if not hasattr(self, '_info_cache'):
encoding_backend = get_backend()
try:
path = os.path.abspath(self.path)
except AttributeError:
... | 0.004367 |
def _api_get(self):
"""
A helper method to GET this object from the server
"""
json = self._client.get(type(self).api_endpoint, model=self)
self._populate(json) | 0.01 |
def get_terminal_size():
"""
Get the terminal size in width and height. Works on Linux, Mac OS X, Windows, Cygwin (Windows).
:return: Returns a 2-tuple with width and height.
"""
import platform
current_os = platform.system()
tuple_xy = None
if current_os == 'Windows':
tuple... | 0.006964 |
def releasers(cls):
"""
Returns all of the supported releasers.
"""
return [
HookReleaser,
VersionFileReleaser,
PythonReleaser,
CocoaPodsReleaser,
NPMReleaser,
CReleaser,
ChangelogReleaser,
G... | 0.00542 |
def entity_tags_form(self, entity, ns=None):
"""Construct a form class with a field for tags in namespace `ns`."""
if ns is None:
ns = self.entity_default_ns(entity)
field = TagsField(label=_l("Tags"), ns=ns)
cls = type("EntityNSTagsForm", (_TagsForm,), {"tags": field})
... | 0.005988 |
def get_design_matrix(self, names=None, format='long', mode='both',
force=False, sampling_rate='TR', **kwargs):
''' Get design matrix and associated information.
Args:
names (list): Optional list of names of variables to include in the
returned desi... | 0.001099 |
def taper(self):
"""Taper the spectrum by adding zero throughput to each end.
This is similar to :meth:`TabularSourceSpectrum.taper`.
There is no check to see if the spectrum is already tapered.
Hence, calling this on a tapered spectrum will result in
multiple zero-throughput en... | 0.001542 |
def from_string(cls, contents, **kwargs):
"""
Given a markdown string, create an Entry object.
Usually subclasses will want to customize the parts of the markdown
where you provide values for attributes like public - this can be done
by overriding the process_meta method.
"""
lines = contents.splitlines(... | 0.02803 |
def search(self):
"""
Searchs current editor Widget for search pattern.
:return: Method success.
:rtype: bool
"""
editor = self.__container.get_current_editor()
search_pattern = self.Search_comboBox.currentText()
replacement_pattern = self.Replace_With_c... | 0.005089 |
def create_snapshot(self, name, tag):
"""
Create new instance of image with snaphot image (it is copied inside class constructuor)
:param name: str - name of image - not used now
:param tag: str - tag for image
:return: NspawnImage instance
"""
source = self.loca... | 0.004594 |
def get_parent(obj):
'''
get parent from obj.
'''
names = obj.__qualname__.split('.')[:-1]
if '<locals>' in names: # locals function
raise ValueError('cannot get parent from locals object.')
module = sys.modules[obj.__module__]
parent = module
while names:
parent = getatt... | 0.00554 |
def p_expr_binary_op(p):
'''expr : expr BOOLEAN_AND expr
| expr BOOLEAN_OR expr
| expr LOGICAL_AND expr
| expr LOGICAL_OR expr
| expr LOGICAL_XOR expr
| expr AND expr
| expr OR expr
| expr XOR expr
| expr CONCAT expr
... | 0.001079 |
def profile_fields(user):
"""
Returns profile fields as a dict for the given user. Used in the
profile view template when the ``ACCOUNTS_PROFILE_VIEWS_ENABLED``
setting is set to ``True``, and also in the account approval emails
sent to administrators when the ``ACCOUNTS_APPROVAL_REQUIRED``
sett... | 0.001167 |
def deserialize_tag(stream, header, verifier=None):
"""Deserialize the Tag value from a non-framed stream.
:param stream: Source data stream
:type stream: io.BytesIO
:param header: Deserialized header
:type header: aws_encryption_sdk.structures.MessageHeader
:param verifier: Signature verifier ... | 0.00316 |
def onLeftClickLabel(self, event):
"""
When user clicks on a grid label, determine if it is a row label or a col label.
Pass along the event to the appropriate function.
(It will either highlight a column for editing all values, or highlight a row for deletion).
"""
if ev... | 0.007737 |
def log(self, obj):
'''
Commit an arbitrary (picklable) object to the log
'''
entries = self.get()
entries.append(obj)
# Only log the last |n| entries if set
if self._size > 0:
entries = entries[-self._size:]
self._write_entries(entries) | 0.00639 |
def _list_paths(self, bucket, prefix):
""" Read config for list object api, paginate through list objects."""
s3 = self.s3
kwargs = {"Bucket": bucket, "Prefix": prefix}
if self.list_objects:
list_objects_api = "list_objects"
else:
list_objects_api = "list_... | 0.003289 |
def lookup_table(values, key=None, keyval=None, unique=False, use_lists=False):
"""
Builds a dict-based lookup table (index) elegantly.
Supports building normal and unique lookup tables. For example:
>>> assert lookup_table(
... ['foo', 'bar', 'baz', 'qux', 'quux'], lambda s: s[0]) == {
.... | 0.002378 |
def name(value):
"""Get the string title for a particular type.
Given a value, get an appropriate string title for the type that can
be used to re-cast the value later.
"""
if value is None:
return 'any'
for (test, name) in TESTS:
if isinstance(value, test):
return n... | 0.002915 |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
... | 0.002167 |
def distinct_frequencies(self):
"""Return frequencies for each distinct haplotype."""
c = self.distinct_counts()
n = self.shape[1]
return c / n | 0.011364 |
def upload_async(data_service_auth_data, config, upload_id,
filename, index, num_chunks_to_send, progress_queue):
"""
Method run in another process called from ParallelChunkProcessor.make_and_start_process.
:param data_service_auth_data: tuple of auth data for rebuilding DataServiceAuth
... | 0.006834 |
def spawn(self, aid, klass, *param, **kparam):
'''
This method creates an actor attached to this host. It will be
an instance of the class *klass* and it will be assigned an ID
that identifies it among the host.
This method can be called remotely synchronously.
:param s... | 0.000829 |
def collection_response(cls, resources, start=None, stop=None):
"""Return a response for the *resources* of the appropriate content type.
:param resources: resources to be returned in request
:type resource: list of :class:`sandman.model.Model`
:rtype: :class:`flask.Response`
"""
if _get_accep... | 0.00202 |
def dragDropFilter( self ):
"""
Returns a drag and drop filter method. If set, the method should \
accept 2 arguments: a QWidget and a drag/drop event and process it.
:usage |from projexui.qt.QtCore import QEvent
|
|class MyWi... | 0.012279 |
def threshold_gradients_pctile(self, thresh_pctile, min_mag=0.0):
"""Creates a new DepthImage by zeroing out all depths
where the magnitude of the gradient at that point is
greater than some percentile of all gradients.
Parameters
----------
thresh_pctile : float
... | 0.001838 |
def similarity(self, other):
"""Calculates the cosine similarity between this vector and another
vector."""
if self.magnitude == 0 or other.magnitude == 0:
return 0
return self.dot(other) / self.magnitude | 0.008032 |
def init_mysql_db(username, host, database, port='', password='', initTime=False):
"""
Initialize MySQL Database
.. note:: mysql-python or similar driver required
Args:
username(str): Database username.
host(str): Database host URL.
database(str): Database name.
... | 0.01173 |
def get_controller_by_id(self, id):
"""Get the controller object given the id.
This method returns the controller object for given id.
:param id: id of the controller, for example
'Smart Array P822 in Slot 2'
:returns: Controller object which has the id or None if the
... | 0.004024 |
def _handle_result(self, test, status, exception=None, message=None):
"""Create a :class:`~.TestResult` and add it to this
:class:`~ResultCollector`.
Parameters
----------
test : unittest.TestCase
The test that this result will represent.
status : haas.result... | 0.001316 |
def _previous(self, **kwargs):
""" Get the previous item in any particular category """
spec = self._pagination_default_spec(kwargs)
spec.update(kwargs)
query = queries.build_query(spec)
query = queries.where_before_entry(query, self._record)
for record in query.order_b... | 0.004202 |
def single(self):
"""Whether or not the user is only interested in people that are single.
"""
return 'display: none;' not in self._looking_for_xpb.li(id='ajax_single').\
one_(self._profile.profile_tree).attrib['style'] | 0.015686 |
def disk_cache(basename, directory, method=False):
"""
Function decorator for caching pickleable return values on disk. Uses a
hash computed from the function arguments for invalidation. If 'method',
skip the first argument, usually being self or cls. The cache filepath is
'directory/basename-hash.p... | 0.000867 |
def shiftImage(u, v, t, img, interpolation=cv2.INTER_LANCZOS4):
'''
remap an image using velocity field
'''
ny,nx = u.shape
sy, sx = np.mgrid[:float(ny):1,:float(nx):1]
sx += u*t
sy += v*t
return cv2.remap(img.astype(np.float32),
(sx).astype(np.float32),
... | 0.015915 |
def read_config(self):
"""
Read all configuration data
:return:
"""
section = "pypitools"
# read setup.cfg config file
config = configparser.ConfigParser()
homedir_filename = os.path.expanduser("~/.setup.cfg")
if os.path.isfile(homedir_filename):
... | 0.002237 |
def canonicalize_gates(gates: LogicalGates
) -> Dict[frozenset, LogicalGates]:
"""Canonicalizes a set of gates by the qubits they act on.
Takes a set of gates specified by ordered sequences of logical
indices, and groups those that act on the same qubits regardless of
order."""
... | 0.007022 |
def gridlines(ax, scale, multiple=None, horizontal_kwargs=None,
left_kwargs=None, right_kwargs=None, **kwargs):
"""
Plots grid lines excluding boundary.
Parameters
----------
ax: Matplotlib AxesSubplot, None
The subplot to draw on.
scale: float
Simplex scale size.
... | 0.001203 |
def validate(style, value, scalar=False):
"""
Validates a style and associated value.
Arguments
---------
style: str
The style to validate (e.g. 'color', 'size' or 'marker')
value:
The style value to validate
scalar: bool
Returns
-------
valid: boolean or None
... | 0.00312 |
def get(self, item):
"""
Returns the direct dependencies or dependents of a single item. Does not follow the entire dependency path.
:param item: Node to return dependencies for.
:return: Immediate dependencies or dependents.
"""
e = self._deps.get(item)
if e is ... | 0.007752 |
def process_reply(self, reply, status=None, description=None):
"""
Re-entry for processing a successful reply.
Depending on how the ``retxml`` option is set, may return the SOAP
reply XML or process it and return the Python object representing the
returned value.
@param... | 0.002635 |
def check_resource_subscription(self, device_id, _resource_path, **kwargs): # noqa: E501
"""Read subscription status # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.check_resourc... | 0.001684 |
def _fullname(o):
"""Return the fully-qualified name of a function."""
return o.__module__ + "." + o.__name__ if o.__module__ else o.__name__ | 0.006711 |
def provide_with_default(self, name, default=None):
""" Return a dependency-injected instance """
return self.provider.instantiate_by_name_with_default(name, default_value=default) | 0.015306 |
def local_path_from_url(url):
"""
For URLs that point to locations in the local filesystem, extract
and return the filesystem path of the object to which they point.
As a special case pass-through, if the URL is None, the return
value is None. Raises ValueError if the URL is not None and does
not point to a loca... | 0.028329 |
def check_files_on_host(java_home, host, files, batch_size):
"""Check the files on the host. Files are grouped together in groups
of batch_size files. The dump class will be executed on each batch,
sequentially.
:param java_home: the JAVA_HOME of the broker
:type java_home: str
:param host: the... | 0.000927 |
def receive_message(self, message: Message):
""" Handle a Raiden protocol message.
The protocol requires durability of the messages. The UDP transport
relies on the node's WAL for durability. The message will be converted
to a state change, saved to the WAL, and *processed* before the
... | 0.002473 |
def register(self, resource_name, dependent=None):
'''
Register the given dependent as depending on the "resource"
named by resource_name.
'''
if dependent is None:
# Give a partial usable as a decorator
return partial(self.register, resource_name)
... | 0.00349 |
def guess_bounds(params, **overrides):
"""
Given a dictionary of Parameter instances, return a corresponding
set of copies with the bounds appropriately set.
If given a set of override keywords, use those numeric tuple bounds.
"""
guessed = {}
for name, p in params.items():
new_par... | 0.003053 |
def discard(self, element):
"""Remove element from the RangeSet if it is a member.
If the element is not a member, do nothing.
"""
try:
i = int(element)
set.discard(self, i)
except ValueError:
pass | 0.007299 |
def get_relationship_bundle(manager, relationship_id=None, legacy=True):
"""
:param manager: Neo4jDBSessionManager
:param relationship_id: Internal Neo4j id
:param legacy: Backwards compatibility
:type relationship_id: int
:type legacy: bool
:rtype: dictionary
"""
q = """
M... | 0.000853 |
def delete_node(self, name):
"""Delete the specified node if it exists.
It is not an error if the node does not exist.
"""
name = self._validate_name(name)
if name in self.nodes:
del self.nodes[name] | 0.007905 |
async def update_device_data(self):
"""Update device data json."""
url = '{}/devices/{}?offlineView=true'.format(API_URL, self.deviceid)
# Check for access token expiration (every 15days)
exp_delta = datetime.strptime(self._expdate, '%Y-%m-%dT%H:%M:%S.%fZ') \
- datetime.from... | 0.002186 |
def spiro_image(R, r, r_, resolution=2*PI/1000, spins=50, size=[32, 32]):
'''Create image with given Spirograph parameters using numpy and scipy.
'''
x, y = give_dots(200, r, r_, spins=20)
xy = np.array([x, y]).T
xy = np.array(np.around(xy), dtype=np.int64)
xy = xy[(xy[:, 0] >= -250) & (xy[:, 1]... | 0.001764 |
def subdict(super_dict, keys):
"""
Returns a subset of the super_dict with the specified keys.
"""
sub_dict = {}
valid_keys = super_dict.keys()
for key in keys:
if key in valid_keys:
sub_dict[key] = super_dict[key]
return sub_dict | 0.003584 |
def rollback(self):
"""Drop changes from current transaction."""
if not self._in_transaction:
raise NotInTransaction
self._init_cache()
self._in_transaction = False | 0.009615 |
def or_filter(self, **filters):
"""
Works like "filter" but joins given filters with OR operator.
Args:
**filters: Query filters as keyword arguments.
Returns:
Self. Queryset object.
Example:
>>> Person.objects.or_filter(age__gte=16, name__s... | 0.004348 |
def build_grab_exception(ex, curl):
"""
Build Grab exception from the pycurl exception
Args:
ex - the original pycurl exception
curl - the Curl instance raised the exception
"""
# CURLE_WRITE_ERROR (23)
# An error occurred when writing received data to a local file, or
# an ... | 0.000547 |
def new(self, repo_type, name=None, make_default=False,
repository_class=None, aggregate_class=None,
configuration=None):
"""
Creates a new repository of the given type. If the root repository
domain (see :class:`everest.repositories.constants.REPOSITORY_DOMAINS`)
... | 0.002892 |
def _select_position(self, w, h):
"""
Select the position where the y coordinate of the top of the rectangle
is lower, if there are severtal pick the one with the smallest x
coordinate
"""
fitn = ((m.y+h, m.x, w, h, m) for m in self._max_rects
if self._... | 0.009383 |
def setup_continuous_delivery(self, swap_with_slot, app_type_details, cd_project_url, create_account,
vsts_app_auth_token, test, webapp_list):
"""
Use this method to setup Continuous Delivery of an Azure web site from a source control repository.
:param swap_wit... | 0.007382 |
def allocated_chunks(self):
"""
Returns an iterator over all the allocated chunks in the heap.
"""
raise NotImplementedError("%s not implemented for %s" % (self.allocated_chunks.__func__.__name__,
self.__class__.__name__)) | 0.012539 |
def to_binary(self, threshold=0.0):
"""Creates a BinaryImage from the depth image. Points where the depth
is greater than threshold are converted to ones, and all other points
are zeros.
Parameters
----------
threshold : float
The depth threshold.
Re... | 0.003257 |
def months_between(date1, date2, roundOff=True):
"""
Returns number of months between dates date1 and date2.
If date1 is later than date2, then the result is positive.
If date1 and date2 are on the same day of month, or both are the last day of month,
returns an integer (time of day will be ignored)... | 0.00444 |
def predict(self, u=0):
"""
Predict next position using the Kalman filter state propagation
equations for each filter in the bank.
Parameters
----------
u : np.array
Optional control vector. If non-zero, it is multiplied by B
to create the contro... | 0.003929 |
def asRGBA(self):
"""
Return image as RGBA pixels.
Greyscales are expanded into RGB triplets;
an alpha channel is synthesized if necessary.
The return values are as for the :meth:`read` method
except that the *metadata* reflect the returned pixels, not the
source... | 0.000941 |
def trt_pmf(matrices):
"""
Fold full disaggregation matrix to tectonic region type PMF.
:param matrices:
a matrix with T submatrices
:returns:
an array of T probabilities one per each tectonic region type
"""
ntrts, nmags, ndists, nlons, nlats, neps = matrices.shape
pmf = nu... | 0.003155 |
def compose(*functions):
"""Define functions composition like f ∘ g ∘ h
:return: callable object that will perform
function composition of callables given in argument.
"""
def _compose2(f, g): # pylint: disable=invalid-name
return lambda x: f(g(x))
return functools.reduce(_compose2, f... | 0.002924 |
def crud_fields(obj, fields=None):
"""
Display object fields in table rows::
<table>
{% crud_fields object 'id, %}
</table>
* ``fields`` fields to include
If fields is ``None`` all fields will be displayed.
If fields is ``string`` comma separated field names wi... | 0.001321 |
def matches(self, a, b, **config):
""" The message must match by username """
submitter_a = a['msg']['override']['submitter']['name']
submitter_b = b['msg']['override']['submitter']['name']
if submitter_a != submitter_b:
return False
return True | 0.006734 |
def add_directory(self, path, ignore=None):
"""Add ``*.py`` files under the directory ``path`` to the archive.
"""
for root, dirs, files in os.walk(path):
arc_prefix = os.path.relpath(root, os.path.dirname(path))
# py3 remove pyc cache dirs.
if '__pycache__' i... | 0.002635 |
def from_unicode(text, origin = root):
"""Convert unicode text into a Name object.
Lables are encoded in IDN ACE form.
@rtype: dns.name.Name object
"""
if not isinstance(text, unicode):
raise ValueError("input to from_unicode() must be a unicode string")
if not (origin is None or isin... | 0.002513 |
def update_config(self):
""" Updates or creates config of that group. Requires tree bound to db. """
dataset = self._top._config.dataset
session = object_session(self._top._config)
logger.debug(
'Updating group config. dataset: {}, type: {}, key: {}'.format(dataset.vid, self.... | 0.009317 |
def _container_candidates(self):
"""Generate container candidate list
Returns:
tuple list: [(width1, height1), (width2, height2), ...]
"""
if not self._rectangles:
return []
if self._rotation:
sides = sorted(side for rect in self._r... | 0.007987 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.