code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def child(self, name=None, **attrs):
"""
Select the direct child(ren) from the UI element(s) given by the query expression, see ``QueryCondition`` for
more details about the selectors.
Args:
name: query expression of attribute "name", i.e. the UI elements with ``name`` name ... | Select the direct child(ren) from the UI element(s) given by the query expression, see ``QueryCondition`` for
more details about the selectors.
Args:
name: query expression of attribute "name", i.e. the UI elements with ``name`` name will be selected
attrs: other query expressio... |
def _post(self, route, data, headers=None, failure_message=None):
"""
Execute a post request and return the result
:param data:
:param headers:
:return:
"""
headers = self._get_headers(headers)
response_lambda = (
lambda: requests.post(
... | Execute a post request and return the result
:param data:
:param headers:
:return: |
def selectAssemblies(pth, manifest=None):
"""
Return a binary's dependent assemblies files that should be included.
Return a list of pairs (name, fullpath)
"""
rv = []
if not os.path.isfile(pth):
pth = check_extract_from_egg(pth)[0][0]
if manifest:
_depNames = set([dep.name ... | Return a binary's dependent assemblies files that should be included.
Return a list of pairs (name, fullpath) |
def add_uid(fastq, cores):
''' Adds UID:[samplebc cellbc umi] to readname for umi-tools deduplication
Expects formatted fastq files with correct sample and cell barcodes.
'''
uids = partial(append_uids)
p = multiprocessing.Pool(cores)
chunks = tz.partition_all(10000, read_fastq(fastq))
big... | Adds UID:[samplebc cellbc umi] to readname for umi-tools deduplication
Expects formatted fastq files with correct sample and cell barcodes. |
def cublasSsbmv(handle, uplo, n, k, alpha, A, lda, x, incx, beta, y, incy):
"""
Matrix-vector product for real symmetric-banded matrix.
"""
status = _libcublas.cublasSsbmv_v2(handle,
_CUBLAS_FILL_MODE[uplo], n, k,
ctypes.byr... | Matrix-vector product for real symmetric-banded matrix. |
def conflict(self, key, **kwargs):
"""
A helper method that simply raises a validation error.
"""
try:
msg = self.error_messages[key]
except KeyError:
class_name = self.__class__.__name__
msg = MISSING_ERROR_MESSAGE.format(class_name=class_name... | A helper method that simply raises a validation error. |
def correlation_model(prediction, fm):
"""
wraps numpy.corrcoef functionality for model evaluation
input:
prediction: 2D Matrix
the model salience map
fm: fixmat
Used to compute a FDM to which the prediction is compared.
"""
(_, r_x) = calc_resize_factor(pred... | wraps numpy.corrcoef functionality for model evaluation
input:
prediction: 2D Matrix
the model salience map
fm: fixmat
Used to compute a FDM to which the prediction is compared. |
def pretty_print(self, as_list=False, show_datetime=True):
"""
Return a Unicode string pretty print of the log entries.
:param bool as_list: if ``True``, return a list of Unicode strings,
one for each entry, instead of a Unicode string
:param bool show_datet... | Return a Unicode string pretty print of the log entries.
:param bool as_list: if ``True``, return a list of Unicode strings,
one for each entry, instead of a Unicode string
:param bool show_datetime: if ``True``, show the date and time of the entries
:rtype: string ... |
def random_combination(iterable, nquartets):
"""
Random selection from itertools.combinations(iterable, r).
Use this if not sampling all possible quartets.
"""
pool = tuple(iterable)
size = len(pool)
indices = random.sample(xrange(size), nquartets)
return tuple(pool[i] for i in indices) | Random selection from itertools.combinations(iterable, r).
Use this if not sampling all possible quartets. |
def to_dict(self):
'''Save this service port into a dictionary.'''
d = {'name': self.name}
if self.visible != True:
d[RTS_EXT_NS_YAML + 'visible'] = self.visible
if self.comment:
d[RTS_EXT_NS_YAML + 'comment'] = self.comment
props = []
for name in ... | Save this service port into a dictionary. |
def set_typ(self, refobj, typ):
"""Set the type of the given refobj
:param refobj: the reftrack node to edit
:type refobj: refobj
:param typ: the entity type
:type typ: str
:returns: None
:rtype: None
:raises: ValueError
"""
try:
... | Set the type of the given refobj
:param refobj: the reftrack node to edit
:type refobj: refobj
:param typ: the entity type
:type typ: str
:returns: None
:rtype: None
:raises: ValueError |
def luns(self):
"""Aggregator for ioclass_luns and ioclass_snapshots."""
lun_list, smp_list = [], []
if self.ioclass_luns:
lun_list = map(lambda l: VNXLun(lun_id=l.lun_id, name=l.name,
cli=self._cli), self.ioclass_luns)
if self.iocl... | Aggregator for ioclass_luns and ioclass_snapshots. |
def process_alt(header, ref, alt_str): # pylint: disable=W0613
"""Process alternative value using Header in ``header``"""
# By its nature, this function contains a large number of case distinctions
if "]" in alt_str or "[" in alt_str:
return record.BreakEnd(*parse_breakend(alt_str))
elif alt_st... | Process alternative value using Header in ``header`` |
def select_tasks(self, nids=None, wslice=None, task_class=None):
"""
Return a list with a subset of tasks.
Args:
nids: List of node identifiers.
wslice: Slice object used to select works.
task_class: String or class used to select tasks. Ignored if None.
... | Return a list with a subset of tasks.
Args:
nids: List of node identifiers.
wslice: Slice object used to select works.
task_class: String or class used to select tasks. Ignored if None.
.. note::
nids and wslice are mutually exclusive.
If no... |
def stream(self, start_date=values.unset, end_date=values.unset,
identity=values.unset, tag=values.unset, limit=None, page_size=None):
"""
Streams BindingInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the l... | Streams BindingInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param date start_date: Only include usage that ... |
def collect_modules(self):
"""Generator to obtain lines of interest from coverage report files.
Will verify that the source file is within the project tree, relative
to the coverage directory.
"""
coverage_dir = os.path.join(self.root, 'cover')
for name in fnmatch.filter... | Generator to obtain lines of interest from coverage report files.
Will verify that the source file is within the project tree, relative
to the coverage directory. |
def prepare_delete_monarchy(self, node, position=None, save=True):
""" Prepares a given :class:`CTENode` `node` for deletion, by executing
the :const:`DELETE_METHOD_MONARCHY` semantics. Descendant nodes,
if present, will be moved; in this case the optional `position` can
be a... | Prepares a given :class:`CTENode` `node` for deletion, by executing
the :const:`DELETE_METHOD_MONARCHY` semantics. Descendant nodes,
if present, will be moved; in this case the optional `position` can
be a ``callable`` which is invoked prior to each move operation (see
:m... |
def lookup_job_tasks(self,
statuses,
user_ids=None,
job_ids=None,
job_names=None,
task_ids=None,
task_attempts=None,
labels=None,
create... | Yields operations based on the input criteria.
If any of the filters are empty or {'*'}, then no filtering is performed on
that field. Filtering by both a job id list and job name list is
unsupported.
Args:
statuses: {'*'}, or a list of job status strings to return. Valid
status strings ... |
async def listCronJobs(self):
'''
Get information about all the cron jobs accessible to the current user
'''
crons = []
for iden, cron in self.cell.agenda.list():
useriden = cron['useriden']
if not (self.user.admin or useriden == self.user.iden):
... | Get information about all the cron jobs accessible to the current user |
def set_headers(context):
"""
Parameters:
+--------------+---------------+
| header_name | header_value |
+==============+===============+
| header1 | value1 |
+--------------+---------------+
| header2 | value2 |
+--------------... | Parameters:
+--------------+---------------+
| header_name | header_value |
+==============+===============+
| header1 | value1 |
+--------------+---------------+
| header2 | value2 |
+--------------+---------------+ |
def plot_spectrogram(self, node_idx=None):
r"""Docstring overloaded at import time."""
from pygsp.plotting import _plot_spectrogram
_plot_spectrogram(self, node_idx=node_idx) | r"""Docstring overloaded at import time. |
def view(self, tempname='/tmp/tempimage'):
"""Display the image using casaviewer.
If the image is not persistent, a copy will be made that the user
has to delete once viewing has finished. The name of the copy can be
given in argument `tempname`. Default is '/tmp/tempimage'.
""... | Display the image using casaviewer.
If the image is not persistent, a copy will be made that the user
has to delete once viewing has finished. The name of the copy can be
given in argument `tempname`. Default is '/tmp/tempimage'. |
async def startlisten(self, vhost = None):
'''
Start listen on current servers
:param vhost: return only servers of vhost if specified. '' to return only default servers.
None for all servers.
'''
servers = self.getservers(vhost)
for s in se... | Start listen on current servers
:param vhost: return only servers of vhost if specified. '' to return only default servers.
None for all servers. |
def srandmember(self, name, number=None):
"""
Return a random member of the set.
:param name: str the name of the redis key
:return: Future()
"""
with self.pipe as pipe:
f = Future()
res = pipe.srandmember(self.redis_key(name), number=number)
... | Return a random member of the set.
:param name: str the name of the redis key
:return: Future() |
def fill(self, doc_contents):
""" Fill the content of the document with the information in doc_contents.
This is different from the TextDocument fill function, because this will
check for symbools in the values of `doc_content` and replace them
to good XML codes before filling the templa... | Fill the content of the document with the information in doc_contents.
This is different from the TextDocument fill function, because this will
check for symbools in the values of `doc_content` and replace them
to good XML codes before filling the template.
Parameters
----------... |
def market_open(self, session, mins) -> Session:
"""
Time intervals for market open
Args:
session: [allday, day, am, pm, night]
mins: mintues after open
Returns:
Session of start_time and end_time
"""
if session not in self.exch: retu... | Time intervals for market open
Args:
session: [allday, day, am, pm, night]
mins: mintues after open
Returns:
Session of start_time and end_time |
def make_csv(api_key, api_secret, path_to_csv=None, result_limit=1000, **kwargs):
"""
Function which fetches a video library and writes each video_objects Metadata to CSV. Useful for CMS systems.
:param api_key: <string> JWPlatform api-key
:param api_secret: <string> JWPlatform shared-secret
:param... | Function which fetches a video library and writes each video_objects Metadata to CSV. Useful for CMS systems.
:param api_key: <string> JWPlatform api-key
:param api_secret: <string> JWPlatform shared-secret
:param path_to_csv: <string> Local system path to desired CSV. Default will be within current workin... |
def nvmlDeviceGetInforomImageVersion(handle):
r"""
/**
* Retrieves the global infoROM image version
*
* For all products with an inforom.
*
* Image version just like VBIOS version uniquely describes the exact version of the infoROM flashed on the board
* in contrast to infoROM obje... | r"""
/**
* Retrieves the global infoROM image version
*
* For all products with an inforom.
*
* Image version just like VBIOS version uniquely describes the exact version of the infoROM flashed on the board
* in contrast to infoROM object version which is only an indicator of supported... |
def favorites(self):
""" :reference: https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-favorites-list
:allowed_param:'screen_name', 'user_id', 'max_id', 'count', 'since_id', 'max_id'
"""
return bind_api(
api=self,
path='/favorites/... | :reference: https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-favorites-list
:allowed_param:'screen_name', 'user_id', 'max_id', 'count', 'since_id', 'max_id' |
def set_font(self, font):
"""Set IPython widget's font"""
self.shellwidget._control.setFont(font)
self.shellwidget.font = font | Set IPython widget's font |
def post(self, url, data, charset=CHARSET_UTF8, headers={}):
'''response json text'''
if 'Api-Lang' not in headers:
headers['Api-Lang'] = 'python'
if 'Content-Type' not in headers:
headers['Content-Type'] = "application/x-www-form-urlencoded;charset=" + charset
rs... | response json text |
def storeByteArray(self, context, page, len, data, returnError):
"""please override"""
returnError.contents.value = self.IllegalStateError
raise NotImplementedError("You must override this method.") | please override |
def delete(self):
"""Delete the item from storage
:param method callback: The callback method to invoke when done
"""
result = yield gen.Task(RedisSession._redis_client.delete, self._key)
LOGGER.debug('Deleted session %s (%r)', self.id, result)
self.clear()
rais... | Delete the item from storage
:param method callback: The callback method to invoke when done |
def numRef_xml(self, wksht_ref, number_format, values):
"""
Return the ``<c:numRef>`` element specified by the parameters as
unicode text.
"""
pt_xml = self.pt_xml(values)
return (
' <c:numRef>\n'
' <c:f>{wksht_ref}</c:f>\n'... | Return the ``<c:numRef>`` element specified by the parameters as
unicode text. |
def check_effective(func):
"""decorator, tests if an Assessment or Section is effective, raises error if not
Side benefit: raised NotFound on AssessmentSections and AssessmentTakens
"""
def wrapper(*args, **kwargs):
if ('assessment_section_id' in kwargs or
args and 'Section' in... | decorator, tests if an Assessment or Section is effective, raises error if not
Side benefit: raised NotFound on AssessmentSections and AssessmentTakens |
def create_2d_gaussian(dim, sigma):
"""
This function creates a 2d gaussian kernel with the standard deviation
denoted by sigma
:param dim: integer denoting a side (1-d) of gaussian kernel
:param sigma: floating point indicating the standard deviation
:returns: a numpy 2d array
"""
# ... | This function creates a 2d gaussian kernel with the standard deviation
denoted by sigma
:param dim: integer denoting a side (1-d) of gaussian kernel
:param sigma: floating point indicating the standard deviation
:returns: a numpy 2d array |
def _regex_strings(self):
"""
A property to link into IntentEngine's _regex_strings.
Warning: this is only for backwards compatiblility and should not be used if you
intend on using domains.
Returns: the domains _regex_strings from its IntentEngine
"""
domai... | A property to link into IntentEngine's _regex_strings.
Warning: this is only for backwards compatiblility and should not be used if you
intend on using domains.
Returns: the domains _regex_strings from its IntentEngine |
def _any(objs, query):
''' Whether any of a collection of objects satisfies a given query predicate
Args:
objs (seq[Model or Document]) :
query (callable)
Returns:
True, if ``query(obj)`` is True for some object in ``objs``, else False
'''
for obj in objs:
if isin... | Whether any of a collection of objects satisfies a given query predicate
Args:
objs (seq[Model or Document]) :
query (callable)
Returns:
True, if ``query(obj)`` is True for some object in ``objs``, else False |
def unpack(tokens):
"""Evaluate and unpack the given computation graph."""
logger.log_tag("unpack", tokens)
if use_computation_graph:
tokens = evaluate_tokens(tokens)
if isinstance(tokens, ParseResults) and len(tokens) == 1:
tokens = tokens[0]
return tokens | Evaluate and unpack the given computation graph. |
def atlas_find_missing_zonefile_availability( peer_table=None, con=None, path=None, missing_zonefile_info=None ):
"""
Find the set of missing zonefiles, as well as their popularity amongst
our neighbors.
Only consider zonefiles that are known by at least
one peer; otherwise they're missing from
... | Find the set of missing zonefiles, as well as their popularity amongst
our neighbors.
Only consider zonefiles that are known by at least
one peer; otherwise they're missing from
our clique (and we'll re-sync our neighborss' inventories
every so often to make sure we detect when zonefiles
becom... |
def protect_shorthand(text, split_locations):
"""
Annotate locations in a string that contain
periods as being true periods or periods
that are a part of shorthand (and thus should
not be treated as punctuation marks).
Arguments:
----------
text : str
split_locations : list<... | Annotate locations in a string that contain
periods as being true periods or periods
that are a part of shorthand (and thus should
not be treated as punctuation marks).
Arguments:
----------
text : str
split_locations : list<int>, same length as text. |
def put(self, request):
"""
Update a single profile for a given video.
Example request data:
{
'edx_video_id': '1234'
'profile': 'hls',
'encode_data': {
'url': 'foo.com/qwe.m3u8'
'file_size': 34
... | Update a single profile for a given video.
Example request data:
{
'edx_video_id': '1234'
'profile': 'hls',
'encode_data': {
'url': 'foo.com/qwe.m3u8'
'file_size': 34
'bitrate': 12
... |
def layer_from_combo(combo):
"""Get the QgsMapLayer currently selected in a combo.
Obtain QgsMapLayer id from the userrole of the QtCombo and return it as a
QgsMapLayer.
:returns: The currently selected map layer a combo.
:rtype: QgsMapLayer
"""
index = combo.currentIndex()
if index < ... | Get the QgsMapLayer currently selected in a combo.
Obtain QgsMapLayer id from the userrole of the QtCombo and return it as a
QgsMapLayer.
:returns: The currently selected map layer a combo.
:rtype: QgsMapLayer |
def api_request(self, method, path):
'''
Query Sensu api for information.
'''
if not hasattr(self, 'api_settings'):
ValueError('api.json settings not found')
if method.lower() == 'get':
_request = requests.get
elif method.lower() == 'post':
... | Query Sensu api for information. |
def _unpack_object_array(inp, source, prescatter):
"""Unpack Array[Object] with a scatter for referencing in input calls.
There is no shorthand syntax for referencing all items in an array, so
we explicitly unpack them with a scatter.
"""
raise NotImplementedError("Currently not used with record/st... | Unpack Array[Object] with a scatter for referencing in input calls.
There is no shorthand syntax for referencing all items in an array, so
we explicitly unpack them with a scatter. |
def unpack_frame(message):
"""Called to unpack a STOMP message into a dictionary.
returned = {
# STOMP Command:
'cmd' : '...',
# Headers e.g.
'headers' : {
'destination' : 'xyz',
'message-id' : 'some event',
:
etc,
}
... | Called to unpack a STOMP message into a dictionary.
returned = {
# STOMP Command:
'cmd' : '...',
# Headers e.g.
'headers' : {
'destination' : 'xyz',
'message-id' : 'some event',
:
etc,
}
# Body:
'body' : '...1... |
def handle(self, url, method):
""" Execute the handler bound to the specified url and method and return
its output. If catchall is true, exceptions are catched and returned as
HTTPError(500) objects. """
if not self.serve:
return HTTPError(503, "Server stopped")
hand... | Execute the handler bound to the specified url and method and return
its output. If catchall is true, exceptions are catched and returned as
HTTPError(500) objects. |
def get_raw_data_from_buffer(self, filter_func=None, converter_func=None):
'''Reads local data buffer and returns raw data array.
Returns
-------
data : np.array
An array containing data words from the local data buffer.
'''
if self._is_running:
... | Reads local data buffer and returns raw data array.
Returns
-------
data : np.array
An array containing data words from the local data buffer. |
def send(self, tid, company_code, session, **kwargs):
'''taobao.logistics.online.send 在线订单发货处理(支持货到付款)
- 用户调用该接口可实现在线订单发货(支持货到付款)
- 调用该接口实现在线下单发货,有两种情况:
- 如果不输入运单号的情况:交易状态不会改变,需要调用taobao.logistics.online.confirm确认发货后交易状态才会变成卖家已发货。
- 如果输入运单号的情况发货:交易订单状态会直接变成卖家已发货 。'''
... | taobao.logistics.online.send 在线订单发货处理(支持货到付款)
- 用户调用该接口可实现在线订单发货(支持货到付款)
- 调用该接口实现在线下单发货,有两种情况:
- 如果不输入运单号的情况:交易状态不会改变,需要调用taobao.logistics.online.confirm确认发货后交易状态才会变成卖家已发货。
- 如果输入运单号的情况发货:交易订单状态会直接变成卖家已发货 。 |
def say(*words):
'''
Say some words.
words
The words to execute the say command with.
CLI Example:
.. code-block:: bash
salt '*' desktop.say <word0> <word1> ... <wordN>
'''
cmd = 'say {0}'.format(' '.join(words))
call = __salt__['cmd.run_all'](
cmd,
ou... | Say some words.
words
The words to execute the say command with.
CLI Example:
.. code-block:: bash
salt '*' desktop.say <word0> <word1> ... <wordN> |
def maximum_impact_estimation(membership_matrix, max_iters=1000):
"""An expectation maximization technique that produces pathway definitions
devoid of crosstalk. That is, each gene is mapped to the pathway in
which it has the greatest predicted impact; this removes any overlap
between pathway definition... | An expectation maximization technique that produces pathway definitions
devoid of crosstalk. That is, each gene is mapped to the pathway in
which it has the greatest predicted impact; this removes any overlap
between pathway definitions.
Parameters
-----------
membership_matrix : numpy.array(fl... |
def handle_page_location_changed(self, timeout=None):
'''
If the chrome tab has internally redirected (generally because jerberscript), this
will walk the page navigation responses and attempt to fetch the response body for
the tab's latest location.
'''
# In general, this is often called after other mecha... | If the chrome tab has internally redirected (generally because jerberscript), this
will walk the page navigation responses and attempt to fetch the response body for
the tab's latest location. |
def values(prev, *keys, **kw):
"""values pipe extract value from previous pipe.
If previous pipe send a dictionary to values pipe, keys should contains
the key of dictionary which you want to get. If previous pipe send list or
tuple,
:param prev: The previous iterator of pipe.
:type prev: Pipe... | values pipe extract value from previous pipe.
If previous pipe send a dictionary to values pipe, keys should contains
the key of dictionary which you want to get. If previous pipe send list or
tuple,
:param prev: The previous iterator of pipe.
:type prev: Pipe
:returns: generator |
def render_request(self, sort=True):
"""Render the dict's Cookie objects into a string formatted for HTTP
request headers (simple 'Cookie: ' style).
"""
if not sort:
return ("; ".join(
cookie.render_request() for cookie in self.values()))
return ("; ".... | Render the dict's Cookie objects into a string formatted for HTTP
request headers (simple 'Cookie: ' style). |
def retrieve(pdb_id, cache_dir = None):
'''Creates a PDBML object by using a cached copy of the files if they exists or by retrieving the files from the RCSB.'''
pdb_contents = None
xml_contents = None
pdb_id = pdb_id.upper()
if cache_dir:
# Check to see whether we ... | Creates a PDBML object by using a cached copy of the files if they exists or by retrieving the files from the RCSB. |
def delete_tag(self, tag_name, **kwargs):
"""delete a tag by name
Args:
tag_name (string): name of tag to delete
"""
resp = self._delete(self._u(self._TAG_ENDPOINT_SUFFIX, tag_name),
**kwargs)
resp.raise_for_status()
# successful d... | delete a tag by name
Args:
tag_name (string): name of tag to delete |
def usable_id(cls, id, datacenter=None):
""" Retrieve id from input which can be label or id."""
try:
qry_id = int(id)
except Exception:
# if id is a string, prefer a system disk then a label
qry_id = cls.from_sysdisk(id) or cls.from_label(id, datacenter)
... | Retrieve id from input which can be label or id. |
def _random_ipv4_address_from_subnet(self, subnet, network=False):
"""
Produces a random IPv4 address or network with a valid CIDR
from within a given subnet.
:param subnet: IPv4Network to choose from within
:param network: Return a network address, and not an IP address
... | Produces a random IPv4 address or network with a valid CIDR
from within a given subnet.
:param subnet: IPv4Network to choose from within
:param network: Return a network address, and not an IP address |
def read_table(self, table_type):
"""Read either the hash or block table of a MPQ archive."""
if table_type == 'hash':
entry_class = MPQHashTableEntry
elif table_type == 'block':
entry_class = MPQBlockTableEntry
else:
raise ValueError("Invalid table t... | Read either the hash or block table of a MPQ archive. |
def mark_sacrificed(self,request,queryset):
"""An admin action for marking several animals as sacrificed.
This action sets the selected animals as Alive=False, Death=today and Cause_of_Death as sacrificed. To use other paramters, mice muse be individually marked as sacrificed.
This admin act... | An admin action for marking several animals as sacrificed.
This action sets the selected animals as Alive=False, Death=today and Cause_of_Death as sacrificed. To use other paramters, mice muse be individually marked as sacrificed.
This admin action also shows as the output the number of mice sacrifi... |
def _get_path_for_type(type_):
"""Similar to `_get_path_for` but for only type names."""
if type_.lower() in CORE_TYPES:
return Path('index.html#%s' % type_.lower())
elif '.' in type_:
namespace, name = type_.split('.')
return Path('types', namespace, _get_file_name(name))
else:
... | Similar to `_get_path_for` but for only type names. |
def begin(self):
"""Start a new transaction."""
if self.in_transaction: # we're already in a transaction...
if self._auto_transaction:
self._auto_transaction = False
return
self.commit()
self.in_transaction = True
for collection, s... | Start a new transaction. |
def create(graph, verbose=True):
"""
Compute the in degree, out degree and total degree of each vertex.
Parameters
----------
graph : SGraph
The graph on which to compute degree counts.
verbose : bool, optional
If True, print progress updates.
Returns
-------
out :... | Compute the in degree, out degree and total degree of each vertex.
Parameters
----------
graph : SGraph
The graph on which to compute degree counts.
verbose : bool, optional
If True, print progress updates.
Returns
-------
out : DegreeCountingModel
Examples
------... |
def make_pdb(self):
"""Generates a PDB string for the `Monomer`."""
pdb_str = write_pdb(
[self], ' ' if not self.ampal_parent else self.ampal_parent.id)
return pdb_str | Generates a PDB string for the `Monomer`. |
def checkGradient(self,h=1e-6,verbose=True):
""" utility function to check the gradient of the gp """
grad_an = self.LMLgrad()
grad_num = {}
params0 = self.params.copy()
for key in list(self.params.keys()):
paramsL = params0.copy()
paramsR = params0.copy()... | utility function to check the gradient of the gp |
def p_function_call_parameter(p):
'''function_call_parameter : expr
| AND variable'''
if len(p) == 2:
p[0] = ast.Parameter(p[1], False, lineno=p.lineno(1))
else:
p[0] = ast.Parameter(p[2], True, lineno=p.lineno(1)) | function_call_parameter : expr
| AND variable |
def parent(idx, dim, axis=None):
"""
Parent node according to Bertran's notation.
Parameters
----------
idx : int
Index of the child node.
dim : int
Dimensionality of the problem.
axis : int
Assume axis direction.
Returns
-------
out : int
Index ... | Parent node according to Bertran's notation.
Parameters
----------
idx : int
Index of the child node.
dim : int
Dimensionality of the problem.
axis : int
Assume axis direction.
Returns
-------
out : int
Index of parent node with `j<=i`, and `j==i` iff `i... |
def createListRecursively(self,args):
"""
This is an internal method to create the list of input files (or directories)
recursively, starting at the provided directory or directories.
"""
resultList = []
dirDict = self.getDirectoryDictionary(args)
for key in dirDi... | This is an internal method to create the list of input files (or directories)
recursively, starting at the provided directory or directories. |
def check_R_package(self, package):
"""Execute a subprocess to check the package's availability.
Args:
package (str): Name of the package to be tested.
Returns:
bool: `True` if the package is available, `False` otherwise
"""
test_package = not bool(launc... | Execute a subprocess to check the package's availability.
Args:
package (str): Name of the package to be tested.
Returns:
bool: `True` if the package is available, `False` otherwise |
def extract_angular(fileobj, keywords, comment_tags, options):
"""Extract messages from angular template (HTML) files.
It extract messages from angular template (HTML) files that use
angular-gettext translate directive as per
https://angular-gettext.rocketeer.be/
:param fileobj: the file-like obje... | Extract messages from angular template (HTML) files.
It extract messages from angular template (HTML) files that use
angular-gettext translate directive as per
https://angular-gettext.rocketeer.be/
:param fileobj: the file-like object the messages should be extracted
from
:para... |
def right_press(self, event):
"""
Callback for the right mouse button event to pop up the correct menu.
:param event: Tkinter event
"""
self.set_current()
current = self.canvas.find_withtag("current")
if current and current[0] in self.canvas.find_withtag(... | Callback for the right mouse button event to pop up the correct menu.
:param event: Tkinter event |
def write(p_file, p_string):
"""
Write p_string to file p_file, trailed by a newline character.
ANSI codes are removed when the file is not a TTY (and colors are
automatically determined).
"""
if not config().colors(p_file.isatty()):
p_string = escape_ansi(p_string)
if p_string:
... | Write p_string to file p_file, trailed by a newline character.
ANSI codes are removed when the file is not a TTY (and colors are
automatically determined). |
def collect(self):
"""
Collect interrupt data
"""
if not os.access(self.PROC, os.R_OK):
return False
# Open PROC file
file = open(self.PROC, 'r')
# Get data
for line in file:
if not line.startswith('softirq'):
con... | Collect interrupt data |
def question_detail(request, topic_slug, slug):
"""
A detail view of a Question.
Templates:
:template:`faq/question_detail.html`
Context:
question
A :model:`faq.Question`.
topic
The :model:`faq.Topic` object related to ``question``.
"""
extra_con... | A detail view of a Question.
Templates:
:template:`faq/question_detail.html`
Context:
question
A :model:`faq.Question`.
topic
The :model:`faq.Topic` object related to ``question``. |
def grep(query, directory):
"""This function will search through the directory structure of the
application and for each directory it finds it launches an Async task to
run itself. For each .py file it finds, it actually greps the file and then
returns the found output."""
dir_contents = os.listdir... | This function will search through the directory structure of the
application and for each directory it finds it launches an Async task to
run itself. For each .py file it finds, it actually greps the file and then
returns the found output. |
def plot_structures(self, structures, fontsize=6, **kwargs):
"""
Plot diffraction patterns for multiple structures on the same figure.
Args:
structures (Structure): List of structures
two_theta_range ([float of length 2]): Tuple for range of
two_thetas to... | Plot diffraction patterns for multiple structures on the same figure.
Args:
structures (Structure): List of structures
two_theta_range ([float of length 2]): Tuple for range of
two_thetas to calculate in degrees. Defaults to (0, 90). Set to
None if you wa... |
def view_task_durations(token, dstore):
"""
Display the raw task durations. Here is an example of usage::
$ oq show task_durations:classical
"""
task = token.split(':')[1] # called as task_duration:task_name
array = dstore['task_info/' + task]['duration']
return '\n'.join(map(str, array)... | Display the raw task durations. Here is an example of usage::
$ oq show task_durations:classical |
def range_interleave(ranges, sizes={}, empty=False):
"""
Returns the ranges in between the given ranges.
>>> ranges = [("1", 30, 40), ("1", 45, 50), ("1", 10, 30)]
>>> range_interleave(ranges)
[('1', 41, 44)]
>>> ranges = [("1", 30, 40), ("1", 42, 50)]
>>> range_interleave(ranges)
[('1'... | Returns the ranges in between the given ranges.
>>> ranges = [("1", 30, 40), ("1", 45, 50), ("1", 10, 30)]
>>> range_interleave(ranges)
[('1', 41, 44)]
>>> ranges = [("1", 30, 40), ("1", 42, 50)]
>>> range_interleave(ranges)
[('1', 41, 41)]
>>> range_interleave(ranges, sizes={"1": 70})
... |
def body_block_paragraph_render(p_tag, html_flag=True, base_url=None):
"""
paragraphs may wrap some other body block content
this is separated out so it can be called from more than one place
"""
# Configure the XML to HTML conversion preference for shorthand use below
convert = lambda xml_strin... | paragraphs may wrap some other body block content
this is separated out so it can be called from more than one place |
def _inherit_parent_kwargs(self, kwargs):
"""Extract any necessary attributes from parent serializer to
propagate down to child serializer.
"""
if not self.parent or not self._is_dynamic:
return kwargs
if 'request_fields' not in kwargs:
# If 'request_fie... | Extract any necessary attributes from parent serializer to
propagate down to child serializer. |
def googlenet(pretrained=False, **kwargs):
r"""GoogLeNet (Inception v1) model architecture from
`"Going Deeper with Convolutions" <http://arxiv.org/abs/1409.4842>`_.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
aux_logits (bool): If True, adds two auxiliary bran... | r"""GoogLeNet (Inception v1) model architecture from
`"Going Deeper with Convolutions" <http://arxiv.org/abs/1409.4842>`_.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
aux_logits (bool): If True, adds two auxiliary branches that can improve training.
Def... |
def _sort_text(definition):
""" Ensure builtins appear at the bottom.
Description is of format <type>: <module>.<item>
"""
# If its 'hidden', put it next last
prefix = 'z{}' if definition.name.startswith('_') else 'a{}'
return prefix.format(definition.name) | Ensure builtins appear at the bottom.
Description is of format <type>: <module>.<item> |
def check_html(html_file, begin):
'''
Checking the HTML
'''
sig = False
for html_line in open(html_file).readlines():
# uu = x.find('{% extends')
uuu = pack_str(html_line).find('%extends')
# print(pack_str(x))
if uuu > 0:
f_tmpl = html_line.strip().split(... | Checking the HTML |
def get_transformation(self, struct1, struct2):
"""
Returns the supercell transformation, fractional translation vector,
and a mapping to transform struct2 to be similar to struct1.
Args:
struct1 (Structure): Reference structure
struct2 (Structure): Structure to ... | Returns the supercell transformation, fractional translation vector,
and a mapping to transform struct2 to be similar to struct1.
Args:
struct1 (Structure): Reference structure
struct2 (Structure): Structure to transform.
Returns:
supercell (numpy.ndarray(3,... |
def compile_file(self, infile, outfile, outdated=False, force=False):
"""Process sass file."""
myfile = codecs.open(outfile, 'w', 'utf-8')
if settings.DEBUG:
myfile.write(sass.compile(filename=infile))
else:
myfile.write(sass.compile(filename=infile,
... | Process sass file. |
def get_task_runs(self, json_file=None):
"""Load all project Task Runs from Tasks."""
if self.project is None:
raise ProjectError
loader = create_task_runs_loader(self.project.id, self.tasks,
json_file, self.all)
self.task_runs, self.t... | Load all project Task Runs from Tasks. |
def count(y_true, y_score=None, countna=False):
"""
Counts the number of examples. If countna is False then only count labeled examples,
i.e. those with y_true not NaN
"""
if not countna:
return (~np.isnan(to_float(y_true))).sum()
else:
return len(y_true) | Counts the number of examples. If countna is False then only count labeled examples,
i.e. those with y_true not NaN |
def _update_secrets(self):
'''update secrets will look for a dropbox token in the environment at
SREGISTRY_DROPBOX_TOKEN and if found, create a client. If not,
an error message is returned and the client exits.
'''
# Retrieve the user token. Exit if not found
toke... | update secrets will look for a dropbox token in the environment at
SREGISTRY_DROPBOX_TOKEN and if found, create a client. If not,
an error message is returned and the client exits. |
def translate_to_international_phonetic_alphabet(self, hide_stress_mark=False):
'''
转换成国际音标。只要一个元音的时候需要隐藏重音标识
:param hide_stress_mark:
:return:
'''
translations = self.stress.mark_ipa() if (not hide_stress_mark) and self.have_vowel else ""
for phoneme in self._p... | 转换成国际音标。只要一个元音的时候需要隐藏重音标识
:param hide_stress_mark:
:return: |
def setXr(self, Xr):
""" set genotype data of the set component """
self.Xr = Xr
self.gp_block.covar.G = Xr | set genotype data of the set component |
def _get_free_gpu(max_gpu_utilization=40, min_free_memory=0.5, num_gpu=1):
"""Get available GPUs according to utilization thresholds.
Args:
:max_gpu_utilization: percent utilization threshold to consider a GPU "free"
:min_free_memory: percent free memory to consider a GPU "free"
:num_gpu: number of req... | Get available GPUs according to utilization thresholds.
Args:
:max_gpu_utilization: percent utilization threshold to consider a GPU "free"
:min_free_memory: percent free memory to consider a GPU "free"
:num_gpu: number of requested GPUs
Returns:
A tuple of (available_gpus, minimum_free_memory), wh... |
def _validate_client(self, request, data):
"""
:return: ``tuple`` - ``(client or False, data or error)``
"""
client = self.get_client(data.get('client_id'))
if client is None:
raise OAuthError({
'error': 'unauthorized_client',
'error_d... | :return: ``tuple`` - ``(client or False, data or error)`` |
def blog_likes(self, blogname, **kwargs):
"""
Gets the current given user's likes
:param limit: an int, the number of likes you want returned
(DEPRECATED) :param offset: an int, the like you want to start at, for pagination.
:param before: an int, the timestamp for likes you want... | Gets the current given user's likes
:param limit: an int, the number of likes you want returned
(DEPRECATED) :param offset: an int, the like you want to start at, for pagination.
:param before: an int, the timestamp for likes you want before.
:param after: an int, the timestamp for likes... |
def update_preference_communication_channel_id(self, notification, communication_channel_id, notification_preferences_frequency):
"""
Update a preference.
Change the preference for a single notification for a single communication channel
"""
path = {}
data = {}
... | Update a preference.
Change the preference for a single notification for a single communication channel |
def _FormatSizeInUnitsOf1024(self, size):
"""Represents a number of bytes in units of 1024.
Args:
size (int): size in bytes.
Returns:
str: human readable string of the size.
"""
magnitude_1024 = 0
used_memory_1024 = float(size)
while used_memory_1024 >= 1024:
used_memory_... | Represents a number of bytes in units of 1024.
Args:
size (int): size in bytes.
Returns:
str: human readable string of the size. |
def offset(requestContext, seriesList, factor):
"""
Takes one metric or a wildcard seriesList followed by a constant, and adds
the constant to each datapoint.
Example::
&target=offset(Server.instance01.threads.busy,10)
"""
for series in seriesList:
series.name = "offset(%s,%g)... | Takes one metric or a wildcard seriesList followed by a constant, and adds
the constant to each datapoint.
Example::
&target=offset(Server.instance01.threads.busy,10) |
def read_reporting_revisions_get(self, project=None, fields=None, types=None, continuation_token=None, start_date_time=None, include_identity_ref=None, include_deleted=None, include_tag_ref=None, include_latest_only=None, expand=None, include_discussion_changes_only=None, max_page_size=None):
"""ReadReportingRe... | ReadReportingRevisionsGet.
Get a batch of work item revisions with the option of including deleted items
:param str project: Project ID or project name
:param [str] fields: A list of fields to return in work item revisions. Omit this parameter to get all reportable fields.
:param [str] t... |
def set_options(self, options):
"""Sets the given options as instance attributes (only
if they are known).
:parameters:
options : Dict
All known instance attributes and more if the childclass
has defined them before this call.
:rtype: None
... | Sets the given options as instance attributes (only
if they are known).
:parameters:
options : Dict
All known instance attributes and more if the childclass
has defined them before this call.
:rtype: None |
def create_notification(self, notification_type, label=None, name=None,
details=None):
"""
Defines a notification for handling an alarm.
"""
return self._notification_manager.create(notification_type,
label=label, name=name, details=details) | Defines a notification for handling an alarm. |
def num_equal(result, operator, comparator):
"""
Returns the number of elements in a list that pass a comparison
:param result: The list of results of a dice roll
:param operator: Operator in string to perform comparison on:
Either '+', '-', or '*'
:param comparator: The value to compare
... | Returns the number of elements in a list that pass a comparison
:param result: The list of results of a dice roll
:param operator: Operator in string to perform comparison on:
Either '+', '-', or '*'
:param comparator: The value to compare
:return: |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.