code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def histogram1d(data, bins=None, *args, **kwargs):
"""Facade function to create one-dimensional histogram using dask.
Parameters
----------
data: dask.DaskArray or array-like
See also
--------
physt.histogram
"""
import dask
if not hasattr(data, "dask"):
data = dask.arr... | Facade function to create one-dimensional histogram using dask.
Parameters
----------
data: dask.DaskArray or array-like
See also
--------
physt.histogram |
def _get_preferred_host(self, result: ResolveResult) -> Tuple[str, str]:
'''Get preferred host from DNS results.'''
host_1 = result.first_ipv4.ip_address if result.first_ipv4 else None
host_2 = result.first_ipv6.ip_address if result.first_ipv6 else None
if not host_2:
return... | Get preferred host from DNS results. |
def increment(self, key, amount=1):
"""
Increment one value in the object. Note that this happens immediately:
it does not wait for save() to be called
"""
payload = {
key: {
'__op': 'Increment',
'amount': amount
}
... | Increment one value in the object. Note that this happens immediately:
it does not wait for save() to be called |
def do_connect(self):
"""发起连接"""
assert self.socket is None
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.connect(self._connect_address) | 发起连接 |
def guess_line_ending(string):
'''Return the most likely line delimiter from the string.'''
assert isinstance(string, str), 'Expect str. Got {}'.format(type(string))
crlf_count = string.count('\r\n')
lf_count = string.count('\n')
if crlf_count >= lf_count:
return '\r\n'
else:
re... | Return the most likely line delimiter from the string. |
def tag_info_chart (self):
""" Make the taginfo.txt plot """
## TODO: human chrs on hg19. How will this work with GRCh genome or other, non human, genomes?
# nice if they are ordered by size
ucsc = ["chr" + str(i) for i in range(1,23)].append([ "chrX", "chrY", "chrM"])
ensembl ... | Make the taginfo.txt plot |
def validate_config_value(value, possible_values):
""" Validate a config value to make sure it is one of the possible values.
Args:
value: the config value to validate.
possible_values: the possible values the value can be
Raises:
Exception if the value is not one of possible values.
"""
if valu... | Validate a config value to make sure it is one of the possible values.
Args:
value: the config value to validate.
possible_values: the possible values the value can be
Raises:
Exception if the value is not one of possible values. |
def update_meta_data_for_transition_waypoints(graphical_editor_view, transition_v, last_waypoint_list, publish=True):
"""This method updates the relative position meta data of the transitions waypoints if they changed
:param graphical_editor_view: Graphical Editor the change occurred in
:param transition_v... | This method updates the relative position meta data of the transitions waypoints if they changed
:param graphical_editor_view: Graphical Editor the change occurred in
:param transition_v: Transition that changed
:param last_waypoint_list: List of waypoints before change
:param bool publish: Whether to ... |
def classmarkChange(MobileStationClassmark3_presence=0):
"""CLASSMARK CHANGE Section 9.1.11"""
a = TpPd(pd=0x6)
b = MessageType(mesType=0x16) # 00010110
c = MobileStationClassmark2()
packet = a / b / c
if MobileStationClassmark3_presence is 1:
e = MobileStationClassmark3(ieiMSC3=0x20)
... | CLASSMARK CHANGE Section 9.1.11 |
def add_query(self, query, join_with=AND):
"""Join a new query to existing queries on the stack.
Args:
query (tuple or list or DomainCondition): The condition for the
query. If a ``DomainCondition`` object is not provided, the
input should conform to the inte... | Join a new query to existing queries on the stack.
Args:
query (tuple or list or DomainCondition): The condition for the
query. If a ``DomainCondition`` object is not provided, the
input should conform to the interface defined in
:func:`~.domain.Domai... |
def author_name_contains_fullnames(author_name):
"""Recognizes whether the name contains full name parts and not initials or only lastname.
Returns:
bool: True if name has only full name parts, e.g. 'Ellis John', False otherwise. So for example, False is
returned for 'Ellis, J.' or 'Ellis... | Recognizes whether the name contains full name parts and not initials or only lastname.
Returns:
bool: True if name has only full name parts, e.g. 'Ellis John', False otherwise. So for example, False is
returned for 'Ellis, J.' or 'Ellis'. |
def purge_results(self, client_id, msg):
"""Purge results from memory. This method is more valuable before we move
to a DB based message storage mechanism."""
content = msg['content']
self.log.info("Dropping records with %s", content)
msg_ids = content.get('msg_ids', [])
... | Purge results from memory. This method is more valuable before we move
to a DB based message storage mechanism. |
def handle_apply(args):
"""usage: {program} apply <module-path> <operator> <occurrence>
Apply the specified mutation to the files on disk. This is primarily a debugging
tool.
options:
--python-version=VERSION Python major.minor version (e.g. 3.6) of the code being mutated.
"""
python_v... | usage: {program} apply <module-path> <operator> <occurrence>
Apply the specified mutation to the files on disk. This is primarily a debugging
tool.
options:
--python-version=VERSION Python major.minor version (e.g. 3.6) of the code being mutated. |
def _apply_line_rules(self, markdown_string):
""" Iterates over the lines in a given markdown string and applies all the enabled line rules to each line """
all_violations = []
lines = markdown_string.split("\n")
line_rules = self.line_rules
line_nr = 1
ignoring = False
... | Iterates over the lines in a given markdown string and applies all the enabled line rules to each line |
def add_camera_make_model(self, make, model):
''' Add camera make and model.'''
self._ef['0th'][piexif.ImageIFD.Make] = make
self._ef['0th'][piexif.ImageIFD.Model] = model | Add camera make and model. |
async def send(self, config, entry):
""" Send a webmention to this target from the specified entry """
if self.endpoint:
LOGGER.debug("%s -> %s", entry.url, self.url)
try:
await self.endpoint.send(config, entry.url, self.url)
except Exception as err: ... | Send a webmention to this target from the specified entry |
def serialize(self, image):
"""Turn a Image into a mutagen.flac.Picture.
"""
pic = mutagen.flac.Picture()
pic.data = image.data
pic.type = image.type_index
pic.mime = image.mime_type
pic.desc = image.desc or u''
return pic | Turn a Image into a mutagen.flac.Picture. |
def show(cls, report_name, data):
"""
Shows a report by issuing a GET request to the /reports/report_name
endpoint.
Args:
`report_name`: the name of the report to show
`data`: the parameters for the report
"""
conn = Qubole.agent()
return... | Shows a report by issuing a GET request to the /reports/report_name
endpoint.
Args:
`report_name`: the name of the report to show
`data`: the parameters for the report |
def get_user_sets(client_id, user_id):
"""Find all user sets."""
data = api_call('get', 'users/{}/sets'.format(user_id), client_id=client_id)
return [WordSet.from_dict(wordset) for wordset in data] | Find all user sets. |
def pr_auc(fg_vals, bg_vals):
"""
Computes the Precision-Recall Area Under Curve (PR AUC)
Parameters
----------
fg_vals : array_like
list of values for positive set
bg_vals : array_like
list of values for negative set
Returns
-------
score : float
PR AU... | Computes the Precision-Recall Area Under Curve (PR AUC)
Parameters
----------
fg_vals : array_like
list of values for positive set
bg_vals : array_like
list of values for negative set
Returns
-------
score : float
PR AUC score |
def parse(self, data_model, crit):
"""
Take the relevant pieces of the data model json
and parse into data model and criteria map.
Parameters
----------
data_model : data model piece of json (nested dicts)
crit : criteria map piece of json (nested dicts)
... | Take the relevant pieces of the data model json
and parse into data model and criteria map.
Parameters
----------
data_model : data model piece of json (nested dicts)
crit : criteria map piece of json (nested dicts)
Returns
----------
data_model : dictio... |
def accepts(**schemas):
"""Create a decorator for validating function parameters.
Example::
@accepts(a="number", body={"+field_ids": [int], "is_ok": bool})
def f(a, body):
print (a, body["field_ids"], body.get("is_ok"))
:param schemas: The schema for validating a given paramet... | Create a decorator for validating function parameters.
Example::
@accepts(a="number", body={"+field_ids": [int], "is_ok": bool})
def f(a, body):
print (a, body["field_ids"], body.get("is_ok"))
:param schemas: The schema for validating a given parameter. |
def traverse(self, edge):
"""
Traverse the graph, and selecting the destination
nodes for a particular relation that the selected
nodes are a source of, i.e. select the friends of
my friends. You can traverse indefinitely.
:param edge: The edge query. If the edge's
... | Traverse the graph, and selecting the destination
nodes for a particular relation that the selected
nodes are a source of, i.e. select the friends of
my friends. You can traverse indefinitely.
:param edge: The edge query. If the edge's
destination node is specified then the ... |
def get_line_number_next_to_cursor_with_string_within(self, s):
""" Find the closest occurrence of a string with respect to the cursor position in the text view """
line_number, _ = self.get_cursor_position()
text_buffer = self.text_view.get_buffer()
line_iter = text_buffer.get_iter_at_l... | Find the closest occurrence of a string with respect to the cursor position in the text view |
def get_servo_status(self):
""" Get the error status of servo
This function gets the error status (if any) of the servo
Args:
none
Returns:
int: an integer corresponding to the servo status
* refer datasheet
"""
data = []
... | Get the error status of servo
This function gets the error status (if any) of the servo
Args:
none
Returns:
int: an integer corresponding to the servo status
* refer datasheet |
def create (raw_properties = []):
""" Creates a new 'PropertySet' instance for the given raw properties,
or returns an already existing one.
"""
assert (is_iterable_typed(raw_properties, property.Property)
or is_iterable_typed(raw_properties, basestring))
# FIXME: propagate to caller... | Creates a new 'PropertySet' instance for the given raw properties,
or returns an already existing one. |
def get_objective_lookup_session(self, proxy):
"""Gets the ``OsidSession`` associated with the objective lookup service.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: an ``ObjectiveLookupSession``
:rtype: ``osid.learning.ObjectiveLookupSession``
:raise... | Gets the ``OsidSession`` associated with the objective lookup service.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: an ``ObjectiveLookupSession``
:rtype: ``osid.learning.ObjectiveLookupSession``
:raise: ``NullArgument`` -- ``proxy`` is ``null``
:raise... |
def add_default_values_of_scoped_variables_to_scoped_data(self):
"""Add the scoped variables default values to the scoped_data dictionary
"""
for key, scoped_var in self.scoped_variables.items():
self.scoped_data[str(scoped_var.data_port_id) + self.state_id] = \
Scop... | Add the scoped variables default values to the scoped_data dictionary |
def run_only_once(self, keyword):
"""
Runs a keyword only once in one of the parallel processes.
As the keyword will be called
only in one process and the return value could basically be anything.
The "Run Only Once" can't return the actual return value.
If the keyword fa... | Runs a keyword only once in one of the parallel processes.
As the keyword will be called
only in one process and the return value could basically be anything.
The "Run Only Once" can't return the actual return value.
If the keyword fails, "Run Only Once" fails.
Others executing "... |
def __new_argv(self, *new_pargs, **new_kargs):
"""Calculate new argv and extra_argv values resulting from adding
the specified positional and keyword arguments."""
new_argv = self.argv.copy()
new_extra_argv = list(self.extra_argv)
for v in new_pargs:
arg_name = None... | Calculate new argv and extra_argv values resulting from adding
the specified positional and keyword arguments. |
def _Register(self, conditions, callback):
"""Map functions that should be called if the condition applies."""
for condition in conditions:
registered = self._registry.setdefault(condition, [])
if callback and callback not in registered:
registered.append(callback) | Map functions that should be called if the condition applies. |
def _escape_xref(xref_match):
"""Escape things that need to be escaped if they're in a cross-reference.
"""
xref = xref_match.group()
xref = xref.replace('/', '%2F')
xref = xref.replace('?', '%3F')
xref = xref.replace('#', '%23')
return xref | Escape things that need to be escaped if they're in a cross-reference. |
def inputfiles(self, inputtemplate=None):
"""Generator yielding all inputfiles for the specified inputtemplate, if ``inputtemplate=None``, inputfiles are returned regardless of inputtemplate."""
if isinstance(inputtemplate, InputTemplate):
#ID suffices:
inputtemplate = inputtempl... | Generator yielding all inputfiles for the specified inputtemplate, if ``inputtemplate=None``, inputfiles are returned regardless of inputtemplate. |
def parse_only_extr_license(self, extr_lic):
"""
Return an ExtractedLicense object to represent a license object.
But does not add it to the SPDXDocument model.
Return None if failed.
"""
# Grab all possible values
ident = self.get_extr_license_ident(extr_lic)
... | Return an ExtractedLicense object to represent a license object.
But does not add it to the SPDXDocument model.
Return None if failed. |
def update_w(self):
""" alternating least squares step, update W under the convexity
constraint """
def update_single_w(i):
""" compute single W[:,i] """
# optimize beta using qp solver from cvxopt
FB = base.matrix(np.float64(np.dot(-self.data.T, W_hat[:,i... | alternating least squares step, update W under the convexity
constraint |
def poll(self, verbose_model_scoring_history = False):
"""
Wait until the job finishes.
This method will continuously query the server about the status of the job, until the job reaches a
completion. During this time we will display (in stdout) a progress bar with % completion status.
... | Wait until the job finishes.
This method will continuously query the server about the status of the job, until the job reaches a
completion. During this time we will display (in stdout) a progress bar with % completion status. |
def p_ioport_head_width(self, p):
'ioport_head : sigtypes width portname'
p[0] = self.create_ioport(p[1], p[3], width=p[2], lineno=p.lineno(3))
p.set_lineno(0, p.lineno(1)) | ioport_head : sigtypes width portname |
def update_vnic_template(self, host_id, vlan_id, physnet,
vnic_template_path, vnic_template):
"""Updates VNIC Template with the vlan_id."""
ucsm_ip = self.get_ucsm_ip_for_host(host_id)
if not ucsm_ip:
LOG.info('UCS Manager network driver does not have UCSM IP '
... | Updates VNIC Template with the vlan_id. |
def in_special_context(node):
""" Returns true if node is in an environment where all that is required
of it is being iterable (ie, it doesn't matter if it returns a list
or an iterator).
See test_map_nochange in test_fixers.py for some examples and tests.
"""
global p0, p1, p2, ... | Returns true if node is in an environment where all that is required
of it is being iterable (ie, it doesn't matter if it returns a list
or an iterator).
See test_map_nochange in test_fixers.py for some examples and tests. |
def pre_readline(self):
"""readline hook to be used at the start of each line.
Currently it handles auto-indent only."""
if self.rl_do_indent:
self.readline.insert_text(self._indent_current_str())
if self.rl_next_input is not None:
self.readline.insert_text(self... | readline hook to be used at the start of each line.
Currently it handles auto-indent only. |
def _compute_jsonclass(obj):
"""
Compute the content of the __jsonclass__ field for the given object
:param obj: An object
:return: The content of the __jsonclass__ field
"""
# It's not a standard type, so it needs __jsonclass__
module_name = inspect.getmodule(obj).__name__
json_class =... | Compute the content of the __jsonclass__ field for the given object
:param obj: An object
:return: The content of the __jsonclass__ field |
def get_offsets(self):
"""
returns
-------
a dictionary with these entries
header_start:
byte offset from beginning of the file to the start
of the header
data_start:
byte offset from beginning of the file to the start
of t... | returns
-------
a dictionary with these entries
header_start:
byte offset from beginning of the file to the start
of the header
data_start:
byte offset from beginning of the file to the start
of the data section
data_end:
... |
def set_scf_algorithm_and_iterations(self, algorithm="diis",
iterations=50):
"""
Set algorithm used for converging SCF and max number of SCF iterations.
Args:
algorithm: The algorithm used for converging SCF. (str)
iterations: The... | Set algorithm used for converging SCF and max number of SCF iterations.
Args:
algorithm: The algorithm used for converging SCF. (str)
iterations: The max number of SCF iterations. (Integer) |
def plot(self, data, color='k', symbol=None, line_kind='-', width=1.,
marker_size=10., edge_color='k', face_color='b', edge_width=1.,
title=None, xlabel=None, ylabel=None):
"""Plot a series of data using lines and markers
Parameters
----------
data : array | tw... | Plot a series of data using lines and markers
Parameters
----------
data : array | two arrays
Arguments can be passed as ``(Y,)``, ``(X, Y)`` or
``np.array((X, Y))``.
color : instance of Color
Color of the line.
symbol : str
Marker... |
def train(self, token, tag, previous=None, next=None):
""" Trains the model to predict the given tag for the given token,
in context of the given previous and next (token, tag)-tuples.
"""
self._classifier.train(self._v(token, previous, next), type=tag) | Trains the model to predict the given tag for the given token,
in context of the given previous and next (token, tag)-tuples. |
def validate_version(self, service_id, version_number):
"""Validate the version for a particular service and version."""
content = self._fetch("/service/%s/version/%d/validate" % (service_id, version_number))
return self._status(content) | Validate the version for a particular service and version. |
def closest_leaf_to_root(self):
'''Return the leaf that is closest to the root and the corresponding distance. Edges with no length will be considered to have a length of 0
Returns:
``tuple``: First value is the closest leaf to the root, and second value is the corresponding distance
... | Return the leaf that is closest to the root and the corresponding distance. Edges with no length will be considered to have a length of 0
Returns:
``tuple``: First value is the closest leaf to the root, and second value is the corresponding distance |
def group_by(what, by):
"""
Take a list and apply the given function on each its value, then group the
values by the function results.
.. testsetup::
from proso.list import group_by
.. doctest::
>>> group_by([i for i in range(10)], by=lambda x: x % 2 == 0)
{False: [1, 3, ... | Take a list and apply the given function on each its value, then group the
values by the function results.
.. testsetup::
from proso.list import group_by
.. doctest::
>>> group_by([i for i in range(10)], by=lambda x: x % 2 == 0)
{False: [1, 3, 5, 7, 9], True: [0, 2, 4, 6, 8]}
... |
def configuration_ES(t0: date, t1: Optional[date] = None,
steps_per_day: int = None) -> Tuple[np.ndarray, np.ndarray]:
"""
Get the positions and velocities of the earth and sun from date t0 to t1.
Returned as a tuple q, v
q: Nx3 array of positions (x, y, z) in the J2000.0 coordinat... | Get the positions and velocities of the earth and sun from date t0 to t1.
Returned as a tuple q, v
q: Nx3 array of positions (x, y, z) in the J2000.0 coordinate frame. |
def populateFromFile(self, dataUrl):
"""
Populates the instance variables of this FeatureSet from the specified
data URL.
"""
self._dbFilePath = dataUrl
self._db = Gff3DbBackend(self._dbFilePath) | Populates the instance variables of this FeatureSet from the specified
data URL. |
def get_alter_table_sql(self, diff):
"""
Get the ALTER TABLE SQL statement
:param diff: The table diff
:type diff: orator.dbal.table_diff.TableDiff
:rtype: list
"""
sql = self._get_simple_alter_table_sql(diff)
if sql is not False:
return sql
... | Get the ALTER TABLE SQL statement
:param diff: The table diff
:type diff: orator.dbal.table_diff.TableDiff
:rtype: list |
def is_transition_metal(self):
"""
True if element is a transition metal.
"""
ns = list(range(21, 31))
ns.extend(list(range(39, 49)))
ns.append(57)
ns.extend(list(range(72, 81)))
ns.append(89)
ns.extend(list(range(104, 113)))
return self.Z ... | True if element is a transition metal. |
def getReffs(self, level=1, subreference=None) -> CtsReferenceSet:
""" Reference available at a given level
:param level: Depth required. If not set, should retrieve first encountered level (1 based). 0 retrieves inside
a range
:param subreference: Subreference (optional)
:r... | Reference available at a given level
:param level: Depth required. If not set, should retrieve first encountered level (1 based). 0 retrieves inside
a range
:param subreference: Subreference (optional)
:returns: List of levels |
def getAutoStartEnabled(self):
"""Returns True if enabled, False if disabled"""
command = '$GE'
settings = self.sendCommand(command)
flags = int(settings[2], 16)
return not (flags & 0x0040) | Returns True if enabled, False if disabled |
def update_grammar_with_untyped_entities(grammar_dictionary: Dict[str, List[str]]) -> None:
"""
Variables can be treated as numbers or strings if their type can be inferred -
however, that can be difficult, so instead, we can just treat them all as values
and be a bit looser on the typing we allow in ou... | Variables can be treated as numbers or strings if their type can be inferred -
however, that can be difficult, so instead, we can just treat them all as values
and be a bit looser on the typing we allow in our grammar. Here we just remove
all references to number and string from the grammar, replacing them ... |
def dns_compress(pkt):
"""This function compresses a DNS packet according to compression rules.
"""
if DNS not in pkt:
raise Scapy_Exception("Can only compress DNS layers")
pkt = pkt.copy()
dns_pkt = pkt.getlayer(DNS)
build_pkt = raw(dns_pkt)
def field_gen(dns_pkt):
"""Itera... | This function compresses a DNS packet according to compression rules. |
def replace_mutating_webhook_configuration(self, name, body, **kwargs):
"""
replace the specified MutatingWebhookConfiguration
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_mutati... | replace the specified MutatingWebhookConfiguration
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_mutating_webhook_configuration(name, body, async_req=True)
>>> result = thread.get()
... |
def read(self, address, length_bytes, x, y, p=0):
"""Read a bytestring from an address in memory.
Parameters
----------
address : int
The address at which to start reading the data.
length_bytes : int
The number of bytes to read from memory. Large reads a... | Read a bytestring from an address in memory.
Parameters
----------
address : int
The address at which to start reading the data.
length_bytes : int
The number of bytes to read from memory. Large reads are
transparently broken into multiple SCP read co... |
def report(self):
"""Prints in standard output report about animation rendering. Namely, it prints seconds spent, number of
frames and step size that is used in functional animation.
"""
message = 'Elapsed in {0} seconds with {1} frames and {2} step.'
print(message.format(self.el... | Prints in standard output report about animation rendering. Namely, it prints seconds spent, number of
frames and step size that is used in functional animation. |
def transformer_symshard_base():
"""Set of hyperparameters."""
hparams = common_hparams.basic_params1()
hparams.hidden_size = 256
hparams.batch_size = 2048
hparams.max_length = 0
# All hyperparameters ending in "dropout" are automatically set to 0.0
# when not in training mode.
hparams.layer_prepostproc... | Set of hyperparameters. |
def color_range(color, N=20):
"""
Generates a scale of colours from a base colour
Parameters:
-----------
color : string
Color representation in hex
N : int
number of colours to generate
Example:
color_range('#ff9933',20... | Generates a scale of colours from a base colour
Parameters:
-----------
color : string
Color representation in hex
N : int
number of colours to generate
Example:
color_range('#ff9933',20) |
def _get_app_module_path(module_label):
""" Given a module label, loop over the apps specified in the INSTALLED_APPS to find the
corresponding application module path.
"""
app_name = module_label.rsplit('.', 1)[0]
for app in settings.INSTALLED_APPS:
if app.endswith('.' + app_name) or app... | Given a module label, loop over the apps specified in the INSTALLED_APPS to find the
corresponding application module path. |
async def get(self):
"""Remove and return an item from the queue.
If queue is empty, wait until an item is available.
This method is a coroutine.
"""
self._parent._check_closing()
async with self._parent._async_not_empty:
self._parent._sync_mutex.acquire()
... | Remove and return an item from the queue.
If queue is empty, wait until an item is available.
This method is a coroutine. |
def _retrieve_device_cache(proxy=None):
'''
Loads the network device details if not cached already.
'''
global DEVICE_CACHE
if not DEVICE_CACHE:
if proxy and salt.utils.napalm.is_proxy(__opts__):
# if proxy var passed and is NAPALM-type proxy minion
if 'napalm.get_dev... | Loads the network device details if not cached already. |
def wait(self):
""" waits for the process to complete, handles the exit code """
self.log.debug("acquiring wait lock to wait for completion")
# using the lock in a with-context blocks, which is what we want if
# we're running wait()
with self._wait_lock:
self.log.deb... | waits for the process to complete, handles the exit code |
def _lookup_node_parent(self, node):
"""
Return the parent of the given node, based on an internal dictionary
mapping of child nodes to the child's parent required since
ElementTree doesn't make info about node ancestry/parentage available.
"""
# Basic caching of our inte... | Return the parent of the given node, based on an internal dictionary
mapping of child nodes to the child's parent required since
ElementTree doesn't make info about node ancestry/parentage available. |
def accept( self ):
"""
Saves the data to the profile before closing.
"""
if ( not self.uiNameTXT.text() ):
QMessageBox.information(self,
'Invalid Name',
'You need to supply a name for your layout.')... | Saves the data to the profile before closing. |
def slughifi(value, overwrite_char_map={}):
"""
High Fidelity slugify - slughifi.py, v 0.1
Examples :
>>> text = 'C\'est déjà l\'été.'
>>> slughifi(text)
'cest-deja-lete'
>>> slughifi(text, overwrite_char_map={u'\': '-',})
'c-est-deja-l-ete'
>>> s... | High Fidelity slugify - slughifi.py, v 0.1
Examples :
>>> text = 'C\'est déjà l\'été.'
>>> slughifi(text)
'cest-deja-lete'
>>> slughifi(text, overwrite_char_map={u'\': '-',})
'c-est-deja-l-ete'
>>> slughifi(text, do_slugify=False)
"C'est deja l'ete."
... |
def WriteFixedString(self, value, length):
"""
Write a string value to the stream.
Args:
value (str): value to write to the stream.
length (int): length of the string to write.
"""
towrite = value.encode('utf-8')
slen = len(towrite)
if sle... | Write a string value to the stream.
Args:
value (str): value to write to the stream.
length (int): length of the string to write. |
def set(self, key, value):
"""Set a configuration property."""
# Try to set self._jconf first if JVM is created, set self._conf if JVM is not created yet.
if self._jconf is not None:
self._jconf.set(key, unicode(value))
else:
self._conf[key] = unicode(value)
... | Set a configuration property. |
def int_flags(flags, mapper=const.PERM_STRING_MAP):
"""
Converts string permission flags into integer permission flags as
specified in const.PERM_STRING_MAP
Arguments:
- flags <str>: one or more flags
For example: "crud" or "ru" or "r"
- mapper <list=const.PERM_STRING_MAP>: a... | Converts string permission flags into integer permission flags as
specified in const.PERM_STRING_MAP
Arguments:
- flags <str>: one or more flags
For example: "crud" or "ru" or "r"
- mapper <list=const.PERM_STRING_MAP>: a list containing tuples mapping
int permission flag ... |
def _walk(self, target, visitor):
"""Walks the dependency graph for the given target.
:param target: The target to start the walk from.
:param visitor: A function that takes a target and returns `True` if its dependencies should
also be visited.
"""
visited = set()
def walk... | Walks the dependency graph for the given target.
:param target: The target to start the walk from.
:param visitor: A function that takes a target and returns `True` if its dependencies should
also be visited. |
def filter(self, info, releases):
"""
Remove all release versions that match any of the specificed patterns.
"""
for version in list(releases.keys()):
if any(pattern.match(version) for pattern in self.patterns):
del releases[version] | Remove all release versions that match any of the specificed patterns. |
def list(self):
'''
Create a dictionary with the details for the updates in the collection.
Returns:
dict: Details about each update
.. code-block:: cfg
List of Updates:
{'<GUID>': {'Title': <title>,
'KB': <KB>,
... | Create a dictionary with the details for the updates in the collection.
Returns:
dict: Details about each update
.. code-block:: cfg
List of Updates:
{'<GUID>': {'Title': <title>,
'KB': <KB>,
'GUID': <the globally uni... |
def clean_pe_name(self, nlog, root):
"""additional name cleaning for paired end data"""
use_output_name = getattr(config, 'flash', {}).get('use_output_name', False)
if use_output_name:
name = re.search(r'Output files\:\n\[FLASH\]\s+(.+?)\n', nlog)
else:
name = re.... | additional name cleaning for paired end data |
def process_link(self, env, refnode, has_explicit_title, title, target):
"""Called after parsing title and target text, and creating the reference
node. Alter the reference node and return it with chapel module and
class information, if relevant.
"""
refnode['chpl:module'] = env.... | Called after parsing title and target text, and creating the reference
node. Alter the reference node and return it with chapel module and
class information, if relevant. |
def block_jids(self, jids_to_block):
"""
Add the JIDs in the sequence `jids_to_block` to the client's
blocklist.
"""
yield from self._check_for_blocking()
if not jids_to_block:
return
cmd = blocking_xso.BlockCommand(jids_to_block)
iq = aioxmp... | Add the JIDs in the sequence `jids_to_block` to the client's
blocklist. |
def generate(bits, progress_func=None):
"""
Generate a new private RSA key. This factory function can be used to
generate a new host key or authentication key.
@param bits: number of bits the generated key should be.
@type bits: int
@param progress_func: an optional fun... | Generate a new private RSA key. This factory function can be used to
generate a new host key or authentication key.
@param bits: number of bits the generated key should be.
@type bits: int
@param progress_func: an optional function to call at key points in
key generation (u... |
def get_display_opts(options, argv = sys.argv):
"""display, name, db, args = get_display_opts(options, [argv])
Parse X OPTIONS from ARGV (or sys.argv if not provided).
Connect to the display specified by a *.display resource if one is
set, or to the default X display otherwise. Extract the
RESOUR... | display, name, db, args = get_display_opts(options, [argv])
Parse X OPTIONS from ARGV (or sys.argv if not provided).
Connect to the display specified by a *.display resource if one is
set, or to the default X display otherwise. Extract the
RESOURCE_MANAGER property and insert all resources from ARGV.... |
def _insert_continuation_prompt(self, cursor):
""" Inserts new continuation prompt using the specified cursor.
"""
if self._continuation_prompt_html is None:
self._insert_plain_text(cursor, self._continuation_prompt)
else:
self._continuation_prompt = self._insert_... | Inserts new continuation prompt using the specified cursor. |
def reqContractDetails(self, contract: Contract) -> List[ContractDetails]:
"""
Get a list of contract details that match the given contract.
If the returned list is empty then the contract is not known;
If the list has multiple values then the contract is ambiguous.
The fully qu... | Get a list of contract details that match the given contract.
If the returned list is empty then the contract is not known;
If the list has multiple values then the contract is ambiguous.
The fully qualified contract is available in the the
ContractDetails.contract attribute.
T... |
def execute(self, conn, logical_file_name, transaction=False):
"""
simple execute
"""
if not conn:
dbsExceptionHandler("dbsException-db-conn-failed", "Oracle/FileBuffer/DeleteDupicates. Expects db connection from upper layer.")
print(self.sql)
self.dbi.processData(self.sql, logical_fil... | simple execute |
def normalize_nfc(txt):
"""
Normalize message to NFC and return bytes suitable for protobuf.
This seems to be bitcoin-qt standard of doing things.
"""
if isinstance(txt, bytes):
txt = txt.decode()
return unicodedata.normalize("NFC", txt).encode() | Normalize message to NFC and return bytes suitable for protobuf.
This seems to be bitcoin-qt standard of doing things. |
def mount_point(cls, file_path):
""" Return mount point that, where the given path is reside on
:param file_path: target path to search
:return: WMountPoint or None (if file path is outside current mount points)
"""
mount = None
for mp in cls.mounts():
mp_path = mp.path()
if file_path.startswith(mp_... | Return mount point that, where the given path is reside on
:param file_path: target path to search
:return: WMountPoint or None (if file path is outside current mount points) |
def MergeAllSummaries(period=0, run_alone=False, key=None):
"""
This callback is enabled by default.
Evaluate all summaries by ``tf.summary.merge_all``, and write them to logs.
Args:
period (int): by default the callback summarizes once every epoch.
This option (if not set to 0) mak... | This callback is enabled by default.
Evaluate all summaries by ``tf.summary.merge_all``, and write them to logs.
Args:
period (int): by default the callback summarizes once every epoch.
This option (if not set to 0) makes it additionally summarize every ``period`` steps.
run_alone (... |
def take_action(name=None, call=None, command=None, data=None, method='GET',
location=DEFAULT_LOCATION):
'''
take action call used by start,stop, reboot
:param name: name given to the machine
:param call: call value in this case is 'action'
:command: api path
:data: any data to ... | take action call used by start,stop, reboot
:param name: name given to the machine
:param call: call value in this case is 'action'
:command: api path
:data: any data to be passed to the api, must be in json format
:method: GET,POST,or DELETE
:location: data center to execute the command on
... |
def get_sql(self):
"""Retrieve the data type for a data record."""
test_method = [
self.is_time,
self.is_date,
self.is_datetime,
self.is_decimal,
self.is_year,
self.is_tinyint,
self.is_smallint,
self.is_mediu... | Retrieve the data type for a data record. |
def get_or_exception(cls, id):
''' Tries to retrieve an instance of this model from the database or
raises an exception in case of failure '''
obj = cls.get(id)
if obj is None:
raise ModelNotFoundError('This object does not exist in database')
return obj | Tries to retrieve an instance of this model from the database or
raises an exception in case of failure |
def read_vcf(input,
fields=None,
exclude_fields=None,
rename_fields=None,
types=None,
numbers=None,
alt_number=DEFAULT_ALT_NUMBER,
fills=None,
region=None,
tabix='tabix',
samples=None,
... | Read data from a VCF file into NumPy arrays.
.. versionchanged:: 1.12.0
Now returns None if no variants are found in the VCF file or matching the
requested region.
Parameters
----------
input : string or file-like
{input}
fields : list of strings, optional
{fields}
... |
def visit_str(self, node, parent):
"""visit a String/Bytes node by returning a fresh instance of Const"""
return nodes.Const(
node.s,
getattr(node, "lineno", None),
getattr(node, "col_offset", None),
parent,
) | visit a String/Bytes node by returning a fresh instance of Const |
def orderrun_detail(backend, kitchen, summary, nodestatus, runstatus, log, timing, test, all_things,
order_id, order_run_id, disp_order_id, disp_order_run_id):
"""
Display information about an Order-Run
"""
err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen)
if use_kitc... | Display information about an Order-Run |
def create_arguments(primary, pyfunction, call_node, scope):
"""A factory for creating `Arguments`"""
args = list(call_node.args)
args.extend(call_node.keywords)
called = call_node.func
# XXX: Handle constructors
if _is_method_call(primary, pyfunction) and \
isinstance(called, ast.Attribu... | A factory for creating `Arguments` |
def _create_pax_generic_header(cls, pax_headers, type, encoding):
"""Return a POSIX.1-2008 extended or global header sequence
that contains a list of keyword, value pairs. The values
must be strings.
"""
# Check if one of the fields contains surrogate characters and thereby... | Return a POSIX.1-2008 extended or global header sequence
that contains a list of keyword, value pairs. The values
must be strings. |
def stream(self, item, *, device_id=None, quality='hi', session_token=None):
"""Get MP3 stream of a podcast episode, library song, station_song, or store song.
Note:
Streaming requires a ``device_id`` from a valid, linked mobile device.
Parameters:
item (str): A podcast episode, library song, station_song... | Get MP3 stream of a podcast episode, library song, station_song, or store song.
Note:
Streaming requires a ``device_id`` from a valid, linked mobile device.
Parameters:
item (str): A podcast episode, library song, station_song, or store song.
A Google Music subscription is required to stream store songs... |
def bures_angle(rho0: Density, rho1: Density) -> float:
"""Return the Bures angle between mixed quantum states
Note: Bures angle cannot be calculated within the tensor backend.
"""
return np.arccos(np.sqrt(fidelity(rho0, rho1))) | Return the Bures angle between mixed quantum states
Note: Bures angle cannot be calculated within the tensor backend. |
def doane(data):
"""
Modified Doane modified
"""
from scipy.stats import skew
n = len(data)
sigma = np.sqrt(6. * (n - 2.) / (n + 1.) / (n + 3.))
return 1 + np.log2(n) + \
np.log2(1 + np.abs(skew(data)) / sigma) | Modified Doane modified |
def use_model_attr(attr):
"""Use the validator set on a separate attribute on the class."""
def use_model_validator(instance, attribute, value):
getattr(instance, attr)(instance, attribute, value)
return use_model_validator | Use the validator set on a separate attribute on the class. |
def anim_to_html(anim, fps=None, embed_frames=True, default_mode='loop'):
"""Generate HTML representation of the animation"""
if fps is None and hasattr(anim, '_interval'):
# Convert interval in ms to frames per second
fps = 1000. / anim._interval
plt.close(anim._fig)
if hasattr(anim, "... | Generate HTML representation of the animation |
def _uminumaxvmin(self,*args,**kwargs):
"""
NAME:
_uminumaxvmin
PURPOSE:
evaluate u_min, u_max, and v_min
INPUT:
Either:
a) R,vR,vT,z,vz
b) Orbit instance: initial condition used if that's it, orbit(t)
if there... | NAME:
_uminumaxvmin
PURPOSE:
evaluate u_min, u_max, and v_min
INPUT:
Either:
a) R,vR,vT,z,vz
b) Orbit instance: initial condition used if that's it, orbit(t)
if there is a time given as well
c= True/False; override... |
def make_response(self, rv, status=200, headers=None, mime='application/json'):
"""Create a response object using the :class:`flask.Response` class.
:param rv: Response value. If the value is not an instance
of :class:`werkzeug.wrappers.Response` it will be converted
into a Res... | Create a response object using the :class:`flask.Response` class.
:param rv: Response value. If the value is not an instance
of :class:`werkzeug.wrappers.Response` it will be converted
into a Response object.
:param status: specify the HTTP status code for this response.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.