positive stringlengths 100 30.3k | anchor stringlengths 1 15k |
|---|---|
def _GetPurgeMessage(most_recent_step, most_recent_wall_time, event_step,
event_wall_time, num_expired_scalars, num_expired_histos,
num_expired_comp_histos, num_expired_images,
num_expired_audio):
"""Return the string message associated with TensorBoard p... | Return the string message associated with TensorBoard purges. |
def set_exclusion_file(self, confound, exclusion_criteria, confound_stat='mean'):
"""
Excludes subjects given a certain exclusion criteria.
Parameters
----------
confound : str or list
string or list of confound name(s) from confound files
exclusi... | Excludes subjects given a certain exclusion criteria.
Parameters
----------
confound : str or list
string or list of confound name(s) from confound files
exclusion_criteria : str or list
for each confound, an exclusion_criteria should be expresse... |
def deepcopy(original_obj):
"""
Creates a deep copy of an object with no crossed referenced lists or dicts,
useful when loading from yaml as anchors generate those cross-referenced
dicts and lists
Args:
original_obj(object): Object to deep copy
Return:
object: deep copy of the ... | Creates a deep copy of an object with no crossed referenced lists or dicts,
useful when loading from yaml as anchors generate those cross-referenced
dicts and lists
Args:
original_obj(object): Object to deep copy
Return:
object: deep copy of the object |
def truncate(self, path, length, fh=None):
"Download existing path, truncate and reupload"
try:
f = self._getpath(path)
except JFS.JFSError:
raise OSError(errno.ENOENT, '')
if isinstance(f, (JFS.JFSFile, JFS.JFSFolder)) and f.is_deleted():
raise OSErro... | Download existing path, truncate and reupload |
def autoLayout(self):
"""
Automatically lays out the contents for this widget.
"""
try:
direction = self.currentSlide().scene().direction()
except AttributeError:
direction = QtGui.QBoxLayout.TopToBottom
size = self.size()
... | Automatically lays out the contents for this widget. |
def silence_warnings(*warnings):
"""
Context manager for silencing bokeh validation warnings.
"""
for warning in warnings:
silence(warning)
try:
yield
finally:
for warning in warnings:
silence(warning, False) | Context manager for silencing bokeh validation warnings. |
def list_deelgemeenten_by_gemeente(self, gemeente):
'''
List all `deelgemeenten` in a `gemeente`.
:param gemeente: The :class:`Gemeente` for which the \
`deelgemeenten` are wanted. Currently only Flanders is supported.
:rtype: A :class:`list` of :class:`Deelgemeente`.
... | List all `deelgemeenten` in a `gemeente`.
:param gemeente: The :class:`Gemeente` for which the \
`deelgemeenten` are wanted. Currently only Flanders is supported.
:rtype: A :class:`list` of :class:`Deelgemeente`. |
def bb_get_instr_max_width(basic_block):
"""Get maximum instruction mnemonic width
"""
asm_mnemonic_max_width = 0
for instr in basic_block:
if len(instr.mnemonic) > asm_mnemonic_max_width:
asm_mnemonic_max_width = len(instr.mnemonic)
return asm_mnemonic_max_width | Get maximum instruction mnemonic width |
def wrongstatus(data, sb, msb, lsb):
"""Check if the status bit and field bits are consistency. This Function
is used for checking BDS code versions.
"""
# status bit, most significant bit, least significant bit
status = int(data[sb-1])
value = bin2int(data[msb-1:lsb])
if not status:
... | Check if the status bit and field bits are consistency. This Function
is used for checking BDS code versions. |
def can_be_updated(cls, dist, latest_version):
"""Determine whether package can be updated or not."""
scheme = get_scheme('default')
name = dist.project_name
dependants = cls.get_dependants(name)
for dependant in dependants:
requires = dependant.requires()
... | Determine whether package can be updated or not. |
def create_method(self):
"""
Build the estimator method or function.
Returns
-------
:return : string
The built method as string.
"""
n_indents = 1 if self.target_language in ['java', 'js',
'php', 'rub... | Build the estimator method or function.
Returns
-------
:return : string
The built method as string. |
def get_current_selection(self, i=None):
"""Get the :class:`TaskFileInfo` for the file selected in the active tab
:param i: If None, returns selection of active tab. If 0, assetselection. If 1, shotselection
:type i:
:returns: The taskfile info in the currently active tab
:rtype... | Get the :class:`TaskFileInfo` for the file selected in the active tab
:param i: If None, returns selection of active tab. If 0, assetselection. If 1, shotselection
:type i:
:returns: The taskfile info in the currently active tab
:rtype: :class:`TaskFileInfo` | None
:raises: None |
def __trim_outputspeech(self, speech_output=None):
# type: (Union[str, None]) -> str
"""Trims the output speech if it already has the
<speak></speak> tag.
:param speech_output: the output speech sent back to user.
:type speech_output: str
:return: the trimmed output spee... | Trims the output speech if it already has the
<speak></speak> tag.
:param speech_output: the output speech sent back to user.
:type speech_output: str
:return: the trimmed output speech.
:rtype: Union[bool, None] |
def toggle_actions(actions, enable):
"""Enable/disable actions"""
if actions is not None:
for action in actions:
if action is not None:
action.setEnabled(enable) | Enable/disable actions |
def put_file(self, client, source_file):
"""
Put file on instance in default SSH directory.
"""
try:
file_name = os.path.basename(source_file)
ipa_utils.put_file(client, source_file, file_name)
except Exception as error:
raise IpaCloudException... | Put file on instance in default SSH directory. |
def wait_for_close(
raiden: 'RaidenService',
payment_network_id: PaymentNetworkID,
token_address: TokenAddress,
channel_ids: List[ChannelID],
retry_timeout: float,
) -> None:
"""Wait until all channels are closed.
Note:
This does not time out, use gevent.Timeout.... | Wait until all channels are closed.
Note:
This does not time out, use gevent.Timeout. |
def __getStationName(name, id):
"""Construct a staiion name."""
name = name.replace("Meetstation", "")
name = name.strip()
name += " (%s)" % id
return name | Construct a staiion name. |
def render_children(node: Node, **child_args):
"""Render node children"""
for xml_node in node.xml_node.children:
child = render(xml_node, **child_args)
node.add_child(child) | Render node children |
def capture_widget(widget, path=None):
"""Grab an image of a Qt widget
Args:
widget: The Qt Widget to capture
path (optional): The path to save to. If not provided - will return image data.
Returns:
If a path is provided, the image will be saved to it.
If not, the PNG buffe... | Grab an image of a Qt widget
Args:
widget: The Qt Widget to capture
path (optional): The path to save to. If not provided - will return image data.
Returns:
If a path is provided, the image will be saved to it.
If not, the PNG buffer will be returned. |
def ovsdb_server_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ovsdb_server = ET.SubElement(config, "ovsdb-server", xmlns="urn:brocade.com:mgmt:brocade-tunnels")
name = ET.SubElement(ovsdb_server, "name")
name.text = kwargs.pop('name')
... | Auto Generated Code |
def get_vlan_brief_output_vlan_vlan_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
output = ET.SubElement(get_vlan_brief, "output")
vlan = ET.SubElement(output, "... | Auto Generated Code |
def convert_url_to_download_info(self, url, project_name):
"""
See if a URL is a candidate for a download URL for a project (the URL
has typically been scraped from an HTML page).
If it is, a dictionary is returned with keys "name", "version",
"filename" and "url"; otherwise, No... | See if a URL is a candidate for a download URL for a project (the URL
has typically been scraped from an HTML page).
If it is, a dictionary is returned with keys "name", "version",
"filename" and "url"; otherwise, None is returned. |
def setup(self):
"""
Create mask list.
Consists of all tuples between which this filter accepts lines.
"""
# get start and end of the mask and set a start_limit
if not self.mask_source.start:
raise SystemExit("Can't parse format of %s. Is this a log file or "... | Create mask list.
Consists of all tuples between which this filter accepts lines. |
def no_exception(on_exception, logger=None):
"""
处理函数抛出异常的装饰器, ATT: on_exception必填
:param on_exception: 遇到异常时函数返回什么内容
"""
def decorator(function):
def wrapper(*args, **kwargs):
try:
result = function(*args, **kwargs)
except Exception, e:
... | 处理函数抛出异常的装饰器, ATT: on_exception必填
:param on_exception: 遇到异常时函数返回什么内容 |
def location(ip=None, key=None, field=None):
''' Get geolocation data for a given IP address
If field is specified, get specific field as text
Else get complete location data as JSON
'''
if field and (field not in field_list):
return 'Invalid field'
if field:
if ip:
... | Get geolocation data for a given IP address
If field is specified, get specific field as text
Else get complete location data as JSON |
def path(self, source, target):
"""
Find the path of id fields connecting two tables.
This is just a basic breadth-first-search. The relations file
should be small enough to not be a problem.
Returns:
list: (table, fieldname) pairs describing the path from
... | Find the path of id fields connecting two tables.
This is just a basic breadth-first-search. The relations file
should be small enough to not be a problem.
Returns:
list: (table, fieldname) pairs describing the path from
the source to target tables
Raises:
... |
def ping(**kwargs):
'''
Checks connections with the kubernetes API server.
Returns True if the connection can be established, False otherwise.
CLI Example:
salt '*' kubernetes.ping
'''
status = True
try:
nodes(**kwargs)
except CommandExecutionError:
status = Fals... | Checks connections with the kubernetes API server.
Returns True if the connection can be established, False otherwise.
CLI Example:
salt '*' kubernetes.ping |
def yearly_average(arr, dt):
"""Average a sub-yearly time-series over each year.
Resulting timeseries comprises one value for each year in which the
original array had valid data. Accounts for (i.e. ignores) masked values
in original data when computing the annual averages.
Parameters
-------... | Average a sub-yearly time-series over each year.
Resulting timeseries comprises one value for each year in which the
original array had valid data. Accounts for (i.e. ignores) masked values
in original data when computing the annual averages.
Parameters
----------
arr : xarray.DataArray
... |
def fromCSV(csvfile,out=None,fieldnames=None,fmtparams=None,conv_func={},
empty_to_None=[]):
"""Conversion from CSV to PyDbLite
csvfile : name of the CSV file in the file system
out : path for the new PyDbLite base in the file system
fieldnames : list of field names. If set to None, the fie... | Conversion from CSV to PyDbLite
csvfile : name of the CSV file in the file system
out : path for the new PyDbLite base in the file system
fieldnames : list of field names. If set to None, the field names must
be present in the first line of the CSV file
fmtparams : the format paramete... |
def update(self, capacity=values.unset, available=values.unset):
"""
Update the WorkerChannelInstance
:param unicode capacity: The total number of Tasks worker should handle for this TaskChannel type.
:param bool available: Toggle the availability of the WorkerChannel.
:returns... | Update the WorkerChannelInstance
:param unicode capacity: The total number of Tasks worker should handle for this TaskChannel type.
:param bool available: Toggle the availability of the WorkerChannel.
:returns: Updated WorkerChannelInstance
:rtype: twilio.rest.taskrouter.v1.workspace.w... |
def a(value):
"""Eq(a) -> Parser(a, a)
Returns a parser that parses a token that is equal to the value value.
"""
name = getattr(value, 'name', value)
return some(lambda t: t == value).named(u'(a "%s")' % (name,)) | Eq(a) -> Parser(a, a)
Returns a parser that parses a token that is equal to the value value. |
def ci_data(namespace, name, branch='master'):
'''Returns or starts the ci data collection process'''
with repository(namespace, name, branch) as (path, latest, cache):
if not path or not latest:
return {'build_success': NOT_FOUND, 'status': NOT_FOUND}
elif latest in cache:
... | Returns or starts the ci data collection process |
def strip_footer(ref_lines, section_title):
"""Remove footer title from references lines"""
pattern = ur'\(?\[?\d{0,4}\]?\)?\.?\s*%s\s*$' % re.escape(section_title)
re_footer = re.compile(pattern, re.UNICODE)
return [l for l in ref_lines if not re_footer.match(l)] | Remove footer title from references lines |
def to_csv(self, filename, stimuli=None, inhibitors=None, prepend=""):
"""
Writes the list of clampings to a CSV file
Parameters
----------
filename : str
Absolute path where to write the CSV file
stimuli : Optional[list[str]]
List of stimuli nam... | Writes the list of clampings to a CSV file
Parameters
----------
filename : str
Absolute path where to write the CSV file
stimuli : Optional[list[str]]
List of stimuli names. If given, stimuli are converted to {0,1} instead of {-1,1}.
inhibitors : Optio... |
def _from_fields(self, fields):
'''
Parse from generator. Raise StopIteration if the property could
not be read.
'''
return _np.dtype(self.dtype()).type(next(fields)) | Parse from generator. Raise StopIteration if the property could
not be read. |
def facetintervallookupone(table, key, start='start', stop='stop',
value=None, include_stop=False, strict=True):
"""
Construct a faceted interval lookup for the given table, returning at most
one result for each query.
If ``strict=True``, queries returning more than one r... | Construct a faceted interval lookup for the given table, returning at most
one result for each query.
If ``strict=True``, queries returning more than one result will
raise a `DuplicateKeyError`. If ``strict=False`` and there is
more than one result, the first result is returned. |
def _get_ami_dict(json_url):
"""Get ami from a web url.
Args:
region (str): AWS Region to find AMI ID.
Returns:
dict: Contents in dictionary format.
"""
LOG.info("Getting AMI from %s", json_url)
response = requests.get(json_url)
assert response.ok, "Error getting ami info ... | Get ami from a web url.
Args:
region (str): AWS Region to find AMI ID.
Returns:
dict: Contents in dictionary format. |
def entity_readme_content(self, entity_id, channel=None):
'''Get the readme for an entity.
@entity_id The id of the entity (i.e. charm, bundle).
@param channel Optional channel name.
'''
readme_url = self.entity_readme_url(entity_id, channel=channel)
response = self._get... | Get the readme for an entity.
@entity_id The id of the entity (i.e. charm, bundle).
@param channel Optional channel name. |
def _noise_model_program_header(noise_model):
"""
Generate the header for a pyquil Program that uses ``noise_model`` to overload noisy gates.
The program header consists of 3 sections:
- The ``DEFGATE`` statements that define the meaning of the newly introduced "noisy" gate
names.
... | Generate the header for a pyquil Program that uses ``noise_model`` to overload noisy gates.
The program header consists of 3 sections:
- The ``DEFGATE`` statements that define the meaning of the newly introduced "noisy" gate
names.
- The ``PRAGMA ADD-KRAUS`` statements to overload these n... |
def receipts():
'''
Return the results of a call to
``system_profiler -xml -detail full SPInstallHistoryDataType``
as a dictionary. Top-level keys of the dictionary
are the names of each set of install receipts, since
there can be multiple receipts with the same name.
Contents of each key a... | Return the results of a call to
``system_profiler -xml -detail full SPInstallHistoryDataType``
as a dictionary. Top-level keys of the dictionary
are the names of each set of install receipts, since
there can be multiple receipts with the same name.
Contents of each key are a list of dictionaries.
... |
def inv(self, q_data, max_iterations=100, tollerance=1e-5):
"""
Inverse Rosenblatt transformation.
If possible the transformation is done analytically. If not possible,
transformation is approximated using an algorithm that alternates
between Newton-Raphson and binary search.
... | Inverse Rosenblatt transformation.
If possible the transformation is done analytically. If not possible,
transformation is approximated using an algorithm that alternates
between Newton-Raphson and binary search.
Args:
q_data (numpy.ndarray):
Probabilities t... |
def boxcox(X):
"""
Gaussianize X using the Box-Cox transformation: [samples x phenotypes]
- each phentoype is brought to a positive schale, by first subtracting the minimum value and adding 1.
- Then each phenotype transformed by the boxcox transformation
"""
X_transformed = sp.zeros_like(X)
... | Gaussianize X using the Box-Cox transformation: [samples x phenotypes]
- each phentoype is brought to a positive schale, by first subtracting the minimum value and adding 1.
- Then each phenotype transformed by the boxcox transformation |
def topN(self, user, n=10, exclude_seen=True, items_pool=None):
"""
Recommend Top-N items for a user
Outputs the Top-N items according to score predicted by the model.
Can exclude the items for the user that were associated to her in the
training set, and can also recommend from only a subset of user-provide... | Recommend Top-N items for a user
Outputs the Top-N items according to score predicted by the model.
Can exclude the items for the user that were associated to her in the
training set, and can also recommend from only a subset of user-provided items.
Parameters
----------
user : obj
User for which to re... |
def mark_all(request):
"""
Marks notifications as either read or unread depending of POST parameters.
Takes ``action`` as POST data, it can either be ``read`` or ``unread``.
:param request: HTTP Request context.
:return: Response to mark_all action.
"""
action = request.POST.get('action', ... | Marks notifications as either read or unread depending of POST parameters.
Takes ``action`` as POST data, it can either be ``read`` or ``unread``.
:param request: HTTP Request context.
:return: Response to mark_all action. |
def wrap(cls, meth):
'''
Wraps a connection opening method in this class.
'''
async def inner(*args, **kwargs):
sock = await meth(*args, **kwargs)
return cls(sock)
return inner | Wraps a connection opening method in this class. |
def bleu_tokenize(string):
r"""Tokenize a string following the official BLEU implementation.
See https://github.com/moses-smt/mosesdecoder/"
"blob/master/scripts/generic/mteval-v14.pl#L954-L983
In our case, the input string is expected to be just one line
and no HTML entities de-escaping is needed.
... | r"""Tokenize a string following the official BLEU implementation.
See https://github.com/moses-smt/mosesdecoder/"
"blob/master/scripts/generic/mteval-v14.pl#L954-L983
In our case, the input string is expected to be just one line
and no HTML entities de-escaping is needed.
So we just tokenize on punc... |
def azureTables(self, *args, **kwargs):
"""
List Tables in an Account Managed by Auth
Retrieve a list of all tables in an account.
This method gives output: ``v1/azure-table-list-response.json#``
This method is ``stable``
"""
return self._makeApiCall(self.func... | List Tables in an Account Managed by Auth
Retrieve a list of all tables in an account.
This method gives output: ``v1/azure-table-list-response.json#``
This method is ``stable`` |
def load_images(input_dir, batch_shape):
"""Read png images from input directory in batches.
Args:
input_dir: input directory
batch_shape: shape of minibatch array, i.e. [batch_size, height, width, 3]
Yields:
filenames: list file names without path of each image
Length of this list could be le... | Read png images from input directory in batches.
Args:
input_dir: input directory
batch_shape: shape of minibatch array, i.e. [batch_size, height, width, 3]
Yields:
filenames: list file names without path of each image
Length of this list could be less than batch_size, in this case only
fi... |
def _set_domain_name(self, v, load=False):
"""
Setter method for domain_name, mapped from YANG variable /protocol/cfm/domain_name/domain_name (string)
If this variable is read-only (config: false) in the
source YANG file, then _set_domain_name is considered as a private
method. Backends looking to p... | Setter method for domain_name, mapped from YANG variable /protocol/cfm/domain_name/domain_name (string)
If this variable is read-only (config: false) in the
source YANG file, then _set_domain_name is considered as a private
method. Backends looking to populate this variable should
do so via calling this... |
def sample_cluster(sources, srcfilter, num_ses, param):
"""
Yields ruptures generated by a cluster of sources.
:param sources:
A sequence of sources of the same group
:param num_ses:
Number of stochastic event sets
:param param:
a dictionary of additional parameters includin... | Yields ruptures generated by a cluster of sources.
:param sources:
A sequence of sources of the same group
:param num_ses:
Number of stochastic event sets
:param param:
a dictionary of additional parameters including
ses_per_logic_tree_path
:yields:
dictionaries ... |
def listen(manifest, config, model_mock=False):
"""
IRC listening process.
"""
config['manifest'] = manifest
config['model_mock'] = model_mock
IRC = IrcBot(config)
try:
IRC.start()
except KeyboardInterrupt:
pass | IRC listening process. |
def make_ref(self, branch):
""" Make a branch on github
:param branch: Name of the branch to create
:return: Sha of the branch or self.ProxyError
"""
master_sha = self.get_ref(self.master_upstream)
if not isinstance(master_sha, str):
return self.ProxyError(
... | Make a branch on github
:param branch: Name of the branch to create
:return: Sha of the branch or self.ProxyError |
def load_data(self):
"""
Loads data from `scipy_data_fitting.Data.path` using [`numpy.genfromtxt`][1]
and returns a [`numpy.ndarray`][2].
Data is scaled according to `scipy_data_fitting.Data.scale`.
Arguments to [`numpy.genfromtxt`][1] are controlled
by `scipy_data_fitt... | Loads data from `scipy_data_fitting.Data.path` using [`numpy.genfromtxt`][1]
and returns a [`numpy.ndarray`][2].
Data is scaled according to `scipy_data_fitting.Data.scale`.
Arguments to [`numpy.genfromtxt`][1] are controlled
by `scipy_data_fitting.Data.genfromtxt_args`.
[1]: ... |
def find_databases(databases):
"""
define ribosomal proteins and location of curated databases
"""
# 16 ribosomal proteins in their expected order
proteins = ['L15', 'L18', 'L6', 'S8', 'L5', 'L24', 'L14',
'S17', 'L16', 'S3', 'L22', 'S19', 'L2', 'L4', 'L3', 'S10']
# curated databases
... | define ribosomal proteins and location of curated databases |
def store_object(self, obj_name, data, content_type=None, etag=None,
content_encoding=None, ttl=None, return_none=False,
headers=None, extra_info=None):
"""
Creates a new object in this container, and populates it with the given
data. A StorageObject reference to the uplo... | Creates a new object in this container, and populates it with the given
data. A StorageObject reference to the uploaded file will be returned,
unless 'return_none' is set to True.
The 'extra_info' parameter is included for backwards compatibility. It
is no longer used at all, and will n... |
def print_help_page(bot, file=sys.stdout):
"""print help page"""
def p(text):
print(text, file=file)
plugin = bot.get_plugin(Commands)
title = "Available Commands for {nick} at {host}".format(**bot.config)
p("=" * len(title))
p(title)
p("=" * len(title))
p('')
p('.. contents:... | print help page |
def is_open(table_name=None, table_key=None, gsi_name=None, gsi_key=None):
""" Checks whether the circuit breaker is open
:param table_name: Name of the table being checked
:param table_key: Configuration key for table
:param gsi_name: Name of the GSI being checked
:param gsi_key: Configuration key... | Checks whether the circuit breaker is open
:param table_name: Name of the table being checked
:param table_key: Configuration key for table
:param gsi_name: Name of the GSI being checked
:param gsi_key: Configuration key for the GSI
:returns: bool -- True if the circuit is open |
def validate(token):
"""Validate token and return auth context."""
token_url = TOKEN_URL_FMT.format(token=token)
headers = {
'x-auth-token': token,
'accept': 'application/json',
}
resp = requests.get(token_url, headers=headers)
if not resp.status_code == 200:
raise HTTPE... | Validate token and return auth context. |
def _set_catalog_view(self, session):
"""Sets the underlying catalog view to match current view"""
if self._catalog_view == FEDERATED:
try:
session.use_federated_catalog_view()
except AttributeError:
pass
else:
try:
... | Sets the underlying catalog view to match current view |
def filter_out_none_valued_keys(self, d):
# type: (typing.Dict[K, V]) -> typing.Dict[K, V]
"""Given a dict, returns a new dict with all the same key/values except
for keys that had values of None."""
new_d = {}
for k, v in d.items():
if v is not None:
... | Given a dict, returns a new dict with all the same key/values except
for keys that had values of None. |
def flatten_hierarchical_dict(original_dict, separator='.', max_recursion_depth=None):
"""Flatten a dict.
Inputs
------
original_dict: dict
the dictionary to flatten
separator: string, optional
the separator item in the keys of the flattened dictionary
max_recursion_depth: posit... | Flatten a dict.
Inputs
------
original_dict: dict
the dictionary to flatten
separator: string, optional
the separator item in the keys of the flattened dictionary
max_recursion_depth: positive integer, optional
the number of recursions to be done. None is infinte.
Outpu... |
def get_rule_id_from_name(self, name):
"""Finds the rule that matches name.
SoftLayer_Virtual_PlacementGroup_Rule.getAllObjects doesn't support objectFilters.
"""
results = self.client.call('SoftLayer_Virtual_PlacementGroup_Rule', 'getAllObjects')
return [result['id'] for result... | Finds the rule that matches name.
SoftLayer_Virtual_PlacementGroup_Rule.getAllObjects doesn't support objectFilters. |
def decr(self, key, value, noreply=False):
"""
The memcached "decr" command.
Args:
key: str, see class docs for details.
value: int, the amount by which to increment the value.
noreply: optional bool, False to wait for the reply (the default).
Returns:
... | The memcached "decr" command.
Args:
key: str, see class docs for details.
value: int, the amount by which to increment the value.
noreply: optional bool, False to wait for the reply (the default).
Returns:
If noreply is True, always returns None. Otherwise retur... |
def setTreeDoc(self, tree):
"""update all nodes under the tree to point to the right
document """
if tree is None: tree__o = None
else: tree__o = tree._o
libxml2mod.xmlSetTreeDoc(tree__o, self._o) | update all nodes under the tree to point to the right
document |
def _rename_duplicate_tabs(self, current, name, path):
"""
Rename tabs whose title is the same as the name
"""
for i in range(self.count()):
if self.widget(i)._tab_name == name and self.widget(i) != current:
file_path = self.widget(i).file.path
... | Rename tabs whose title is the same as the name |
def chhome(name, home, persist=False):
'''
Set a new home directory for an existing user
name
Username to modify
home
New home directory to set
persist : False
Set to ``True`` to prevent configuration files in the new home
directory from being overwritten by the fi... | Set a new home directory for an existing user
name
Username to modify
home
New home directory to set
persist : False
Set to ``True`` to prevent configuration files in the new home
directory from being overwritten by the files from the skeleton
directory.
CLI E... |
def load_fasta_file_as_dict_of_seqs(filename):
"""Load a FASTA file and return the sequences as a dict of {ID: sequence string}
Args:
filename (str): Path to the FASTA file to load
Returns:
dict: Dictionary of IDs to their sequence strings
"""
results = {}
records = load_fast... | Load a FASTA file and return the sequences as a dict of {ID: sequence string}
Args:
filename (str): Path to the FASTA file to load
Returns:
dict: Dictionary of IDs to their sequence strings |
def OnUpdate(self, event):
"""Updates the toolbar states"""
attributes = event.attr
self._update_font(attributes["textfont"])
self._update_pointsize(attributes["pointsize"])
self._update_font_weight(attributes["fontweight"])
self._update_font_style(attributes["fontstyle... | Updates the toolbar states |
def adjoint(self):
"""Adjoint of this operator."""
if not self.is_linear:
raise NotImplementedError('this operator is not linear and '
'thus has no adjoint')
forward_op = self
class ResizingOperatorAdjoint(ResizingOperatorBase):
... | Adjoint of this operator. |
def try_int(s, default=None, minimum=None):
""" Try parsing a string into an integer.
If None is passed, default is returned.
On failure, InvalidNumber is raised.
"""
if not s:
return default
try:
val = int(s)
except (TypeError, ValueError):
raise InvalidNumbe... | Try parsing a string into an integer.
If None is passed, default is returned.
On failure, InvalidNumber is raised. |
def setup_errors(app, error_template="error.html"):
"""Add a handler for each of the available HTTP error responses."""
def error_handler(error):
if isinstance(error, HTTPException):
description = error.get_description(request.environ)
code = error.code
name = error.n... | Add a handler for each of the available HTTP error responses. |
def item_wegobject_adapter(obj, request):
"""
Adapter for rendering a list of
:class:`crabpy.gateway.Wegobject` to json.
"""
return {
'id': obj.id,
'aard': {
'id': obj.aard.id,
'naam': obj.aard.naam,
'definitie': obj.aard.definitie
},
... | Adapter for rendering a list of
:class:`crabpy.gateway.Wegobject` to json. |
def default(session):
"""Default unit test session.
This is intended to be run **without** an interpreter set, so
that the current ``python`` (on the ``PATH``) or the version of
Python corresponding to the ``nox`` binary the ``PATH`` can
run the tests.
"""
# Install all test dependencies, t... | Default unit test session.
This is intended to be run **without** an interpreter set, so
that the current ``python`` (on the ``PATH``) or the version of
Python corresponding to the ``nox`` binary the ``PATH`` can
run the tests. |
def get_labels(self, depth=None):
"""
Returns a list with a copy of the labels in this cell.
Parameters
----------
depth : integer or ``None``
If not ``None``, defines from how many reference levels to
retrieve labels from.
Returns
------... | Returns a list with a copy of the labels in this cell.
Parameters
----------
depth : integer or ``None``
If not ``None``, defines from how many reference levels to
retrieve labels from.
Returns
-------
out : list of ``Label``
List con... |
def from_epsg(self, epsg_code):
"""
Loads self.prj by epsg_code.
If prjtext not found returns False.
"""
self.epsg_code = epsg_code
assert isinstance(self.epsg_code, int)
cur = self.conn.cursor()
cur.execute("SELECT prjtext FROM prj_epsg WHERE epsg_code = ... | Loads self.prj by epsg_code.
If prjtext not found returns False. |
async def stop_bridges(self):
"""Stop all sleep tasks to allow bridges to end."""
for task in self.sleep_tasks:
task.cancel()
for bridge in self.bridges:
bridge.stop() | Stop all sleep tasks to allow bridges to end. |
def get_strategy_types():
"""Get a list of all :class:`Strategy` subclasses."""
def get_subtypes(type_):
subtypes = type_.__subclasses__()
for subtype in subtypes:
subtypes.extend(get_subtypes(subtype))
return subtypes
return get_subtypes(Strategy) | Get a list of all :class:`Strategy` subclasses. |
def personas(text, cloud=None, batch=False, api_key=None, version=None, **kwargs):
"""
Given input text, returns the authors likelihood of being 16 different personality
types in a dict.
Example usage:
.. code-block:: python
>>> text = "I love going out with my friends"
>>> entities... | Given input text, returns the authors likelihood of being 16 different personality
types in a dict.
Example usage:
.. code-block:: python
>>> text = "I love going out with my friends"
>>> entities = indicoio.personas(text)
{'architect': 0.2191890478134155, 'logician': 0.0158474326133... |
def args_str(self):
"""
Return an args string for the repr.
"""
matched = [str(m) for m in self._matchers[:self._position]]
unmatched = [str(m) for m in self._matchers[self._position:]]
return 'matched=[{}], unmatched=[{}]'.format(
', '.join(matched), ', '.joi... | Return an args string for the repr. |
def build(self, targets: Iterable[str]) -> Iterable[str]:
"""
Shell out to buck to build the targets, then yield the paths to the
link trees.
"""
return generate_source_directories(
targets, build=self._build, prompt=self._prompt
) | Shell out to buck to build the targets, then yield the paths to the
link trees. |
def createList(self,args):
"""
This is an internal method to create the list of input files (or directories)
contained in the provided directory or directories.
"""
resultList = []
if len(args.path) == 1 and os.path.isdir(args.path[0]):
resultList = [os.path.j... | This is an internal method to create the list of input files (or directories)
contained in the provided directory or directories. |
def set_rubric(self, assessment_id):
"""Sets the rubric expressed as another assessment.
arg: assessment_id (osid.id.Id): the assessment ``Id``
raise: InvalidArgument - ``assessment_id`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
raise: NullArgument... | Sets the rubric expressed as another assessment.
arg: assessment_id (osid.id.Id): the assessment ``Id``
raise: InvalidArgument - ``assessment_id`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
raise: NullArgument - ``assessment_id`` is ``null``
*compli... |
def get_undecorated_callback(self):
""" Return the callback. If the callback is a decorated function, try to
recover the original function. """
func = self.callback
func = getattr(func, '__func__' if py3k else 'im_func', func)
closure_attr = '__closure__' if py3k else 'func_c... | Return the callback. If the callback is a decorated function, try to
recover the original function. |
def xml(self, attribs = None,elements = None, skipchildren = False):
"""See :meth:`AbstractElement.xml`"""
if not attribs: attribs = {}
E = ElementMaker(namespace="http://ilk.uvt.nl/folia",nsmap={None: "http://ilk.uvt.nl/folia", 'xml' : "http://www.w3.org/XML/1998/namespace"})
e = super(... | See :meth:`AbstractElement.xml` |
def _step(self, theme, direction):
"""
Traverse the list in the given direction and return the next theme
"""
if not self.themes:
self.reload()
# Try to find the starting index
key = (theme.source, theme.name)
for i, val in enumerate(self.themes):
... | Traverse the list in the given direction and return the next theme |
def post(self, endpoint, json=None, params=None, **kwargs):
"""POST to DHIS2
:param endpoint: DHIS2 API endpoint
:param json: HTTP payload
:param params: HTTP parameters
:return: requests.Response object
"""
json = kwargs['data'] if 'data' in kwargs else json
... | POST to DHIS2
:param endpoint: DHIS2 API endpoint
:param json: HTTP payload
:param params: HTTP parameters
:return: requests.Response object |
def tz(self):
"""Time zone information."""
if self.timezone is None:
return None
try:
tz = pytz.timezone(self.timezone)
return tz
except pytz.UnknownTimeZoneError:
raise AstralError("Unknown timezone '%s'" % self.timezone) | Time zone information. |
def compileGLShader(self, pchShaderName, pchVertexShader, pchFragmentShader):
"""
Purpose: Compiles a GL shader program and returns the handle. Returns 0 if
the shader couldn't be compiled for some reason.
"""
unProgramID = glCreateProgram()
nSceneVertexShader = ... | Purpose: Compiles a GL shader program and returns the handle. Returns 0 if
the shader couldn't be compiled for some reason. |
def change (properties, feature, value = None):
""" Returns a modified version of properties with all values of the
given feature replaced by the given value.
If 'value' is None the feature will be removed.
"""
assert is_iterable_typed(properties, basestring)
assert isinstance(feature, b... | Returns a modified version of properties with all values of the
given feature replaced by the given value.
If 'value' is None the feature will be removed. |
async def on_raw_433(self, message):
""" Nickname in use. """
if not self.registered:
self._registration_attempts += 1
# Attempt to set new nickname.
if self._attempt_nicknames:
await self.set_nickname(self._attempt_nicknames.pop(0))
else:
... | Nickname in use. |
def _get_table_as_string(self):
"""Get table as SOFT formated string."""
tablelist = []
tablelist.append("!%s_table_begin" % self.geotype.lower())
tablelist.append("\t".join(self.table.columns))
for idx, row in self.table.iterrows():
tablelist.append("\t".join(map(str... | Get table as SOFT formated string. |
def visit(self, node):
"""Visit a node.
This method is largely modelled after the ast.NodeTransformer class.
Args:
node: The node to visit.
Returns:
A tuple of the primal and adjoint, each of which is a node or a list of
nodes.
"""
method = 'visit_' + node.__class__.__name__... | Visit a node.
This method is largely modelled after the ast.NodeTransformer class.
Args:
node: The node to visit.
Returns:
A tuple of the primal and adjoint, each of which is a node or a list of
nodes. |
def patch(self, operation, path, value, custom_headers=None, timeout=-1):
"""Uses the PATCH to update a resource.
Only one operation can be performed in each PATCH call.
Args
operation: Patch operation
path: Path
value: Value
timeout: Timeout in ... | Uses the PATCH to update a resource.
Only one operation can be performed in each PATCH call.
Args
operation: Patch operation
path: Path
value: Value
timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operatio... |
def cmd(send, msg, args):
"""Corrects a previous message.
Syntax: {command}/<msg>/<replacement>/<ig|nick>
"""
if not msg:
send("Invalid Syntax.")
return
char = msg[0]
msg = [x.replace(r'\/', '/') for x in re.split(r'(?<!\\)\%s' % char, msg[1:], maxsplit=2)]
# fix for people... | Corrects a previous message.
Syntax: {command}/<msg>/<replacement>/<ig|nick> |
def show_linkinfo_output_show_link_info_linkinfo_isl_linkinfo_isllink_destdomain(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_linkinfo = ET.Element("show_linkinfo")
config = show_linkinfo
output = ET.SubElement(show_linkinfo, "output")
... | Auto Generated Code |
def popvalue(self, k, d=None):
"""
D.popvalue(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised
"""
if k not in self._col_dict:
return d
value = self._col_dict.pop(k)... | D.popvalue(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised |
def lastNode(class_, hot_map):
''' Return the very last node (recursively) in the hot map. '''
children = hot_map[-1][2]
if children:
return class_.lastNode(children)
else:
return hot_map[-1][1] | Return the very last node (recursively) in the hot map. |
def make_interface_child(device_name, interface_name, parent_name):
'''
.. versionadded:: 2019.2.0
Set an interface as part of a LAG.
device_name
The name of the device, e.g., ``edge_router``.
interface_name
The name of the interface to be attached to LAG, e.g., ``xe-1/0/2``.
... | .. versionadded:: 2019.2.0
Set an interface as part of a LAG.
device_name
The name of the device, e.g., ``edge_router``.
interface_name
The name of the interface to be attached to LAG, e.g., ``xe-1/0/2``.
parent_name
The name of the LAG interface, e.g., ``ae13``.
CLI Exa... |
def tea_decipher(v, key):
"""
Tiny Decryption Algorithm decription (TEA)
See https://en.wikipedia.org/wiki/Tiny_Encryption_Algorithm
"""
DELTA = 0x9e3779b9
n = len(v)
rounds = 6 + 52//n
sum = (rounds*DELTA)
y = v[0]
while sum != 0:
e = (sum >> 2) & 3
for p in rang... | Tiny Decryption Algorithm decription (TEA)
See https://en.wikipedia.org/wiki/Tiny_Encryption_Algorithm |
def labels():
"""
Path to labels file
"""
datapath = path.join(path.dirname(path.realpath(__file__)), path.pardir)
datapath = path.join(datapath, '../gzoo_data', 'train_solution.csv')
return path.normpath(datapath) | Path to labels file |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.