positive stringlengths 100 30.3k | anchor stringlengths 1 15k |
|---|---|
def user(self):
"""The current user.
This property is cached in the ``_user`` attribute.
"""
if self._user is not None:
return self._user
cert = self.transport.getPeerCertificate()
self._user = user = userForCert(self.store, cert)
return user | The current user.
This property is cached in the ``_user`` attribute. |
def _resolve_conflict(
self, incompatibility
): # type: (Incompatibility) -> Incompatibility
"""
Given an incompatibility that's satisfied by _solution,
The `conflict resolution`_ constructs a new incompatibility that encapsulates the root
cause of the conflict and backtrack... | Given an incompatibility that's satisfied by _solution,
The `conflict resolution`_ constructs a new incompatibility that encapsulates the root
cause of the conflict and backtracks _solution until the new
incompatibility will allow _propagate() to deduce new assignments.
Adds the new inc... |
def is_outdated(dist, dep=False):
"""Return a dict with outdated distributions
If the given distribution has dependencies, they are checked as well.
:param dist: a distribution to check
:type dist: :class:`pkg_resources.Distribution` | str
:param dep: If True, also return all outdated dependencies... | Return a dict with outdated distributions
If the given distribution has dependencies, they are checked as well.
:param dist: a distribution to check
:type dist: :class:`pkg_resources.Distribution` | str
:param dep: If True, also return all outdated dependencies. If False, only check given dist.
:t... |
def unfinished(finished_status,
update_interval,
table,
status_column,
edit_at_column):
"""
Create text sql statement query for sqlalchemy that getting all unfinished task.
:param finished_status: int, status code that less than this
will ... | Create text sql statement query for sqlalchemy that getting all unfinished task.
:param finished_status: int, status code that less than this
will be considered as unfinished.
:param update_interval: int, the record will be updated every x seconds.
:return: sqlalchemy text sql statement.
**中... |
def _choose_model_from_target_emotions(self):
"""
Initializes pre-trained deep learning model for the set of target emotions supplied by user.
"""
model_indices = [self.emotion_index_map[emotion] for emotion in self.target_emotions]
sorted_indices = [str(idx) for idx in sorted(mo... | Initializes pre-trained deep learning model for the set of target emotions supplied by user. |
def await_item_handle(self, original, loc, tokens):
"""Check for Python 3.5 await expression."""
internal_assert(len(tokens) == 1, "invalid await statement tokens", tokens)
if not self.target:
self.make_err(
CoconutTargetError,
"await requires a specif... | Check for Python 3.5 await expression. |
def main(global_config, **settings):
"""Main WSGI application factory."""
initialize_sentry_integration()
config = Configurator(settings=settings)
declare_api_routes(config)
declare_type_info(config)
# allowing the pyramid templates to render rss and xml
config.include('pyramid_jinja2')
... | Main WSGI application factory. |
def strptime(cls, date_string, fmt):
"""
This is opposite of the :py:meth:`khayyam.JalaliDate.strftime`,
and used to parse date strings into date object.
`ValueError` is raised if the date_string and format can’t be
parsed by time.strptime() or if it returns a value which isn’t ... | This is opposite of the :py:meth:`khayyam.JalaliDate.strftime`,
and used to parse date strings into date object.
`ValueError` is raised if the date_string and format can’t be
parsed by time.strptime() or if it returns a value which isn’t a time tuple. For a
complete list of formatting d... |
def demix1(servo1, servo2, gain=0.5):
'''de-mix a mixed servo output'''
s1 = servo1 - 1500
s2 = servo2 - 1500
out1 = (s1+s2)*gain
out2 = (s1-s2)*gain
return out1+1500 | de-mix a mixed servo output |
def build(term_to_index_dict):
'''
Parameters
----------
term_to_index_dict: term -> idx dictionary
Returns
-------
IndexStore
'''
idxstore = IndexStore()
idxstore._val2i = term_to_index_dict
idxstore._next_i = len(term_to_index_dict)
idxstore._i2val = [None for _ in range(idxstore._next_i)]
... | Parameters
----------
term_to_index_dict: term -> idx dictionary
Returns
-------
IndexStore |
def rt_update(self, statement, linenum, mode, xparser):
"""Uses the specified line parser to parse the given line.
:arg statement: a string of lines that are part of a single statement.
:arg linenum: the line number of the first line in the list relative to
the entire module contents.... | Uses the specified line parser to parse the given line.
:arg statement: a string of lines that are part of a single statement.
:arg linenum: the line number of the first line in the list relative to
the entire module contents.
arg mode: either 'insert', 'replace' or 'delete'
:... |
def _handle_start_relation(self, attrs):
"""
Handle opening relation element
:param attrs: Attributes of the element
:type attrs: Dict
"""
self._curr = {
'attributes': dict(attrs),
'members': [],
'rel_id': None,
'tags': {}
... | Handle opening relation element
:param attrs: Attributes of the element
:type attrs: Dict |
def open_with_encoding(filename, encoding, mode='r'):
"""Return opened file with a specific encoding."""
return io.open(filename, mode=mode, encoding=encoding,
newline='') | Return opened file with a specific encoding. |
def singularize(word):
"""
Converts the inputted word to the single form of it. This method works
best if you use the inflect module, as it will just pass along the
request to inflect.singular_noun. If you do not have that module, then a
simpler and less impressive singularization technique will ... | Converts the inputted word to the single form of it. This method works
best if you use the inflect module, as it will just pass along the
request to inflect.singular_noun. If you do not have that module, then a
simpler and less impressive singularization technique will be used.
:sa https... |
def modify_node(hostname, username, password, name,
connection_limit=None,
description=None,
dynamic_ratio=None,
logging=None,
monitor=None,
rate_limit=None,
ratio=None,
session=None,
... | A function to connect to a bigip device and modify an existing node.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the node to modify
connection_limit
[integer]
descr... |
def PyParseJoinList(string, location, tokens):
"""Return a joined token from a list of tokens.
This is a callback method for pyparsing setParseAction that modifies
the returned token list to join all the elements in the list to a single
token.
Args:
string (str): original string.
location (int): loc... | Return a joined token from a list of tokens.
This is a callback method for pyparsing setParseAction that modifies
the returned token list to join all the elements in the list to a single
token.
Args:
string (str): original string.
location (int): location in the string where the match was made.
to... |
def get_tagged(self, tags):
"""
Tag format.
The format for the tags list is tuples for tags: mongos, config, shard,
secondary tags of the form (tag, number), e.g. ('mongos', 2) which
references the second mongos in the list. For all other tags, it is
simply the string, e... | Tag format.
The format for the tags list is tuples for tags: mongos, config, shard,
secondary tags of the form (tag, number), e.g. ('mongos', 2) which
references the second mongos in the list. For all other tags, it is
simply the string, e.g. 'primary'. |
def add_property(self, prop, objects=()):
"""Add a property to the definition and add ``objects`` as related."""
self._properties.add(prop)
self._objects |= objects
self._pairs.update((o, prop) for o in objects) | Add a property to the definition and add ``objects`` as related. |
def set_source(self, propname, pores):
r"""
Applies a given source term to the specified pores
Parameters
----------
propname : string
The property name of the source term model to be applied
pores : array_like
The pore indices where the source t... | r"""
Applies a given source term to the specified pores
Parameters
----------
propname : string
The property name of the source term model to be applied
pores : array_like
The pore indices where the source term should be applied
Notes
--... |
def confirmation(self, pdu):
"""Message going upstream."""
if _debug: StreamToPacket._debug("StreamToPacket.confirmation %r", pdu)
# hack it up into chunks
for packet in self.packetize(pdu, self.upstreamBuffer):
self.response(packet) | Message going upstream. |
def detect_iter(self, det_iter, show_timer=False):
"""
detect all images in iterator
Parameters:
----------
det_iter : DetIter
iterator for all testing images
show_timer : Boolean
whether to print out detection exec time
Returns:
... | detect all images in iterator
Parameters:
----------
det_iter : DetIter
iterator for all testing images
show_timer : Boolean
whether to print out detection exec time
Returns:
----------
list of detection results |
def create_org_smarthost(self, orgid, data):
"""Create an organization smarthost"""
return self.api_call(
ENDPOINTS['orgsmarthosts']['new'],
dict(orgid=orgid),
body=data) | Create an organization smarthost |
def add_instruction (self, instr):
"""
Adds the argument instruction in the list of instructions of this basic block.
Also updates the variable lists (used_variables, defined_variables)
"""
assert(isinstance(instr, Instruction))
self.instruction_list.append(instr)
... | Adds the argument instruction in the list of instructions of this basic block.
Also updates the variable lists (used_variables, defined_variables) |
def set_atoms(self, a):
"""Assign an atoms object."""
for c in self.calcs:
if hasattr(c, "set_atoms"):
c.set_atoms(a) | Assign an atoms object. |
def parse_function(
name: str,
target: typing.Callable
) -> typing.Union[None, dict]:
"""
Parses the documentation for a function, which is specified by the name of
the function and the function itself.
:param name:
Name of the function to parse
:param target:
The fu... | Parses the documentation for a function, which is specified by the name of
the function and the function itself.
:param name:
Name of the function to parse
:param target:
The function to parse into documentation
:return:
A dictionary containing documentation for the specified fu... |
def cache_infos(self, queryset):
"""
Cache the number of entries published and the last
modification date under each tag.
"""
self.cache = {}
for item in queryset:
# If the sitemap is too slow, don't hesitate to do this :
# self.cache[item.pk] = ... | Cache the number of entries published and the last
modification date under each tag. |
def break_fiber(depth=0):
"""After calling break_fiber, get_state() will return None."""
set_stack_var(SECTION_BOUNDARY_TAG, True, depth=depth+1)
set_stack_var(SECTION_STATE_TAG, None, depth=depth+1) | After calling break_fiber, get_state() will return None. |
def predict(self, data):
"""
Predict new values by running data through the fit model.
Parameters
----------
data : pandas.DataFrame
Table with columns corresponding to the RHS of `model_expression`.
Returns
-------
predicted : ndarray
... | Predict new values by running data through the fit model.
Parameters
----------
data : pandas.DataFrame
Table with columns corresponding to the RHS of `model_expression`.
Returns
-------
predicted : ndarray
Array of predicted values. |
def generate_sky_catalog(image, refwcs, **kwargs):
"""Build source catalog from input image using photutils.
This script borrows heavily from build_source_catalog.
The catalog returned by this function includes sources found in all chips
of the input image with the positions translated to the coordina... | Build source catalog from input image using photutils.
This script borrows heavily from build_source_catalog.
The catalog returned by this function includes sources found in all chips
of the input image with the positions translated to the coordinate frame
defined by the reference WCS `refwcs`. The s... |
def main():
"""
Set up the context and connectors
"""
try:
init()
except custom_exceptions.NotConfigured:
configure()
init()
# Adding this in case users are trying to run without adding a jira url.
# I would like to take this out in a release or two.
# TODO: REMOV... | Set up the context and connectors |
def set_mode(path, mode):
'''
Set the mode of a file
This just calls get_mode, which returns None because we don't use mode on
Windows
Args:
path: The path to the file or directory
mode: The mode (not used)
Returns:
None
CLI Example:
.. code-block:: bash
... | Set the mode of a file
This just calls get_mode, which returns None because we don't use mode on
Windows
Args:
path: The path to the file or directory
mode: The mode (not used)
Returns:
None
CLI Example:
.. code-block:: bash
salt '*' file.set_mode /etc/passw... |
def fit(self, X, y, weights=None):
"""Fit the generalized additive model.
Parameters
----------
X : array-like, shape (n_samples, m_features)
Training vectors.
y : array-like, shape (n_samples,)
Target values,
ie integers in classification, re... | Fit the generalized additive model.
Parameters
----------
X : array-like, shape (n_samples, m_features)
Training vectors.
y : array-like, shape (n_samples,)
Target values,
ie integers in classification, real numbers in
regression)
... |
def parse_tables(self):
"""
Parse and return all tables from the DOM.
Returns
-------
list of parsed (header, body, footer) tuples from tables.
"""
tables = self._parse_tables(self._build_doc(), self.match, self.attrs)
return (self._parse_thead_tbody_tfoo... | Parse and return all tables from the DOM.
Returns
-------
list of parsed (header, body, footer) tuples from tables. |
def ServicesSetMetod (self, sensor_id, service_id, method, parameters):
"""
Set expression for the math service.
@param sensor_id (int) - Sensor id of the sensor the service is connected to.
@param service_id (int) - Service id of the service for which to se... | Set expression for the math service.
@param sensor_id (int) - Sensor id of the sensor the service is connected to.
@param service_id (int) - Service id of the service for which to set the expression.
@param method (string) - The set method name.
@param p... |
def reset(self):
""" Re-initialises the environment.
"""
logger.info("Reseting environment.")
self._step = 0
# Reset the set-point of each generator to its original value.
gs = [g for g in self.case.online_generators if g.bus.type !=REFERENCE]
for i, g in enumer... | Re-initialises the environment. |
def are_token_parallel(sequences: Sequence[Sized]) -> bool:
"""
Returns True if all sequences in the list have the same length.
"""
if not sequences or len(sequences) == 1:
return True
return all(len(s) == len(sequences[0]) for s in sequences) | Returns True if all sequences in the list have the same length. |
def check_api_version(self):
"""
Self check that the client expects the api version used by the
server. /status/ is available without authentication so it
will not interfere with hello.
"""
url = self.base_url + "/status/"
juicer.utils.Log.log_debug("[REST:GET:%s]... | Self check that the client expects the api version used by the
server. /status/ is available without authentication so it
will not interfere with hello. |
def get_vnetwork_vms_input_datacenter(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vnetwork_vms = ET.Element("get_vnetwork_vms")
config = get_vnetwork_vms
input = ET.SubElement(get_vnetwork_vms, "input")
datacenter = ET.SubElement(... | Auto Generated Code |
def stopProducing(self):
"""
Stop producing messages and disconnect from the server.
Returns:
Deferred: fired when the production is stopped.
"""
_legacy_twisted_log.msg("Disconnecting from the AMQP broker")
yield self.pauseProducing()
yield self.close... | Stop producing messages and disconnect from the server.
Returns:
Deferred: fired when the production is stopped. |
def register_type_name(t, name):
""" Register a human-friendly name for the given type. This will be used in Invalid errors
:param t: The type to register
:type t: type
:param name: Name for the type
:type name: unicode
"""
assert isinstance(t, type)
assert isinstance(name, unicode)
... | Register a human-friendly name for the given type. This will be used in Invalid errors
:param t: The type to register
:type t: type
:param name: Name for the type
:type name: unicode |
def generate_certificate(common_name, size=DEFAULT_KEY_SIZE):
'''
Generate private key and certificate for https
'''
private_key_path = '{}/{}.key'.format(CERTIFICATES_PATH, common_name)
certificate_path = '{}/{}.crt'.format(CERTIFICATES_PATH, common_name)
if not os.path.isfile(certificate_... | Generate private key and certificate for https |
def remove_prefix(self, prefix):
"""Removes prefix from this set. This is a no-op if the prefix
doesn't exist in it.
"""
if prefix not in self.__prefix_map:
return
ni = self.__lookup_prefix(prefix)
ni.prefixes.discard(prefix)
del self.__prefix_map[pr... | Removes prefix from this set. This is a no-op if the prefix
doesn't exist in it. |
def create_network(batch_size, update_freq):
"""Create a linear regression network for performing SVRG optimization.
:return: an instance of mx.io.NDArrayIter
:return: an instance of mx.mod.svrgmodule for performing SVRG optimization
"""
head = '%(asctime)-15s %(message)s'
logging.basicConfig(le... | Create a linear regression network for performing SVRG optimization.
:return: an instance of mx.io.NDArrayIter
:return: an instance of mx.mod.svrgmodule for performing SVRG optimization |
def _bp_static_url(blueprint):
""" builds the absolute url path for a blueprint's static folder """
u = six.u('%s%s' % (blueprint.url_prefix or '', blueprint.static_url_path or ''))
return u | builds the absolute url path for a blueprint's static folder |
def parse_stream(self, stream: BytesIO, context=None):
"""
Parse some python object from the stream.
:param stream: Stream from which the data is read and parsed.
:param context: Optional context dictionary.
"""
if context is None:
context = Context()
... | Parse some python object from the stream.
:param stream: Stream from which the data is read and parsed.
:param context: Optional context dictionary. |
def make_gaussian_kernel(sigma, npix=501, cdelt=0.01, xpix=None, ypix=None):
"""Make kernel for a 2D gaussian.
Parameters
----------
sigma : float
Standard deviation in degrees.
"""
sigma /= cdelt
def fn(t, s): return 1. / (2 * np.pi * s ** 2) * np.exp(
-t ** 2 / (s ** 2 * ... | Make kernel for a 2D gaussian.
Parameters
----------
sigma : float
Standard deviation in degrees. |
def configure():
'''
Configures the logging facility
This function will setup an initial logging facility for handling display
and debug outputs. The default facility will send display messages to
stdout and the default debug facility will do nothing.
:returns: None
'''
root_logger = ... | Configures the logging facility
This function will setup an initial logging facility for handling display
and debug outputs. The default facility will send display messages to
stdout and the default debug facility will do nothing.
:returns: None |
def scope(self, cleanup=True):
"""This helper method can be used with the context object to promote
it to the current thread local (see :func:`get_current_context`).
The default behavior of this is to invoke the cleanup functions which
can be disabled by setting `cleanup` to `False`. Th... | This helper method can be used with the context object to promote
it to the current thread local (see :func:`get_current_context`).
The default behavior of this is to invoke the cleanup functions which
can be disabled by setting `cleanup` to `False`. The cleanup
functions are typically ... |
def convex_hull_image(image):
'''Given a binary image, return an image of the convex hull'''
labels = image.astype(int)
points, counts = convex_hull(labels, np.array([1]))
output = np.zeros(image.shape, int)
for i in range(counts[0]):
inext = (i+1) % counts[0]
draw_line(output, point... | Given a binary image, return an image of the convex hull |
def find(pattern, root=os.curdir):
'''Helper around 'locate' '''
hits = ''
for F in locate(pattern, root):
hits = hits + F + '\n'
l = hits.split('\n')
if(not len(l[-1])): l.pop()
if len(l) == 1 and not len(l[0]):
return None
else:
return l | Helper around 'locate' |
def create_media_assetfile(access_token, parent_asset_id, name, is_primary="false", \
is_encrypted="false", encryption_scheme="None", encryptionkey_id="None"):
'''Create Media Service Asset File.
Args:
access_token (str): A valid Azure authentication token.
parent_asset_id (str): Media Service ... | Create Media Service Asset File.
Args:
access_token (str): A valid Azure authentication token.
parent_asset_id (str): Media Service Parent Asset ID.
name (str): Media Service Asset Name.
is_primary (str): Media Service Primary Flag.
is_encrypted (str): Media Service Encrypti... |
def pi_zoom_origin(self, viewer, event, msg=True):
"""Like pi_zoom(), but pans the image as well to keep the
coordinate under the cursor in that same position relative
to the window.
"""
origin = (event.data_x, event.data_y)
return self._pinch_zoom_rotate(viewer, event.st... | Like pi_zoom(), but pans the image as well to keep the
coordinate under the cursor in that same position relative
to the window. |
def _parse_tables(cls, parsed_content):
"""
Parses the information tables found in a world's information page.
Parameters
----------
parsed_content: :class:`bs4.BeautifulSoup`
A :class:`BeautifulSoup` object containing all the content.
Returns
------... | Parses the information tables found in a world's information page.
Parameters
----------
parsed_content: :class:`bs4.BeautifulSoup`
A :class:`BeautifulSoup` object containing all the content.
Returns
-------
:class:`OrderedDict`[:class:`str`, :class:`list`[:... |
def stem(self, words, parser, **kwargs):
"""
Get stems for the words using a given parser
Example:
from .parsing import ListParser
parser = ListParser()
stemmer = Morfologik()
stemmer.stem(['ja tańczę a ona śpi], parser)
[
... | Get stems for the words using a given parser
Example:
from .parsing import ListParser
parser = ListParser()
stemmer = Morfologik()
stemmer.stem(['ja tańczę a ona śpi], parser)
[
('ja': ['ja']),
('tańczę': ['tańczyć'... |
def makedir(self, dir_name, mode=PERM_DEF):
"""Create a leaf Fake directory.
Args:
dir_name: (str) Name of directory to create.
Relative paths are assumed to be relative to '/'.
mode: (int) Mode to create directory with. This argument defaults
to... | Create a leaf Fake directory.
Args:
dir_name: (str) Name of directory to create.
Relative paths are assumed to be relative to '/'.
mode: (int) Mode to create directory with. This argument defaults
to 0o777. The umask is applied to this mode.
Rai... |
def _delete(self, _file_path, _method_title, _record_key):
'''
a helper method for non-blocking deletion of files
:param _file_path: string with path to file to remove
:param _method_title: string with name of method calling _delete
:param _record_key: s... | a helper method for non-blocking deletion of files
:param _file_path: string with path to file to remove
:param _method_title: string with name of method calling _delete
:param _record_key: string with name of record key to delete
:return: None |
def get_relative_airmass(altitude, model='kastenyoung1989'):
"""
Gives the relative (not pressure-corrected) airmass.
Gives the airmass at sea-level when given a sun altitude angle (in
degrees). The ``model`` variable allows selection of different
airmass models (described below). If ``model`` is n... | Gives the relative (not pressure-corrected) airmass.
Gives the airmass at sea-level when given a sun altitude angle (in
degrees). The ``model`` variable allows selection of different
airmass models (described below). If ``model`` is not included or is
not valid, the default model is 'kastenyoung1989'.
... |
def multi_get(self, urls, query_params=None, to_json=True):
"""Issue multiple GET requests.
Args:
urls - A string URL or list of string URLs
query_params - None, a dict, or a list of dicts representing the query params
to_json - A boolean, should the responses be ret... | Issue multiple GET requests.
Args:
urls - A string URL or list of string URLs
query_params - None, a dict, or a list of dicts representing the query params
to_json - A boolean, should the responses be returned as JSON blobs
Returns:
a list of dicts if to_... |
def valid_config_exists(config_path=CONFIG_PATH):
"""Verify that a valid config file exists.
Args:
config_path (str): Path to the config file.
Returns:
boolean: True if there is a valid config file, false if not.
"""
if os.path.isfile(config_path):
try:
config =... | Verify that a valid config file exists.
Args:
config_path (str): Path to the config file.
Returns:
boolean: True if there is a valid config file, false if not. |
def extract_named_group(text, named_group, matchers, return_presence=False):
''' Return ``named_group`` match from ``text`` reached
by using a matcher from ``matchers``.
It also supports matching without a ``named_group`` in a matcher,
which sets ``presence=True``.
``presence`` is ... | Return ``named_group`` match from ``text`` reached
by using a matcher from ``matchers``.
It also supports matching without a ``named_group`` in a matcher,
which sets ``presence=True``.
``presence`` is only returned if ``return_presence=True``. |
def find_TPs_and_DUPs(self, percent=5., makefig=False):
"""
Function which finds TPs and uses the calc_DUP_parameter
function. To calculate DUP parameter evolution dependent of
the star or core mass.
Parameters
----------
fig : integer
Figure number ... | Function which finds TPs and uses the calc_DUP_parameter
function. To calculate DUP parameter evolution dependent of
the star or core mass.
Parameters
----------
fig : integer
Figure number to plot.
t0_model : integer
First he-shell lum peak.
... |
def get_configuration(self):
"""Returns a mapping of UID -> configuration
"""
mapping = {}
settings = self.get_settings()
for record in self.context.getAnalyses():
uid = record.get("service_uid")
setting = settings.get(uid, {})
config = {
... | Returns a mapping of UID -> configuration |
def set_link(self):
"""Parses link to homepage and set value"""
try:
self.link = self.soup.find('link').string
except AttributeError:
self.link = None | Parses link to homepage and set value |
def page_for_in(self, leaderboard_name, member,
page_size=DEFAULT_PAGE_SIZE):
'''
Determine the page where a member falls in the named leaderboard.
@param leaderboard [String] Name of the leaderboard.
@param member [String] Member name.
@param page_size [int]... | Determine the page where a member falls in the named leaderboard.
@param leaderboard [String] Name of the leaderboard.
@param member [String] Member name.
@param page_size [int] Page size to be used in determining page location.
@return the page where a member falls in the leaderboard. |
def calc_rk_v1(self):
"""Determine the actual traveling time of the water (not of the wave!).
Required derived parameter:
|Sek|
Required flux sequences:
|AG|
|QRef|
Calculated flux sequence:
|RK|
Basic equation:
:math:`RK = \\frac{Laen \\cdot A}{QRef}`
Examples... | Determine the actual traveling time of the water (not of the wave!).
Required derived parameter:
|Sek|
Required flux sequences:
|AG|
|QRef|
Calculated flux sequence:
|RK|
Basic equation:
:math:`RK = \\frac{Laen \\cdot A}{QRef}`
Examples:
First, note that t... |
def _get_writable_metadata(self):
"""Get the object / blob metadata which is writable.
This is intended to be used when creating a new object / blob.
See the `API reference docs`_ for more information, the fields
marked as writable are:
* ``acl``
* ``cacheControl``
... | Get the object / blob metadata which is writable.
This is intended to be used when creating a new object / blob.
See the `API reference docs`_ for more information, the fields
marked as writable are:
* ``acl``
* ``cacheControl``
* ``contentDisposition``
* ``con... |
def _copy(self):
"""Create and return a new copy of the Bits (always in memory)."""
s_copy = self.__class__()
s_copy._setbytes_unsafe(self._datastore.getbyteslice(0, self._datastore.bytelength),
self.len, self._offset)
return s_copy | Create and return a new copy of the Bits (always in memory). |
def initialise(self, other):
"""Initialise a :py:class:`Frame` from another :py:class:`Frame`.
Copies the metadata and (a reference to) the data from
:py:obj:`other`. Note that the data is not actually copied --
you must make a copy of the data before changing it.
:param Frame ... | Initialise a :py:class:`Frame` from another :py:class:`Frame`.
Copies the metadata and (a reference to) the data from
:py:obj:`other`. Note that the data is not actually copied --
you must make a copy of the data before changing it.
:param Frame other: The frame to copy. |
def issue(self, CorpNum, ItemCode, MgtKey, Memo=None, EmailSubject=None, UserID=None):
""" 발행
args
CorpNum : 팝빌회원 사업자번호
ItemCode : 명세서 종류 코드
[121 - 거래명세서], [122 - 청구서], [123 - 견적서],
[124 - 발주서], [125 - 입금표], [126 - 영수증]
... | 발행
args
CorpNum : 팝빌회원 사업자번호
ItemCode : 명세서 종류 코드
[121 - 거래명세서], [122 - 청구서], [123 - 견적서],
[124 - 발주서], [125 - 입금표], [126 - 영수증]
MgtKey : 파트너 문서관리번호
Memo : 처리메모
EmailSubject : 발행메일... |
def std(self, ddof=1, *args, **kwargs):
"""
Compute standard deviation of groups, excluding missing values.
Parameters
----------
ddof : integer, default 1
Degrees of freedom.
"""
nv.validate_resampler_func('std', args, kwargs)
return self._do... | Compute standard deviation of groups, excluding missing values.
Parameters
----------
ddof : integer, default 1
Degrees of freedom. |
def steepest_descent(A, b, x0=None, tol=1e-5, maxiter=None, xtype=None, M=None,
callback=None, residuals=None):
"""Steepest descent algorithm.
Solves the linear system Ax = b. Left preconditioning is supported.
Parameters
----------
A : array, matrix, sparse matrix, LinearOper... | Steepest descent algorithm.
Solves the linear system Ax = b. Left preconditioning is supported.
Parameters
----------
A : array, matrix, sparse matrix, LinearOperator
n x n, linear system to solve
b : array, matrix
right hand side, shape is (n,) or (n,1)
x0 : array, matrix
... |
def Set(self, value, fields=None):
"""Sets the metric's current value."""
self._metric_values[_FieldsToKey(fields)] = self._value_type(value) | Sets the metric's current value. |
def change_analysis_requests_id_formatting(portal, p_type="AnalysisRequest"):
"""Applies the system's Sample ID Formatting to Analysis Request
"""
ar_id_format = dict(
form='{sampleType}-{seq:04d}',
portal_type='AnalysisRequest',
prefix='analysisrequest',
sequence_type='gener... | Applies the system's Sample ID Formatting to Analysis Request |
def unquote_redirection_tokens(args: List[str]) -> None:
"""
Unquote redirection tokens in a list of command-line arguments
This is used when redirection tokens have to be passed to another command
:param args: the command line args
"""
for i, arg in enumerate(args):
unquoted_arg = strip... | Unquote redirection tokens in a list of command-line arguments
This is used when redirection tokens have to be passed to another command
:param args: the command line args |
def execute(self, slave_id, route_map):
""" Execute the Modbus function registered for a route.
:param slave_id: Slave id.
:param eindpoint: Instance of modbus.route.Map.
"""
endpoint = route_map.match(slave_id, self.function_code, self.address)
try:
endpoint... | Execute the Modbus function registered for a route.
:param slave_id: Slave id.
:param eindpoint: Instance of modbus.route.Map. |
def filter_active(self, *args, **kwargs):
"""
Return only the 'active' hits.
How you count a hit/view will depend on personal choice: Should the
same user/visitor *ever* be counted twice? After a week, or a month,
or a year, should their view be counted again?
The defa... | Return only the 'active' hits.
How you count a hit/view will depend on personal choice: Should the
same user/visitor *ever* be counted twice? After a week, or a month,
or a year, should their view be counted again?
The defaulf is to consider a visitor's hit still 'active' if they
... |
def model_counts_spectrum(self, name, logemin, logemax, weighted=False):
"""Return the model counts spectrum of a source.
Parameters
----------
name : str
Source name.
"""
# EAC, we need this b/c older version of the ST don't have the right signature
... | Return the model counts spectrum of a source.
Parameters
----------
name : str
Source name. |
def add(self, error):
""" Add an error to the tree.
:param error: :class:`~cerberus.errors.ValidationError`
"""
if not self._path_of_(error):
self.errors.append(error)
self.errors.sort()
else:
super(ErrorTree, self).add(error) | Add an error to the tree.
:param error: :class:`~cerberus.errors.ValidationError` |
def get_next_upper_library_root_state(self):
""" Get next upper library root state
The method recursively checks state parent states till finding a StateMachine as parent or a library root state.
If self is a LibraryState the next upper library root state is searched and it is not handed self.s... | Get next upper library root state
The method recursively checks state parent states till finding a StateMachine as parent or a library root state.
If self is a LibraryState the next upper library root state is searched and it is not handed self.state_copy.
:return library root state (Execution... |
def _encode_utf8(self, **kwargs):
"""
UTF8 encodes all of the NVP values.
"""
if is_py3:
# This is only valid for Python 2. In Python 3, unicode is
# everywhere (yay).
return kwargs
unencoded_pairs = kwargs
for i in unencoded_pairs.key... | UTF8 encodes all of the NVP values. |
def _initialize_session(self):
"""
Creates a session using available authentication type.
Auth priority:
1. Token Auth
2. Tenant Auth
3. Azure CLI Auth
"""
# Only run once
if self.credentials is not None:
return
tenant_auth_... | Creates a session using available authentication type.
Auth priority:
1. Token Auth
2. Tenant Auth
3. Azure CLI Auth |
def keypair_add(self, name, pubfile=None, pubkey=None):
'''
Add a keypair
'''
nt_ks = self.compute_conn
if pubfile:
with salt.utils.files.fopen(pubfile, 'r') as fp_:
pubkey = salt.utils.stringutils.to_unicode(fp_.read())
if not pubkey:
... | Add a keypair |
def add_group_email_grant(self, permission, email_address, headers=None):
"""
Convenience method that provides a quick way to add an email group
grant to a key. This method retrieves the current ACL, creates a new
grant based on the parameters passed in, adds that grant to the ACL and
... | Convenience method that provides a quick way to add an email group
grant to a key. This method retrieves the current ACL, creates a new
grant based on the parameters passed in, adds that grant to the ACL and
then PUT's the new ACL back to GS.
:type permission: string
:param perm... |
def get_at_url(self, url):
"""
Return a object representing the content at url.
Returns None if no object could be matched with the id.
Works for Album, Comment, Gallery_album, Gallery_image, Image and User.
NOTE: Imgur's documentation does not cover what urls are available.
... | Return a object representing the content at url.
Returns None if no object could be matched with the id.
Works for Album, Comment, Gallery_album, Gallery_image, Image and User.
NOTE: Imgur's documentation does not cover what urls are available.
Some urls, such as imgur.com/<ID> can be... |
def get_pixel_bounds_from_datasec_keyword(datasec):
"""
Return the x/y pixel boundaries of the data section.
:param datasec: str e.g. '[33:2080,1:4612]'
:return: ((xmin,xmax),(ymin,ymax))
"""
datasec = re.findall(r'(\d+)', datasec)
x1 = min(int(datasec[0]), int(datasec[1]))
x2 = max(int(... | Return the x/y pixel boundaries of the data section.
:param datasec: str e.g. '[33:2080,1:4612]'
:return: ((xmin,xmax),(ymin,ymax)) |
def integrate_to_file(what, filename, start_line, end_line):
"""WARNING this is working every second run.. so serious bug
Integrate content into a file withing "line marks"
"""
try:
with open(filename) as f:
lines = f.readlines()
except IOError:
lines = []
tmp_file ... | WARNING this is working every second run.. so serious bug
Integrate content into a file withing "line marks" |
def zeros(shape, ctx=None, dtype=None, **kwargs):
"""Returns a new array filled with all zeros, with the given shape and type.
Parameters
----------
shape : int or tuple of int
The shape of the empty array.
ctx : Context, optional
An optional device context (default is the current d... | Returns a new array filled with all zeros, with the given shape and type.
Parameters
----------
shape : int or tuple of int
The shape of the empty array.
ctx : Context, optional
An optional device context (default is the current default context).
dtype : str or numpy.dtype, optional... |
def _set_vxlan_acl_state(self, v, load=False):
"""
Setter method for vxlan_acl_state, mapped from YANG variable /vxlan_acl_state (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_vxlan_acl_state is considered as a private
method. Backends looking to populat... | Setter method for vxlan_acl_state, mapped from YANG variable /vxlan_acl_state (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_vxlan_acl_state is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_v... |
def insrtc(item, inset):
"""
Insert an item into a character set.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/insrtc_c.html
:param item: Item to be inserted.
:type item: str or list of str
:param inset: Insertion set.
:type inset: spiceypy.utils.support_types.SpiceCell
"""
... | Insert an item into a character set.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/insrtc_c.html
:param item: Item to be inserted.
:type item: str or list of str
:param inset: Insertion set.
:type inset: spiceypy.utils.support_types.SpiceCell |
def nl_recvmsgs(sk, cb):
"""Receive a set of messages from a Netlink socket.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L1023
Repeatedly calls nl_recv() or the respective replacement if provided by the application (see nl_cb_overwrite_recv())
and parses the received data as Netlink mes... | Receive a set of messages from a Netlink socket.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L1023
Repeatedly calls nl_recv() or the respective replacement if provided by the application (see nl_cb_overwrite_recv())
and parses the received data as Netlink messages. Stops reading if one of t... |
def create_geoms(self, gdefs, plot):
"""
Add geoms to the guide definitions
"""
new_gdefs = []
for gdef in gdefs:
gdef = gdef.create_geoms(plot)
if gdef:
new_gdefs.append(gdef)
return new_gdefs | Add geoms to the guide definitions |
def get_class_name_from_frame(fr: FrameType) -> Optional[str]:
"""
A frame contains information about a specific call in the Python call
stack; see https://docs.python.org/3/library/inspect.html.
If the call was to a member function of a class, this function attempts
to read the class's name. It re... | A frame contains information about a specific call in the Python call
stack; see https://docs.python.org/3/library/inspect.html.
If the call was to a member function of a class, this function attempts
to read the class's name. It returns ``None`` otherwise. |
def _create_org(self, orch_id, name, desc):
"""Create organization on the DCNM.
:param orch_id: orchestrator ID
:param name: Name of organization
:param desc: Description of organization
"""
url = self._org_url
payload = {
"organizationName": name,
... | Create organization on the DCNM.
:param orch_id: orchestrator ID
:param name: Name of organization
:param desc: Description of organization |
def adaptSegment(self, segUpdate, positiveReinforcement):
"""This function applies segment update information to a segment in a
cell.
If positiveReinforcement is true then synapses on the active list
get their permanence counts incremented by permanenceInc. All other synapses
get their permanence c... | This function applies segment update information to a segment in a
cell.
If positiveReinforcement is true then synapses on the active list
get their permanence counts incremented by permanenceInc. All other synapses
get their permanence counts decremented by permanenceDec.
If positiveReinforcement... |
def find_task(self, request, context):
"""Finds one specific task."""
_log_request(request, context)
task = self.listener.memory.tasks.get(request.task_uuid)
if not task:
return clearly_pb2.TaskMessage()
return ClearlyServer._event_to_pb(task)[1] | Finds one specific task. |
def _significant_pathways_dataframe(pvalue_information,
side_information,
alpha):
"""Create the significant pathways pandas.DataFrame.
Given the p-values corresponding to each pathway in a feature,
apply the FDR correction for multiple ... | Create the significant pathways pandas.DataFrame.
Given the p-values corresponding to each pathway in a feature,
apply the FDR correction for multiple testing and remove those that
do not have a q-value of less than `alpha`. |
def initialize(self, symbolic_vm: LaserEVM):
"""Initializes the mutation pruner
Introduces hooks for SSTORE operations
:param symbolic_vm:
:return:
"""
@symbolic_vm.pre_hook("SSTORE")
def mutator_hook(global_state: GlobalState):
global_state.annotate... | Initializes the mutation pruner
Introduces hooks for SSTORE operations
:param symbolic_vm:
:return: |
def getPutData(request):
"""Adds raw post to the PUT and DELETE querydicts on the request so they behave like post
:param request: Request object to add PUT/DELETE to
:type request: Request
"""
dataDict = {}
data = request.body
for n in urlparse.parse_qsl(data):
dataDict[n[0]] = n[... | Adds raw post to the PUT and DELETE querydicts on the request so they behave like post
:param request: Request object to add PUT/DELETE to
:type request: Request |
def configparser(self):
"""
Adapter to dump/load INI format strings and files using standard library's
``ConfigParser`` (or the backported configparser module in Python 2).
Returns:
ConfigPersistenceAdapter
"""
if self._configparser_adapter is None:
... | Adapter to dump/load INI format strings and files using standard library's
``ConfigParser`` (or the backported configparser module in Python 2).
Returns:
ConfigPersistenceAdapter |
def execute(self, env, args):
""" Edits task configuration.
`env`
Runtime ``Environment`` instance.
`args`
Arguments object from arg parser.
"""
task_name = args.task_name
if not env.task.exists(task_name):
raise ... | Edits task configuration.
`env`
Runtime ``Environment`` instance.
`args`
Arguments object from arg parser. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.