code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def create(appname, **kwargs):
"""Create a `Link` of a particular class, using the kwargs as options"""
if appname in LinkFactory._class_dict:
return LinkFactory._class_dict[appname].create(**kwargs)
else:
raise KeyError(
"Could not create object associat... | Create a `Link` of a particular class, using the kwargs as options |
def stop(self) -> None:
"""Stops listening for new connections.
Requests currently in progress may still continue after the
server is stopped.
"""
if self._stopped:
return
self._stopped = True
for fd, sock in self._sockets.items():
assert ... | Stops listening for new connections.
Requests currently in progress may still continue after the
server is stopped. |
def print_difftext(text, other=None):
"""
Args:
text (str):
CommandLine:
#python -m utool.util_print --test-print_difftext
#autopep8 ingest_data.py --diff | python -m utool.util_print --test-print_difftext
"""
if other is not None:
# hack
text = util_str.dif... | Args:
text (str):
CommandLine:
#python -m utool.util_print --test-print_difftext
#autopep8 ingest_data.py --diff | python -m utool.util_print --test-print_difftext |
def class_box(self, cn: ClassDefinitionName) -> str:
""" Generate a box for the class. Populate its interior only if (a) it hasn't previously been generated and
(b) it appears in the gen_classes list
@param cn:
@param inherited:
@return:
"""
slot_defs: List[str]... | Generate a box for the class. Populate its interior only if (a) it hasn't previously been generated and
(b) it appears in the gen_classes list
@param cn:
@param inherited:
@return: |
def make_instance(cls, data):
"""Validate the data and create a model instance from the data.
Args:
data (dict): The unserialized data to insert into the new model
instance through it's constructor.
Returns:
peewee.Model|sqlalchemy.Model: The model insta... | Validate the data and create a model instance from the data.
Args:
data (dict): The unserialized data to insert into the new model
instance through it's constructor.
Returns:
peewee.Model|sqlalchemy.Model: The model instance with it's data
insert... |
def diamond(x, y, radius, filled=False, thickness=1):
"""
Returns a generator that produces (x, y) tuples in a diamond shape.
It is easier to predict the size of the diamond that this function
produces, as opposed to creatinga 4-sided polygon with `polygon()`
and rotating it 45 degrees.
The `le... | Returns a generator that produces (x, y) tuples in a diamond shape.
It is easier to predict the size of the diamond that this function
produces, as opposed to creatinga 4-sided polygon with `polygon()`
and rotating it 45 degrees.
The `left` and `top` arguments are the x and y coordinates for the toplef... |
def _get_sm_scale_in(self, scale_sm=91.1876):
"""Get an estimate of the SM parameters at the input scale by running
them from the EW scale using constant values for the Wilson coefficients
(corresponding to their leading log approximated values at the EW
scale).
Note that this i... | Get an estimate of the SM parameters at the input scale by running
them from the EW scale using constant values for the Wilson coefficients
(corresponding to their leading log approximated values at the EW
scale).
Note that this is not guaranteed to work and will fail if some of the
... |
def describe_volumes(self, xml_bytes):
"""Parse the XML returned by the C{DescribeVolumes} function.
@param xml_bytes: XML bytes with a C{DescribeVolumesResponse} root
element.
@return: A list of L{Volume} instances.
TODO: attachementSetItemResponseType#deleteOnTermination
... | Parse the XML returned by the C{DescribeVolumes} function.
@param xml_bytes: XML bytes with a C{DescribeVolumesResponse} root
element.
@return: A list of L{Volume} instances.
TODO: attachementSetItemResponseType#deleteOnTermination |
def set_stencil_mask(self, mask=8, face='front_and_back'):
"""Control the front or back writing of individual bits in the stencil
Parameters
----------
mask : int
Mask that is ANDed with ref and stored stencil value.
face : str
Can be 'front', 'back',... | Control the front or back writing of individual bits in the stencil
Parameters
----------
mask : int
Mask that is ANDed with ref and stored stencil value.
face : str
Can be 'front', 'back', or 'front_and_back'. |
def purge_metadata_by_name(self, name):
"""Purge a processes metadata directory.
:raises: `ProcessManager.MetadataError` when OSError is encountered on metadata dir removal.
"""
meta_dir = self._get_metadata_dir_by_name(name, self._metadata_base_dir)
logger.debug('purging metadata directory: {}'.fo... | Purge a processes metadata directory.
:raises: `ProcessManager.MetadataError` when OSError is encountered on metadata dir removal. |
def html_encode(text):
"""
Encode characters with a special meaning as HTML.
:param text: The plain text (a string).
:returns: The text converted to HTML (a string).
"""
text = text.replace('&', '&')
text = text.replace('<', '<')
text = text.replace('>', '>')
text = text.r... | Encode characters with a special meaning as HTML.
:param text: The plain text (a string).
:returns: The text converted to HTML (a string). |
def create_process(self, service, agent=None, title=None, mode=None, service_version=None, **kwargs):
'''
create_process(self, service, agent=None, title=None, mode=None, service_version=None, **kwargs)
Registers a new process or processes
:Parameters:
* *service* (`string`) --... | create_process(self, service, agent=None, title=None, mode=None, service_version=None, **kwargs)
Registers a new process or processes
:Parameters:
* *service* (`string`) -- Service which process will be started
* *agent* (`string`) -- The service identifier (e.g shell_command)
... |
def configure(self, graph, spanning_tree):
"""
Configure the filter.
@type graph: graph
@param graph: Graph.
@type spanning_tree: dictionary
@param spanning_tree: Spanning tree.
"""
self.graph = graph
self.spanning_tree = spanni... | Configure the filter.
@type graph: graph
@param graph: Graph.
@type spanning_tree: dictionary
@param spanning_tree: Spanning tree. |
def canonicalize_tautomer(self):
"""
:returns: A callable :class:`~molvs.tautomer.TautomerCanonicalizer` instance.
"""
return TautomerCanonicalizer(transforms=self.tautomer_transforms, scores=self.tautomer_scores,
max_tautomers=self.max_tautomers) | :returns: A callable :class:`~molvs.tautomer.TautomerCanonicalizer` instance. |
def removeGuideline(self, guideline):
"""
Remove ``guideline`` from the glyph.
>>> glyph.removeGuideline(guideline)
``guideline`` may be a :ref:`BaseGuideline` or an
:ref:`type-int` representing an guideline index.
"""
if isinstance(guideline, int):
... | Remove ``guideline`` from the glyph.
>>> glyph.removeGuideline(guideline)
``guideline`` may be a :ref:`BaseGuideline` or an
:ref:`type-int` representing an guideline index. |
def stop(self):
"""
Stop the sensor server (soft stop - signal packet loop to stop)
Warning: Is non blocking (server might still do something after this!)
:rtype: None
"""
self.debug("()")
super(SensorServer, self).stop()
# No new clients
if self.... | Stop the sensor server (soft stop - signal packet loop to stop)
Warning: Is non blocking (server might still do something after this!)
:rtype: None |
def normalize(in_file, data, passonly=False, normalize_indels=True, split_biallelic=True,
rerun_effects=True, remove_oldeffects=False, nonrefonly=False, work_dir=None):
"""Normalizes variants and reruns SnpEFF for resulting VCF
"""
if remove_oldeffects:
out_file = "%s-noeff-nomultialle... | Normalizes variants and reruns SnpEFF for resulting VCF |
def is_changed(self, start, end):
"""Tell whether any of start till end lines have changed
The end points are inclusive and indices start from 1.
"""
left, right = self._get_changed(start, end)
if left < right:
return True
return False | Tell whether any of start till end lines have changed
The end points are inclusive and indices start from 1. |
def get_pdffilepath(pdffilename):
"""
Returns the path for the pdf file
args:
pdffilename: string
returns path for the plots folder / pdffilename.pdf
"""
return FILEPATHSTR.format(
root_dir=ROOT_DIR, os_sep=os.sep, os_extsep=os.extsep,
... | Returns the path for the pdf file
args:
pdffilename: string
returns path for the plots folder / pdffilename.pdf |
def connect_delete_namespaced_pod_proxy(self, name, namespace, **kwargs): # noqa: E501
"""connect_delete_namespaced_pod_proxy # noqa: E501
connect DELETE requests to proxy of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP reques... | connect_delete_namespaced_pod_proxy # noqa: E501
connect DELETE requests to proxy of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_delete_namespaced_pod_proxy(name, na... |
def p_formula_atom(self, p):
"""formula : ATOM
| TRUE
| FALSE"""
if p[1]==Symbols.TRUE.value:
p[0] = PLTrue()
elif p[1]==Symbols.FALSE.value:
p[0] = PLFalse()
else:
p[0] = PLAtomic(Symbol(p[1])) | formula : ATOM
| TRUE
| FALSE |
def trigger_script(self):
"""Actually process a script."""
if self.remote_bridge.status not in (BRIDGE_STATUS.RECEIVED,):
return [1] #FIXME: State change
# This is asynchronous in real life so just cache the error
try:
self.remote_bridge.parsed_script = UpdateSc... | Actually process a script. |
def set_basic_params(
self, workers=None, zerg_server=None, fallback_node=None, concurrent_events=None,
cheap_mode=None, stats_server=None, quiet=None, buffer_size=None,
keepalive=None, resubscribe_addresses=None):
"""
:param int workers: Number of worker processes to... | :param int workers: Number of worker processes to spawn.
:param str|unicode zerg_server: Attach the router to a zerg server.
:param str|unicode fallback_node: Fallback to the specified node in case of error.
:param int concurrent_events: Set the maximum number of concurrent events router can ... |
def objectcount(data, key):
"""return the count of objects of key"""
objkey = key.upper()
return len(data.dt[objkey]) | return the count of objects of key |
def add_cable_dist(self, lv_cable_dist):
"""Adds a LV cable_dist to _cable_dists and grid graph if not already existing
Parameters
----------
lv_cable_dist :
Description #TODO
"""
if lv_cable_dist not in self._cable_distributors and isinstance(lv_cab... | Adds a LV cable_dist to _cable_dists and grid graph if not already existing
Parameters
----------
lv_cable_dist :
Description #TODO |
def do_search(self, string):
"""Search Ndrive for filenames containing the given string."""
results = self.n.doSearch(string, full_path = self.current_path)
if results:
for r in results:
self.stdout.write("%s\n" % r['path']) | Search Ndrive for filenames containing the given string. |
def say(self, message, **options):
"""
When the current session is a voice channel this key will either play a message or an audio file from a URL.
In the case of an text channel it will send the text back to the user via i nstant messaging or SMS.
Argument: message is a string
A... | When the current session is a voice channel this key will either play a message or an audio file from a URL.
In the case of an text channel it will send the text back to the user via i nstant messaging or SMS.
Argument: message is a string
Argument: **options is a set of optional keyword argumen... |
def get_cell_shift(flow_model):
"""Get flow direction induced cell shift dict.
Args:
flow_model: Currently, "TauDEM", "ArcGIS", and "Whitebox" are supported.
"""
assert flow_model.lower() in FlowModelConst.d8_deltas
return FlowModelConst.d8_deltas.get(flow_model.lower... | Get flow direction induced cell shift dict.
Args:
flow_model: Currently, "TauDEM", "ArcGIS", and "Whitebox" are supported. |
def special_handling(self, text):
"""special_handling = "?" , identifier , "?" ;"""
self._attempting(text)
return concatenation([
"?",
self.identifier,
"?",
], ignore_whitespace=True)(text).retyped(TokenType.special_handling) | special_handling = "?" , identifier , "?" ; |
def getWord(self, pattern, returnDiff = 0):
"""
Returns the word associated with pattern.
Example: net.getWord([0, 0, 0, 1]) => "tom"
This method now returns the closest pattern based on distance.
"""
minDist = 10000
closest = None
for w in self.patterns... | Returns the word associated with pattern.
Example: net.getWord([0, 0, 0, 1]) => "tom"
This method now returns the closest pattern based on distance. |
def qwarp_epi(dset,align_subbrick=5,suffix='_qwal',prefix=None):
'''aligns an EPI time-series using 3dQwarp
Very expensive and not efficient at all, but it can produce pretty impressive alignment for EPI time-series with significant
distortions due to motion'''
info = nl.dset_info(dset)
if info==No... | aligns an EPI time-series using 3dQwarp
Very expensive and not efficient at all, but it can produce pretty impressive alignment for EPI time-series with significant
distortions due to motion |
def neighbor(self, **kwargs):
"""Add BGP neighbor.
Args:
ip_addr (str): IP Address of BGP neighbor.
remote_as (str): Remote ASN of BGP neighbor.
vrf (str): The VRF for this BGP process.
rbridge_id (str): The rbridge ID of the device on which BGP will be
... | Add BGP neighbor.
Args:
ip_addr (str): IP Address of BGP neighbor.
remote_as (str): Remote ASN of BGP neighbor.
vrf (str): The VRF for this BGP process.
rbridge_id (str): The rbridge ID of the device on which BGP will be
configured in a VCS fabric... |
def handler(self, environ, start_response):
"""Proxy for requests to the actual http server"""
logger = logging.getLogger(__name__ + '.WSGIProxyApplication.handler')
url = urlparse(reconstruct_url(environ, self.port))
# Create connection object
try:
connection = self... | Proxy for requests to the actual http server |
def getDefaultConfigObj(taskname,configObj,input_dict={},loadOnly=True):
""" Return default configObj instance for task updated
with user-specified values from input_dict.
Parameters
----------
taskname : string
Name of task to load into TEAL
configObj : string
... | Return default configObj instance for task updated
with user-specified values from input_dict.
Parameters
----------
taskname : string
Name of task to load into TEAL
configObj : string
The valid values for 'configObj' would be::
None ... |
def get_config(self):
"""
Returns pickle-serializable configuration struct for storage.
"""
# Fill this dict with config data
return {
'hash_name': self.hash_name,
'dim': self.dim,
'bin_width': self.bin_width,
'projection_count': se... | Returns pickle-serializable configuration struct for storage. |
def _advapi32_create_handles(cipher, key, iv):
"""
Creates an HCRYPTPROV and HCRYPTKEY for symmetric encryption/decryption. The
HCRYPTPROV must be released by close_context_handle() and the
HCRYPTKEY must be released by advapi32.CryptDestroyKey() when done.
:param cipher:
A unicode string o... | Creates an HCRYPTPROV and HCRYPTKEY for symmetric encryption/decryption. The
HCRYPTPROV must be released by close_context_handle() and the
HCRYPTKEY must be released by advapi32.CryptDestroyKey() when done.
:param cipher:
A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key",
... |
def set_cookie(response, name, value, expiry_seconds=None, secure=False):
"""
Set cookie wrapper that allows number of seconds to be given as the
expiry time, and ensures values are correctly encoded.
"""
if expiry_seconds is None:
expiry_seconds = 90 * 24 * 60 * 60 # Default to 90 days.
... | Set cookie wrapper that allows number of seconds to be given as the
expiry time, and ensures values are correctly encoded. |
def _execute_callback(async, callback):
"""Execute the given callback or insert the Async callback, or if no
callback is given return the async.result.
"""
from furious.async import Async
if not callback:
return async.result.payload
if isinstance(callback, Async):
return callba... | Execute the given callback or insert the Async callback, or if no
callback is given return the async.result. |
def record(self, i=0):
"""Returns a specific dbf record based on the supplied index."""
f = self.__getFileObj(self.dbf)
if not self.numRecords:
self.__dbfHeader()
i = self.__restrictIndex(i)
recSize = self.__recordFmt()[1]
f.seek(0)
f.seek(self... | Returns a specific dbf record based on the supplied index. |
def _createIndexRti(self, index, nodeName):
""" Auxiliary method that creates a PandasIndexRti.
"""
return PandasIndexRti(index=index, nodeName=nodeName, fileName=self.fileName,
iconColor=self._iconColor) | Auxiliary method that creates a PandasIndexRti. |
def transform(self, pyobject):
"""Transform a `PyObject` to textual form"""
if pyobject is None:
return ('none',)
object_type = type(pyobject)
try:
method = getattr(self, object_type.__name__ + '_to_textual')
return method(pyobject)
except Attr... | Transform a `PyObject` to textual form |
def hrd_new(self, input_label="", skip=0):
"""
plot an HR diagram with options to skip the first N lines and
add a label string
Parameters
----------
input_label : string, optional
Diagram label. The default is "".
skip : integer, optional
... | plot an HR diagram with options to skip the first N lines and
add a label string
Parameters
----------
input_label : string, optional
Diagram label. The default is "".
skip : integer, optional
Skip the first n lines. The default is 0. |
def _has_exclusive_option(cls, options):
"""Return `True` iff one or more exclusive options were selected."""
return any([getattr(options, opt) is not None for opt in
cls.BASE_ERROR_SELECTION_OPTIONS]) | Return `True` iff one or more exclusive options were selected. |
def setBatchSize(self, val):
"""
Sets the value of :py:attr:`batchSize`.
"""
self._paramMap[self.batchSize] = val
pythonBigDL_method_name = "setBatchSize" + self.__class__.__name__
callBigDlFunc(self.bigdl_type, pythonBigDL_method_name, self.value, val)
return sel... | Sets the value of :py:attr:`batchSize`. |
def Join(self, Id):
"""Joins with another call to form a conference.
:Parameters:
Id : int
Call Id of the other call to join to the conference.
:return: Conference object.
:rtype: `Conference`
"""
#self._Alter('JOIN_CONFERENCE', Id)
reply =... | Joins with another call to form a conference.
:Parameters:
Id : int
Call Id of the other call to join to the conference.
:return: Conference object.
:rtype: `Conference` |
def external2internal(xe, bounds):
""" Convert a series of external variables to internal variables"""
xi = np.empty_like(xe)
for i, (v, bound) in enumerate(zip(xe, bounds)):
a = bound[0] # minimum
b = bound[1] # maximum
if a == None and b == None: # No constraints
... | Convert a series of external variables to internal variables |
def get_year_and_month(self, net, qs, **kwargs):
"""
Get the year and month. First tries from kwargs, then from
querystrings. If none, or if cal_ignore qs is specified,
sets year and month to this year and this month.
"""
now = c.get_now()
year = now.year
... | Get the year and month. First tries from kwargs, then from
querystrings. If none, or if cal_ignore qs is specified,
sets year and month to this year and this month. |
def gmean(data, channels=None):
"""
Calculate the geometric mean of the events in an FCSData object.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
channels : int or st... | Calculate the geometric mean of the events in an FCSData object.
Parameters
----------
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters (aka channels).
channels : int or str or list of int or list of str, optional
... |
def main():
"""
Commandline interface to initialize Sockeye embedding weights with pretrained word representations.
"""
setup_main_logger(console=True, file_logging=False)
params = argparse.ArgumentParser(description='Quick usage: python3 -m sockeye.init_embedding '
... | Commandline interface to initialize Sockeye embedding weights with pretrained word representations. |
def musixmatch(song):
"""
Returns the lyrics found in musixmatch for the specified mp3 file or an
empty string if not found.
"""
escape = re.sub("'-¡¿", '', URLESCAPE)
translate = {
escape: '',
' ': '-'
}
artist = song.artist.title()
artist = re.sub(r"( '|' )", '', ar... | Returns the lyrics found in musixmatch for the specified mp3 file or an
empty string if not found. |
def _get_bootstrap_url(directory):
'''
Get the most appropriate download URL for the bootstrap script.
directory
directory to execute in
'''
v = _get_buildout_ver(directory)
return _URL_VERSIONS.get(v, _URL_VERSIONS[DEFAULT_VER]) | Get the most appropriate download URL for the bootstrap script.
directory
directory to execute in |
def linear_interpolation_extrapolation(df, target_height):
r"""
Linear inter- or extrapolates between the values of a data frame.
This function can be used for the inter-/extrapolation of a parameter
(e.g wind speed) available at two or more different heights, to approximate
the value at hub height... | r"""
Linear inter- or extrapolates between the values of a data frame.
This function can be used for the inter-/extrapolation of a parameter
(e.g wind speed) available at two or more different heights, to approximate
the value at hub height. The function is carried out when the parameter
`wind_spee... |
def replace_all_post_order(expression: Expression, rules: Iterable[ReplacementRule]) \
-> Union[Expression, Sequence[Expression]]:
"""Replace all occurrences of the patterns according to the replacement rules.
A replacement rule consists of a *pattern*, that is matched against any subexpression
of ... | Replace all occurrences of the patterns according to the replacement rules.
A replacement rule consists of a *pattern*, that is matched against any subexpression
of the expression. If a match is found, the *replacement* callback of the rule is called with
the variables from the match substitution. Whatever... |
def illumination(x, gamma=1., contrast=1., saturation=1., is_random=False):
"""Perform illumination augmentation for a single image, randomly or non-randomly.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
gamma : float
Change bright... | Perform illumination augmentation for a single image, randomly or non-randomly.
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
gamma : float
Change brightness (the same with ``tl.prepro.brightness``)
- if is_random=False, one... |
def adjust_brightness_contrast(image, brightness=0., contrast=0.):
"""
Adjust the brightness and/or contrast of an image
:param image: OpenCV BGR image
:param contrast: Float, contrast adjustment with 0 meaning no change
:param brightness: Float, brightness adjustment with 0 meaning no change
"... | Adjust the brightness and/or contrast of an image
:param image: OpenCV BGR image
:param contrast: Float, contrast adjustment with 0 meaning no change
:param brightness: Float, brightness adjustment with 0 meaning no change |
def update_series(self, series):
"""Update a series with new attributes. This does not change
any of the data written to this series. The recommended workflow for
series updates is to pull a Series object down using the
:meth:`get_series` method, change its attributes, then pass it into... | Update a series with new attributes. This does not change
any of the data written to this series. The recommended workflow for
series updates is to pull a Series object down using the
:meth:`get_series` method, change its attributes, then pass it into
this method.
:param series... |
def filter_empty_parameters(func):
"""Decorator that is filtering empty parameters.
:param func: function that you want wrapping
:type func: function
"""
@wraps(func)
def func_wrapper(self, *args, **kwargs):
my_kwargs = {key: value for key, value in kwargs.items()
i... | Decorator that is filtering empty parameters.
:param func: function that you want wrapping
:type func: function |
def compress(x, y):
"""
Given a x,y coordinate, encode in "compressed format"
Returned is always 33 bytes.
"""
polarity = "02" if y % 2 == 0 else "03"
wrap = lambda x: x
if not is_py2:
wrap = lambda x: bytes(x, 'ascii')
return unhexlify(wrap("%s%0.64x" % (polarity, x))) | Given a x,y coordinate, encode in "compressed format"
Returned is always 33 bytes. |
def translate_path(self, path):
"""Translate a /-separated PATH to the local filename syntax.
Components that mean special things to the local file system
(e.g. drive or directory names) are ignored. (XXX They should
probably be diagnosed.)
"""
# abandon query paramete... | Translate a /-separated PATH to the local filename syntax.
Components that mean special things to the local file system
(e.g. drive or directory names) are ignored. (XXX They should
probably be diagnosed.) |
def IterAssociatorInstancePaths(self, InstanceName, AssocClass=None,
ResultClass=None,
Role=None, ResultRole=None,
FilterQueryLanguage=None, FilterQuery=None,
OperationTimeout=... | Retrieve the instance paths of the instances associated to a source
instance, using the Python :term:`py:generator` idiom to return the
result.
*New in pywbem 0.10 as experimental and finalized in 0.12.*
This method uses the corresponding pull operations if supported by the
WBE... |
def add_chan(self, chan, color=None, values=None, limits_c=None,
colormap=CHAN_COLORMAP, alpha=None, colorbar=False):
"""Add channels to visualization
Parameters
----------
chan : instance of Channels
channels to plot
color : tuple
3-, 4-... | Add channels to visualization
Parameters
----------
chan : instance of Channels
channels to plot
color : tuple
3-, 4-element tuple, representing RGB and alpha, between 0 and 1
values : ndarray
array with values for each channel
limits_... |
def titlefy(subject):
"""\
Titlecases the provided subject but respects common abbreviations.
This function returns ``None`` if the provided `subject` is ``None``. It
returns an empty string if the provided subject is empty.
`subject
A cable's subject.
"""
def clean_word(word... | \
Titlecases the provided subject but respects common abbreviations.
This function returns ``None`` if the provided `subject` is ``None``. It
returns an empty string if the provided subject is empty.
`subject
A cable's subject. |
def _process_output_source_directive(schema, current_schema_type, ast,
location, context, local_unique_directives):
"""Process the output_source directive, modifying the context as appropriate.
Args:
schema: GraphQL schema object, obtained from the graphql library
... | Process the output_source directive, modifying the context as appropriate.
Args:
schema: GraphQL schema object, obtained from the graphql library
current_schema_type: GraphQLType, the schema type at the current location
ast: GraphQL AST node, obtained from the graphql library
locati... |
def integer(description, **kwargs) -> typing.Type:
"""Create a :class:`~doctor.types.Integer` type.
:param description: A description of the type.
:param kwargs: Can include any attribute defined in
:class:`~doctor.types.Integer`
"""
kwargs['description'] = description
return type('Inte... | Create a :class:`~doctor.types.Integer` type.
:param description: A description of the type.
:param kwargs: Can include any attribute defined in
:class:`~doctor.types.Integer` |
def toFilename(url):
'''
gets url and returns filename
'''
urlp = urlparse(url)
path = urlp.path
if not path:
path = "file_{}".format(int(time.time()))
value = re.sub(r'[^\w\s\.\-]', '-', path).strip().lower()
return re.sub(r'[-\s]+', '-', value).strip("-")[-200:] | gets url and returns filename |
def map_constructor(self, loader, node, deep=False):
""" Walk the mapping, recording any duplicate keys.
"""
mapping = {}
for key_node, value_node in node.value:
key = loader.construct_object(key_node, deep=deep)
value = loader.construct_object(value_node, deep=... | Walk the mapping, recording any duplicate keys. |
def do_continue(self, arg):
"""
continue - continue execution
g - continue execution
go - continue execution
"""
if self.cmdprefix:
raise CmdError("prefix not allowed")
if arg:
raise CmdError("too many arguments")
if self.debug.get_... | continue - continue execution
g - continue execution
go - continue execution |
def _check_holiday_structure(self, times):
""" To check the structure of the HolidayClass
:param list times: years or months or days or number week
:rtype: None or Exception
:return: in the case of exception returns the exception
"""
if not isinstance(times, list):
... | To check the structure of the HolidayClass
:param list times: years or months or days or number week
:rtype: None or Exception
:return: in the case of exception returns the exception |
def _submit_request(self):
"""Submit a request to the ACS Zeropoint Calculator.
If an exception is raised during the request, an error message is
given. Otherwise, the response is saved in the corresponding
attribute.
"""
try:
self._response = urlopen(self._... | Submit a request to the ACS Zeropoint Calculator.
If an exception is raised during the request, an error message is
given. Otherwise, the response is saved in the corresponding
attribute. |
def merge(self, elements):
''' Merges all scraping results to a list sorted by frequency of occurrence. '''
from collections import Counter
from lltk.utils import list2tuple, tuple2list
# The list2tuple conversion is necessary because mutable objects (e.g. lists) are not hashable
merged = tuple2list([value f... | Merges all scraping results to a list sorted by frequency of occurrence. |
def nice_display(item):
"""Display a comma-separated list of models for M2M fields"""
if hasattr(item, 'all'): # RelatedManager: display a list
return ', '.join(map(text_type, item.all()))
return item | Display a comma-separated list of models for M2M fields |
def set_resolved_url(self, item=None, subtitles=None):
'''Takes a url or a listitem to be played. Used in conjunction with a
playable list item with a path that calls back into your addon.
:param item: A playable list item or url. Pass None to alert XBMC of a
failure to res... | Takes a url or a listitem to be played. Used in conjunction with a
playable list item with a path that calls back into your addon.
:param item: A playable list item or url. Pass None to alert XBMC of a
failure to resolve the item.
.. warning:: When using set_r... |
def add_row(self, key: str, default: str=None,
unit_label: str=None, enable: bool=None):
"""
Add a single row and re-draw as necessary
:param key: the name and dict accessor
:param default: the default value
:param unit_label: the label that should be \
a... | Add a single row and re-draw as necessary
:param key: the name and dict accessor
:param default: the default value
:param unit_label: the label that should be \
applied at the right of the entry
:param enable: the 'enabled' state (defaults to True)
:return: |
def info(zone, show_all=False):
'''
Display the configuration from memory
zone : string
name of zone
show_all : boolean
also include calculated values like capped-cpu, cpu-shares, ...
CLI Example:
.. code-block:: bash
salt '*' zonecfg.info tallgeese
'''
ret = ... | Display the configuration from memory
zone : string
name of zone
show_all : boolean
also include calculated values like capped-cpu, cpu-shares, ...
CLI Example:
.. code-block:: bash
salt '*' zonecfg.info tallgeese |
def print(self, indent=0):
"""Print self with optional indent."""
text = (
'{indent}{magenta}{name}{none} ({dim}{cls}{none}, '
'default {dim}{default}{none})'
).format(
indent=' ' * indent,
dim=Style.DIM,
magenta=Fore.MAGENTA,
... | Print self with optional indent. |
def check_lon(self, dataset):
'''
float lon(timeSeries) ; //........................................ Depending on the precision used for the variable, the data type could be int or double instead of float.
lon:long_name = "" ; //...................................... RECOMMENDED
... | float lon(timeSeries) ; //........................................ Depending on the precision used for the variable, the data type could be int or double instead of float.
lon:long_name = "" ; //...................................... RECOMMENDED
lon:standard_name = "longitude" ; //................. |
def _find_only_column_of_type(sframe, target_type, type_name, col_name):
"""
Finds the only column in `SFrame` with a type specified by `target_type`.
If there are zero or more than one such columns, an exception will be
raised. The name and type of the target column should be provided as
strings fo... | Finds the only column in `SFrame` with a type specified by `target_type`.
If there are zero or more than one such columns, an exception will be
raised. The name and type of the target column should be provided as
strings for the purpose of error feedback. |
async def do_authentication(sender):
"""
Executes the authentication process with the Telegram servers.
:param sender: a connected `MTProtoPlainSender`.
:return: returns a (authorization key, time offset) tuple.
"""
# Step 1 sending: PQ Request, endianness doesn't matter since it's random
n... | Executes the authentication process with the Telegram servers.
:param sender: a connected `MTProtoPlainSender`.
:return: returns a (authorization key, time offset) tuple. |
def order_target(self) -> Optional[Union[int, Point2]]:
""" Returns the target tag (if it is a Unit) or Point2 (if it is a Position)
from the first order, returns None if the unit is idle """
if self.orders:
if isinstance(self.orders[0].target, int):
return self.order... | Returns the target tag (if it is a Unit) or Point2 (if it is a Position)
from the first order, returns None if the unit is idle |
def perform_command(self):
"""
Perform command and return the appropriate exit code.
:rtype: int
"""
if len(self.actual_arguments) < 2:
return self.print_help()
source_url = self.actual_arguments[0]
output_file_path = self.actual_arguments[1]
... | Perform command and return the appropriate exit code.
:rtype: int |
def instance_attr_ancestors(self, name, context=None):
"""Iterate over the parents that define the given name as an attribute.
:param name: The name to find definitions for.
:type name: str
:returns: The parents that define the given name as
an instance attribute.
:... | Iterate over the parents that define the given name as an attribute.
:param name: The name to find definitions for.
:type name: str
:returns: The parents that define the given name as
an instance attribute.
:rtype: iterable(NodeNG) |
def host_domains(self, ip=None, limit=None, **kwargs):
"""Pass in an IP address."""
return self._results('reverse-ip', '/v1/{0}/host-domains'.format(ip), limit=limit, **kwargs) | Pass in an IP address. |
def merge(objects, compat='no_conflicts', join='outer'):
"""Merge any number of xarray objects into a single Dataset as variables.
Parameters
----------
objects : Iterable[Union[xarray.Dataset, xarray.DataArray, dict]]
Merge together all variables from these objects. If any of them are
... | Merge any number of xarray objects into a single Dataset as variables.
Parameters
----------
objects : Iterable[Union[xarray.Dataset, xarray.DataArray, dict]]
Merge together all variables from these objects. If any of them are
DataArray objects, they must have a name.
compat : {'identic... |
def _print_message(self, flag_message=None, color=None, padding=None,
reverse=False):
""" Outputs the message to the terminal """
if flag_message:
flag_message = stdout_encode(flag(flag_message,
color=color if self.pretty e... | Outputs the message to the terminal |
def add(self, pointer, value):
"""Add element to sequence, member to mapping.
:param pointer: the path to add in it
:param value: the new value
:return: resolved document
:rtype: Target
The pointer must reference one of:
- The root of the target document - w... | Add element to sequence, member to mapping.
:param pointer: the path to add in it
:param value: the new value
:return: resolved document
:rtype: Target
The pointer must reference one of:
- The root of the target document - whereupon the specified value
b... |
def is_catchup_needed_during_view_change(self) -> bool:
"""
Check if received a quorum of view change done messages and if yes
check if caught up till the
Check if all requests ordered till last prepared certificate
Check if last catchup resulted in no txns
"""
if... | Check if received a quorum of view change done messages and if yes
check if caught up till the
Check if all requests ordered till last prepared certificate
Check if last catchup resulted in no txns |
def _setting(self, key, default):
"""Return the setting, checking config, then the appropriate
environment variable, falling back to the default, caching the
results.
:param str key: The key to get
:param any default: The default value if not set
:return: str
""... | Return the setting, checking config, then the appropriate
environment variable, falling back to the default, caching the
results.
:param str key: The key to get
:param any default: The default value if not set
:return: str |
def coroutine(func):
"""Wraps a PEP-342 enhanced generator in a way that avoids boilerplate of the "priming" call to ``next``.
Args:
func (Callable): The function constructing a generator to decorate.
Returns:
Callable: The decorated generator.
"""
def wrapper(*args, **kwargs):
... | Wraps a PEP-342 enhanced generator in a way that avoids boilerplate of the "priming" call to ``next``.
Args:
func (Callable): The function constructing a generator to decorate.
Returns:
Callable: The decorated generator. |
def __openlib(self):
'''
Actual (lazy) dlopen() only when an attribute is accessed
'''
if self.__getattribute__('_libloaded'):
return
libpath_list = self.__get_libres()
for p in libpath_list:
try:
libres = resource_filename(self._mo... | Actual (lazy) dlopen() only when an attribute is accessed |
def received_message(self, address, data):
"""Process a message received from the KNX bus."""
self.value_cache.set(address, data)
if self.notify:
self.notify(address, data)
try:
listeners = self.address_listeners[address]
except KeyError:
list... | Process a message received from the KNX bus. |
def get_event_loop():
"""Return a EventLoop instance.
A new instance is created for each new HTTP request. We determine
that we're in a new request by inspecting os.environ, which is reset
at the start of each request. Also, each thread gets its own loop.
"""
ev = _state.event_loop
if not os.getenv(_EV... | Return a EventLoop instance.
A new instance is created for each new HTTP request. We determine
that we're in a new request by inspecting os.environ, which is reset
at the start of each request. Also, each thread gets its own loop. |
def noEmptyNests(node):
'''recursively make sure that no dictionaries inside node contain empty children lists '''
if type(node)==list:
for i in node:
noEmptyNests(i)
if type(node)==dict:
for i in node.values():
noEmptyNests(i)
if node["children"] == []:
... | recursively make sure that no dictionaries inside node contain empty children lists |
def _remove(self, xer, primary):
"""
Private method for removing a descriptor from the event loop.
It does the inverse job of _add, and also add a check in case of the fd
has gone away.
"""
if xer in primary:
notifier = primary.pop(xer)
notifier.s... | Private method for removing a descriptor from the event loop.
It does the inverse job of _add, and also add a check in case of the fd
has gone away. |
def _create_user_posts_table(self):
"""
Creates the table to store association info between user and blog
posts.
:return:
"""
with self._engine.begin() as conn:
user_posts_table_name = self._table_name("user_posts")
if not conn.dialect.has_table(co... | Creates the table to store association info between user and blog
posts.
:return: |
def clearRedisPools():
'''
clearRedisPools - Disconnect all managed connection pools,
and clear the connectiobn_pool attribute on all stored managed connection pools.
A "managed" connection pool is one where REDIS_CONNECTION_PARAMS does not define the "connection_pool" attribute.
If you define your ... | clearRedisPools - Disconnect all managed connection pools,
and clear the connectiobn_pool attribute on all stored managed connection pools.
A "managed" connection pool is one where REDIS_CONNECTION_PARAMS does not define the "connection_pool" attribute.
If you define your own pools, IndexedRedis will u... |
def write(self, fname, append=True):
"""
Write detection to csv formatted file.
Will append if append==True and file exists
:type fname: str
:param fname: Full path to file to open and write to.
:type append: bool
:param append: Set to true to append to an exist... | Write detection to csv formatted file.
Will append if append==True and file exists
:type fname: str
:param fname: Full path to file to open and write to.
:type append: bool
:param append: Set to true to append to an existing file, if True \
and file doesn't exist, w... |
def train(cls, data, isotonic=True):
"""
Train an isotonic regression model on the given data.
:param data:
RDD of (label, feature, weight) tuples.
:param isotonic:
Whether this is isotonic (which is default) or antitonic.
(default: True)
"""
... | Train an isotonic regression model on the given data.
:param data:
RDD of (label, feature, weight) tuples.
:param isotonic:
Whether this is isotonic (which is default) or antitonic.
(default: True) |
def current_frame(self, n):
"""Sets current frame to ``n``
:param integer n: Frame to set to ``current_frame``
"""
self.sound.seek(n)
self._current_frame = n | Sets current frame to ``n``
:param integer n: Frame to set to ``current_frame`` |
def pprint(object, stream=None, indent=1, width=80, depth=None):
"""Pretty-print a Python object to a stream [default is sys.stdout]."""
printer = PrettyPrinter(
stream=stream, indent=indent, width=width, depth=depth)
printer.pprint(object) | Pretty-print a Python object to a stream [default is sys.stdout]. |
def network_create(auth=None, **kwargs):
'''
Create a network
name
Name of the network being created
shared : False
If ``True``, set the network as shared
admin_state_up : True
If ``True``, Set the network administrative state to "up"
external : False
Control ... | Create a network
name
Name of the network being created
shared : False
If ``True``, set the network as shared
admin_state_up : True
If ``True``, Set the network administrative state to "up"
external : False
Control whether or not this network is externally accessible
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.