code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def list_math_substraction_number(a, b):
"""!
@brief Calculates subtraction between list and number.
@details Each element from list 'a' is subtracted by number 'b'.
@param[in] a (list): List of elements that supports mathematical subtraction.
@param[in] b (list): Value that supports math... | !
@brief Calculates subtraction between list and number.
@details Each element from list 'a' is subtracted by number 'b'.
@param[in] a (list): List of elements that supports mathematical subtraction.
@param[in] b (list): Value that supports mathematical subtraction.
@return (list) R... |
def house_explosions():
"""
Data from http://indexed.blogspot.com/2007/12/meltdown-indeed.html
"""
chart = PieChart2D(int(settings.width * 1.7), settings.height)
chart.add_data([10, 10, 30, 200])
chart.set_pie_labels([
'Budding Chemists',
'Propane issues',
'Meth Labs',
... | Data from http://indexed.blogspot.com/2007/12/meltdown-indeed.html |
def load_yaml_file(yaml_file):
""" load yaml file and check file content format
"""
with io.open(yaml_file, 'r', encoding='utf-8') as stream:
yaml_content = yaml.load(stream)
_check_format(yaml_file, yaml_content)
return yaml_content | load yaml file and check file content format |
def _get_table_rows(parent_table, table_name, row_name):
"""
Inconsistent behavior:
{'TABLE_intf': [{'ROW_intf': {
vs
{'TABLE_mac_address': {'ROW_mac_address': [{
vs
{'TABLE_vrf': {'ROW_vrf': {'TABLE_adj': {'ROW_adj': {
"""
if parent_table is None:... | Inconsistent behavior:
{'TABLE_intf': [{'ROW_intf': {
vs
{'TABLE_mac_address': {'ROW_mac_address': [{
vs
{'TABLE_vrf': {'ROW_vrf': {'TABLE_adj': {'ROW_adj': { |
def get_doc(self):
"""Get the proposed object's docstring.
Returns None if it can not be get.
"""
if not self.pyname:
return None
pyobject = self.pyname.get_object()
if not hasattr(pyobject, 'get_doc'):
return None
return self.pyname.get_o... | Get the proposed object's docstring.
Returns None if it can not be get. |
def plot_kmf(df,
condition_col,
censor_col,
survival_col,
strata_col=None,
threshold=None,
title=None,
xlabel=None,
ylabel=None,
ax=None,
with_condition_color="#B38600",
no_cond... | Plot survival curves by splitting the dataset into two groups based on
condition_col. Report results for a log-rank test (if two groups are plotted)
or CoxPH survival analysis (if >2 groups) for association with survival.
Regarding definition of groups:
If condition_col is numeric, values are split... |
def OnExitSelectionMode(self, event):
"""Event handler for leaving selection mode, enables cell edits"""
self.grid.sel_mode_cursor = None
self.grid.EnableDragGridSize(True)
self.grid.EnableEditing(True) | Event handler for leaving selection mode, enables cell edits |
def _convert_property_type(value):
"""Converts the string value in a boolean, integer or string
:param value: string value
:returns: boolean, integer or string value
"""
if value in ('true', 'True'):
return True
elif value in ('false', 'False'):
r... | Converts the string value in a boolean, integer or string
:param value: string value
:returns: boolean, integer or string value |
def get_file_to_stream(
self, share_name, directory_name, file_name, stream,
start_range=None, end_range=None, validate_content=False,
progress_callback=None, max_connections=2, timeout=None):
'''
Downloads a file to a stream, with automatic chunking and progress
notifica... | Downloads a file to a stream, with automatic chunking and progress
notifications. Returns an instance of :class:`File` with properties
and metadata.
:param str share_name:
Name of existing share.
:param str directory_name:
The path to the directory.
:para... |
def InitPmf(self, values):
"""Initializes with a Pmf.
values: Pmf object
"""
for value, prob in values.Items():
self.Set(value, prob) | Initializes with a Pmf.
values: Pmf object |
def reparentNamespaces(self):
'''
Helper method for :func:`~exhale.graph.ExhaleRoot.reparentAll`. Adds nested
namespaces as children to the relevant namespace ExhaleNode. If a node in
``self.namespaces`` is added as a child to a different namespace node, it is
removed from the ... | Helper method for :func:`~exhale.graph.ExhaleRoot.reparentAll`. Adds nested
namespaces as children to the relevant namespace ExhaleNode. If a node in
``self.namespaces`` is added as a child to a different namespace node, it is
removed from the ``self.namespaces`` list. Because these are remov... |
def visit_pass(self, node, parent):
"""visit a Pass node by returning a fresh instance of it"""
return nodes.Pass(node.lineno, node.col_offset, parent) | visit a Pass node by returning a fresh instance of it |
def _insert_plain_text(self, cursor, text):
""" Inserts plain text using the specified cursor, processing ANSI codes
if enabled.
"""
cursor.beginEditBlock()
if self.ansi_codes:
for substring in self._ansi_processor.split_string(text):
for act in se... | Inserts plain text using the specified cursor, processing ANSI codes
if enabled. |
def fill_symbolic(self):
"""
Fill the class with constrained symbolic values.
"""
self.wYear = self.state.solver.BVS('cur_year', 16, key=('api', 'GetLocalTime', 'cur_year'))
self.wMonth = self.state.solver.BVS('cur_month', 16, key=('api', 'GetLocalTime', 'cur_month'))
sel... | Fill the class with constrained symbolic values. |
def patch_module_function(module, target, aspect, force_name=None, bag=BrokenBag, **options):
"""
Low-level patcher for one function from a specified module.
.. warning:: You should not use this directly.
:returns: An :obj:`aspectlib.Rollback` object.
"""
logdebug("patch_module_function (modul... | Low-level patcher for one function from a specified module.
.. warning:: You should not use this directly.
:returns: An :obj:`aspectlib.Rollback` object. |
def read_var_uint64(self):
"""Reads a varint from the stream, interprets this varint
as an unsigned, 64-bit integer, and returns the integer.
"""
i = self._read_varint_helper()
if not 0 <= i <= wire_format.UINT64_MAX:
raise errors.DecodeError('Value out of range for u... | Reads a varint from the stream, interprets this varint
as an unsigned, 64-bit integer, and returns the integer. |
def send_media_group(self, chat_id, media, disable_notification=None, reply_to_message_id=None):
"""
send a group of photos or videos as an album. On success, an array of the sent Messages is returned.
:param chat_id:
:param media:
:param disable_notification:
:param repl... | send a group of photos or videos as an album. On success, an array of the sent Messages is returned.
:param chat_id:
:param media:
:param disable_notification:
:param reply_to_message_id:
:return: |
def title_case(string):
"""
Converts a string to title case. For example::
title_case('one_two_three') -> 'One Two Three'
"""
if not string:
return string
string = string.replace('_', ' ').replace('-', ' ')
parts = de_camel(string, ' ', _lowercase=False).strip().split(' ')
r... | Converts a string to title case. For example::
title_case('one_two_three') -> 'One Two Three' |
def copyNodeList(self, node):
"""Do a recursive copy of the node list. """
if node is None: node__o = None
else: node__o = node._o
ret = libxml2mod.xmlDocCopyNodeList(self._o, node__o)
if ret is None:raise treeError('xmlDocCopyNodeList() failed')
__tmp = xmlNode(_obj=ret)... | Do a recursive copy of the node list. |
def drop(self, labels, errors='raise'):
"""
Make new Index with passed list of labels deleted.
Parameters
----------
labels : array-like
errors : {'ignore', 'raise'}, default 'raise'
If 'ignore', suppress error and existing labels are dropped.
Return... | Make new Index with passed list of labels deleted.
Parameters
----------
labels : array-like
errors : {'ignore', 'raise'}, default 'raise'
If 'ignore', suppress error and existing labels are dropped.
Returns
-------
dropped : Index
Raises
... |
def to_binary_string(obj, encoding=None):
"""Convert `obj` to binary string (bytes in Python 3, str in Python 2)"""
if PY2:
# Python 2
if encoding is None:
return str(obj)
else:
return obj.encode(encoding)
else:
# Python 3
return byte... | Convert `obj` to binary string (bytes in Python 3, str in Python 2) |
def _parse_dtype(self, space):
"""Get a tensor dtype from a OpenAI Gym space.
Args:
space: Gym space.
Raises:
NotImplementedError: For spaces other than Box and Discrete.
Returns:
TensorFlow data type.
"""
if isinstance(space, gym.spaces.Discrete):
return tf.int32
... | Get a tensor dtype from a OpenAI Gym space.
Args:
space: Gym space.
Raises:
NotImplementedError: For spaces other than Box and Discrete.
Returns:
TensorFlow data type. |
def save(self, annot=None, output_path=None):
"""Saves the collage to disk as an image.
Parameters
-----------
annot : str
text to annotate the figure with a super title
output_path : str
path to save the figure to.
Note: any spaces in the f... | Saves the collage to disk as an image.
Parameters
-----------
annot : str
text to annotate the figure with a super title
output_path : str
path to save the figure to.
Note: any spaces in the filename will be replace with ``_`` |
def register(self, name, content, description=None):
"""
Register a new document.
:param content: Content of this document. Jinja and rst are supported.
:type content: str
:param name: Unique name of the document for documentation purposes.
:param description: Short desc... | Register a new document.
:param content: Content of this document. Jinja and rst are supported.
:type content: str
:param name: Unique name of the document for documentation purposes.
:param description: Short description of this document |
def asyncPipeRename(context=None, _INPUT=None, conf=None, **kwargs):
"""An operator that asynchronously renames or copies fields in the input
source. Not loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : asyncPipe like object (twisted Deferred iterable of items)
conf... | An operator that asynchronously renames or copies fields in the input
source. Not loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : asyncPipe like object (twisted Deferred iterable of items)
conf : {
'RULE': [
{
'op': {'value': 'rename... |
def easter(year):
"""
This method was ported from the work done by GM Arts,
on top of the algorithm by Claus Tondering, which was
based in part on the algorithm of Ouding (1940), as
quoted in "Explanatory Supplement to the Astronomical
Almanac", P. Kenneth Seidelmann, editor.
More about th... | This method was ported from the work done by GM Arts,
on top of the algorithm by Claus Tondering, which was
based in part on the algorithm of Ouding (1940), as
quoted in "Explanatory Supplement to the Astronomical
Almanac", P. Kenneth Seidelmann, editor.
More about the algorithm may be found at:
... |
def _update(dashboard, profile):
'''Update a specific dashboard.'''
payload = {
'dashboard': dashboard,
'overwrite': True
}
request_url = "{0}/api/dashboards/db".format(profile.get('grafana_url'))
response = requests.post(
request_url,
headers={
"Authoriza... | Update a specific dashboard. |
def command(self, payload):
"""
Send a command to i3. See the `list of commands
<http://i3wm.org/docs/userguide.html#_list_of_commands>`_ in the user
guide for available commands. Pass the text of the command to execute
as the first arguments. This is essentially the same as usin... | Send a command to i3. See the `list of commands
<http://i3wm.org/docs/userguide.html#_list_of_commands>`_ in the user
guide for available commands. Pass the text of the command to execute
as the first arguments. This is essentially the same as using
``i3-msg`` or an ``exec`` block in you... |
def compile_assets(self):
"""
Compile the front end assets
"""
try:
# Move into client dir
curdir = os.path.abspath(os.curdir)
client_path = os.path.join(os.path.dirname(__file__), 'longclaw', 'client')
os.chdir(client_path)
sub... | Compile the front end assets |
def _await_flow(self, client, flow_id):
"""Awaits flow completion.
Args:
client: GRR Client object in which to await the flow.
flow_id: string containing ID of flow to await.
Raises:
DFTimewolfError: if flow error encountered.
"""
# Wait for the flow to finish
print('{0:s}: W... | Awaits flow completion.
Args:
client: GRR Client object in which to await the flow.
flow_id: string containing ID of flow to await.
Raises:
DFTimewolfError: if flow error encountered. |
def T1(word):
'''Insert a syllable boundary in front of every CV sequence.'''
# split consonants and vowels: 'balloon' -> ['b', 'a', 'll', 'oo', 'n']
WORD = [i for i in re.split(r'([ieaouäöy]+)', word, flags=FLAGS) if i]
# keep track of which sub-rules are applying
sub_rules = set()
# a count ... | Insert a syllable boundary in front of every CV sequence. |
def _attributes(note, data):
"""
attribute of the note
:param note: note object
:param data:
:return:
"""
# attribute of the note: the link to the website
note_attribute = EvernoteMgr.set_note_attribute(data)
if note_attribute:
note.att... | attribute of the note
:param note: note object
:param data:
:return: |
def postinit(self, exc=None, cause=None):
"""Do some setup after initialisation.
:param exc: What is being raised.
:type exc: NodeNG or None
:param cause: The exception being used to raise this one.
:type cause: NodeNG or None
"""
self.exc = exc
self.cau... | Do some setup after initialisation.
:param exc: What is being raised.
:type exc: NodeNG or None
:param cause: The exception being used to raise this one.
:type cause: NodeNG or None |
def has_bad_headers(self):
"""
Checks for bad headers i.e. newlines in subject, sender or recipients.
RFC5322 allows multiline CRLF with trailing whitespace (FWS) in headers
"""
headers = [self.sender, self.reply_to] + self.recipients
for header in headers:
if... | Checks for bad headers i.e. newlines in subject, sender or recipients.
RFC5322 allows multiline CRLF with trailing whitespace (FWS) in headers |
def annotation_rows(prefix, annotations):
"""
Helper function to extract N: and C: rows from annotations and pad their values
"""
ncol = len(annotations['Column Name'])
return {name.replace(prefix, '', 1) : values + [''] * (ncol - len(values))
for name, values in annotations.items() if n... | Helper function to extract N: and C: rows from annotations and pad their values |
def chapters(self, title):
"""
Get a list of chapters for a visual novel. Keep in mind, this can be slow. I've certainly tried to make it as fast as possible, but it's still pulling text out of a webpage.
:param str title: The title of the novel you want chapters from
:return OrderedDic... | Get a list of chapters for a visual novel. Keep in mind, this can be slow. I've certainly tried to make it as fast as possible, but it's still pulling text out of a webpage.
:param str title: The title of the novel you want chapters from
:return OrderedDict: An OrderedDict which contains the chapters f... |
def handle_input(self):
"""Sends differences in the device state to the MicroBitPad
as events."""
difference = self.check_state()
if not difference:
return
self.events = []
self.handle_new_events(difference)
self.update_timeval()
self.events.ap... | Sends differences in the device state to the MicroBitPad
as events. |
def to_safe_str(s):
"""
converts some (tr) non-ascii chars to ascii counterparts,
then return the result as lowercase
"""
# TODO: This is insufficient as it doesn't do anything for other non-ascii chars
return re.sub(r'[^0-9a-zA-Z]+', '_', s.strip().replace(u'ğ', 'g').replace(u'ö', 'o').replace(... | converts some (tr) non-ascii chars to ascii counterparts,
then return the result as lowercase |
def remove_label(self, to_remove):
"""
Remove a label from the document. (-> rewrite the label file)
"""
if to_remove not in self.labels:
return
labels = self.labels
labels.remove(to_remove)
with self.fs.open(self.fs.join(self.path, self.LABEL_FILE), '... | Remove a label from the document. (-> rewrite the label file) |
def jsd_df_to_2d(jsd_df):
"""Transform a tall JSD dataframe to a square matrix of mean JSDs
Parameters
----------
jsd_df : pandas.DataFrame
A (n_features, n_phenotypes^2) dataframe of the JSD between each
feature between and within phenotypes
Returns
-------
jsd_2d : pandas... | Transform a tall JSD dataframe to a square matrix of mean JSDs
Parameters
----------
jsd_df : pandas.DataFrame
A (n_features, n_phenotypes^2) dataframe of the JSD between each
feature between and within phenotypes
Returns
-------
jsd_2d : pandas.DataFrame
A (n_phenotype... |
def repositories(self):
"""Get dependencies by repositories
"""
if self.repo == "sbo":
self.sbo_case_insensitive()
self.find_pkg = sbo_search_pkg(self.name)
if self.find_pkg:
self.dependencies_list = Requires(self.flag).sbo(self.name)
e... | Get dependencies by repositories |
def factor_schur(z, DPhival, G, A):
M, N = G.shape
P, N = A.shape
"""Multiplier for inequality constraints"""
l = z[N+P:N+P+M]
"""Slacks"""
s = z[N+P+M:]
"""Sigma matrix"""
SIG = diags(l/s, 0)
"""Augmented Jacobian"""
H = DPhival + mydot(G.T, mydot(SIG, G))
"""Factor H"""... | Multiplier for inequality constraints |
def configure_analytics_yandex(self, ident, params=None):
"""Configure Yandex Metrika analytics counter.
:param str|unicode ident: Metrika counter ID.
:param dict params: Additional params.
"""
params = params or {}
data = {
'type': 'Yandex',
'... | Configure Yandex Metrika analytics counter.
:param str|unicode ident: Metrika counter ID.
:param dict params: Additional params. |
def getkeystroke(self, scr, vs=None):
'Get keystroke and display it on status bar.'
k = None
try:
k = scr.get_wch()
self.drawRightStatus(scr, vs or self.sheets[0]) # continue to display progress %
except curses.error:
return '' # curses timeout
... | Get keystroke and display it on status bar. |
def render_it(self, *args, **kwargs):
'''
Render without userinfo.
fun(kind, num)
fun(kind, num, with_tag = val1)
fun(kind, num, with_tag = val1, glyph = val2)
'''
kind = kwargs.get('kind', args[0])
num = kwargs.get('num', args[1] if len(args) > 1 else 6)
... | Render without userinfo.
fun(kind, num)
fun(kind, num, with_tag = val1)
fun(kind, num, with_tag = val1, glyph = val2) |
def _make_class_unpicklable(cls):
"""Make the given class un-picklable."""
def _break_on_call_reduce(self, protocol=None):
raise TypeError('%r cannot be pickled' % self)
cls.__reduce_ex__ = _break_on_call_reduce
cls.__module__ = '<unknown>' | Make the given class un-picklable. |
def ASR(value, amount, width):
"""
The ARM ASR (arithmetic shift right) operation.
:param value: Value to shift
:type value: int or long or BitVec
:param int amount: How many bits to shift it.
:param int width: Width of the value
:return: Resultant value
:rtype int or BitVec
"""
... | The ARM ASR (arithmetic shift right) operation.
:param value: Value to shift
:type value: int or long or BitVec
:param int amount: How many bits to shift it.
:param int width: Width of the value
:return: Resultant value
:rtype int or BitVec |
def generate_search_space(code_dir):
"""Generate search space from Python source code.
Return a serializable search space object.
code_dir: directory path of source files (str)
"""
search_space = {}
if code_dir.endswith(slash):
code_dir = code_dir[:-1]
for subdir, _, files in o... | Generate search space from Python source code.
Return a serializable search space object.
code_dir: directory path of source files (str) |
def raw_rsa_private_crypt(private_key, data):
"""
Performs a raw RSA algorithm in a byte string using a private key.
This is a low-level primitive and is prone to disastrous results if used
incorrectly.
:param private_key:
An oscrypto.asymmetric.PrivateKey object
:param data:
A... | Performs a raw RSA algorithm in a byte string using a private key.
This is a low-level primitive and is prone to disastrous results if used
incorrectly.
:param private_key:
An oscrypto.asymmetric.PrivateKey object
:param data:
A byte string of the plaintext to be signed or ciphertext t... |
def initialize_simulants(self):
"""Initialize this simulation's population. Should not be called
directly."""
super().initialize_simulants()
self._initial_population = self.population.get_population(True) | Initialize this simulation's population. Should not be called
directly. |
def adjust_container_limits_for_variadic_sequences(headerDir, containers, maxElements):
"""Adjusts the limits of variadic sequence MPL-containers."""
for container in containers:
headerFile = os.path.join( headerDir, "limits", container + ".hpp" )
regexMatch = r'(define\s+BOOST_MPL_LIMIT_' + c... | Adjusts the limits of variadic sequence MPL-containers. |
def volume_down(self):
"""Volume down receiver via HTTP get command."""
try:
return bool(self.send_get_command(self._urls.command_volume_down))
except requests.exceptions.RequestException:
_LOGGER.error("Connection error: volume down command not sent.")
return... | Volume down receiver via HTTP get command. |
def get_integer_value(self, label):
"""stub"""
if self.has_integer_value(label):
return int(self.my_osid_object._my_map['integerValues'][label])
raise IllegalState() | stub |
def problem_glob(extension='.py'):
"""Returns ProblemFile objects for all valid problem files"""
filenames = glob.glob('*[0-9][0-9][0-9]*{}'.format(extension))
return [ProblemFile(file) for file in filenames] | Returns ProblemFile objects for all valid problem files |
def graph_from_bbox(north, south, east, west, network_type='all_private',
simplify=True, retain_all=False, truncate_by_edge=False,
name='unnamed', timeout=180, memory=None,
max_query_area_size=50*1000*50*1000, clean_periphery=True,
infrastr... | Create a networkx graph from OSM data within some bounding box.
Parameters
----------
north : float
northern latitude of bounding box
south : float
southern latitude of bounding box
east : float
eastern longitude of bounding box
west : float
western longitude of ... |
def _register_process_with_cgrulesengd(pid):
"""Tell cgrulesengd daemon to not move the given process into other cgroups,
if libcgroup is available.
"""
# Logging/printing from inside preexec_fn would end up in the output file,
# not in the correct logger, thus it is disabled here.
from ctypes i... | Tell cgrulesengd daemon to not move the given process into other cgroups,
if libcgroup is available. |
def is_overlapping_viewport(self, hotspot, xy):
"""
Checks to see if the hotspot at position ``(x, y)``
is (at least partially) visible according to the
position of the viewport.
"""
l1, t1, r1, b1 = calc_bounds(xy, hotspot)
l2, t2, r2, b2 = calc_bounds(self._posi... | Checks to see if the hotspot at position ``(x, y)``
is (at least partially) visible according to the
position of the viewport. |
def _update(self):
r"""Update
This method updates the current reconstruction
Notes
-----
Implements algorithm 1 from [R2012]_
"""
# Calculate gradient for current iteration.
self._grad.get_grad(self._x_old)
# Update z values.
for i in ... | r"""Update
This method updates the current reconstruction
Notes
-----
Implements algorithm 1 from [R2012]_ |
def setup(db_class, simple_object_cls, primary_keys):
"""A simple API to configure the metadata"""
table_name = simple_object_cls.__name__
column_names = simple_object_cls.FIELDS
metadata = MetaData()
table = Table(table_name, metadata,
*[Column(cname, _get_best_column_type(cname)... | A simple API to configure the metadata |
def url(self):
"""
We will always check if this song file exists in local library,
if true, we return the url of the local file.
.. note::
As netease song url will be expired after a period of time,
we can not use static url here. Currently, we assume that the
... | We will always check if this song file exists in local library,
if true, we return the url of the local file.
.. note::
As netease song url will be expired after a period of time,
we can not use static url here. Currently, we assume that the
expiration time is 20 mi... |
def dynamics_from_bundle(b, times, compute=None, return_euler=False, **kwargs):
"""
Parse parameters in the bundle and call :func:`dynamics`.
See :func:`dynamics` for more detailed information.
NOTE: you must either provide compute (the label) OR all relevant options
as kwargs (ltte)
Args:
... | Parse parameters in the bundle and call :func:`dynamics`.
See :func:`dynamics` for more detailed information.
NOTE: you must either provide compute (the label) OR all relevant options
as kwargs (ltte)
Args:
b: (Bundle) the bundle with a set hierarchy
times: (list or array) times at wh... |
def __create(self, client_id, client_secret, calls, **kwargs):
"""Call documentation: `/batch/create
<https://www.wepay.com/developer/reference/batch#create>`_, plus extra
keyword parameter:
:keyword str access_token: will be used instead of instance's
``access_token... | Call documentation: `/batch/create
<https://www.wepay.com/developer/reference/batch#create>`_, plus extra
keyword parameter:
:keyword str access_token: will be used instead of instance's
``access_token`` |
def arg_file_is_new(parser, arg, mode='w'):
"""Auxiliary function to give an error if the file already exists.
Parameters
----------
parser : parser object
Instance of argparse.ArgumentParser()
arg : string
File name.
mode : string
Optional string that specifies the mode... | Auxiliary function to give an error if the file already exists.
Parameters
----------
parser : parser object
Instance of argparse.ArgumentParser()
arg : string
File name.
mode : string
Optional string that specifies the mode in which the file is
opened.
Returns
... |
def bounds_from_opts(
wkt_geometry=None, point=None, bounds=None, zoom=None, raw_conf=None
):
"""
Loads the process pyramid of a raw configuration.
Parameters
----------
raw_conf : dict
Raw mapchete configuration as dictionary.
Returns
-------
BufferedTilePyramid
"""
... | Loads the process pyramid of a raw configuration.
Parameters
----------
raw_conf : dict
Raw mapchete configuration as dictionary.
Returns
-------
BufferedTilePyramid |
def drop_all(self, checkfirst: bool = True) -> None:
"""Drop all data, tables, and databases for the PyBEL cache.
:param checkfirst: Check if the database exists before trying to drop it
"""
self.session.close()
self.base.metadata.drop_all(bind=self.engine, checkfirst=checkfirst... | Drop all data, tables, and databases for the PyBEL cache.
:param checkfirst: Check if the database exists before trying to drop it |
def use_software_cache(sw_dir=None, reload_deps=False):
"""
Adjusts ``sys.path`` so that the cached software at *sw_dir* is used. *sw_dir* is evaluated with
:py:func:`get_sw_dir`. When *reload_deps* is *True*, :py:func:`reload_dependencies` is invoked.
"""
sw_dir = get_sw_dir(sw_dir)
if os.path.... | Adjusts ``sys.path`` so that the cached software at *sw_dir* is used. *sw_dir* is evaluated with
:py:func:`get_sw_dir`. When *reload_deps* is *True*, :py:func:`reload_dependencies` is invoked. |
def fill(self, **kwargs):
''' Loads the relationships into this model. They are not loaded by
default '''
setattr(self.obj, self.name, self.get(**kwargs)) | Loads the relationships into this model. They are not loaded by
default |
def get_ns2nts(results, fldnames=None, **kws):
"""Get namedtuples of GOEA results, split into BP, MF, CC."""
ns2nts = cx.defaultdict(list)
nts = MgrNtGOEAs(results).get_goea_nts_all(fldnames, **kws)
for ntgoea in nts:
ns2nts[ntgoea.NS].append(ntgoea)
return ns2nts | Get namedtuples of GOEA results, split into BP, MF, CC. |
def pad_dialogues(self, dialogues):
"""
Pad the entire dataset.
This involves adding padding at the end of each sentence, and in the case of
a hierarchical model, it also involves adding padding at the end of each dialogue,
so that every training sample (dialogue) has the same di... | Pad the entire dataset.
This involves adding padding at the end of each sentence, and in the case of
a hierarchical model, it also involves adding padding at the end of each dialogue,
so that every training sample (dialogue) has the same dimension. |
def dispatch(self, request, *args, **kwargs):
''' Get the set of invoices for which to permit notifications '''
if 'pk' in self.kwargs:
try:
self.invoices = Invoice.objects.filter(pk=self.kwargs.get('pk'))[:]
except ValueError:
raise Http404()
... | Get the set of invoices for which to permit notifications |
def show_front_page_groups(self, group_id):
"""
Show front page.
Retrieve the content of the front page
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = group_id
self.logg... | Show front page.
Retrieve the content of the front page |
def createWcsHDU(self):
""" Generate a WCS header object that can be used to
populate a reference WCS HDU.
"""
hdu = fits.ImageHDU()
hdu.header['EXTNAME'] = 'WCS'
hdu.header['EXTVER'] = 1
# Now, update original image size information
hdu.header['WCSAXE... | Generate a WCS header object that can be used to
populate a reference WCS HDU. |
def iter_tiles(self, include_controller=True):
"""Iterate over all tiles in this device in order.
The ordering is by tile address which places the controller tile
first in the list.
Args:
include_controller (bool): Include the controller tile in the
results.... | Iterate over all tiles in this device in order.
The ordering is by tile address which places the controller tile
first in the list.
Args:
include_controller (bool): Include the controller tile in the
results.
Yields:
int, EmulatedTile: A tuple w... |
def _rd_dat_file(file_name, dir_name, pb_dir, fmt, start_byte, n_samp):
"""
Read data from a dat file, either local or remote, into a 1d numpy
array.
This is the lowest level dat reading function (along with
`_stream_dat` which this function may call), and is called by
`_rd_dat_signals`.
P... | Read data from a dat file, either local or remote, into a 1d numpy
array.
This is the lowest level dat reading function (along with
`_stream_dat` which this function may call), and is called by
`_rd_dat_signals`.
Parameters
----------
start_byte : int
The starting byte number to re... |
def called_with(self, *args, **kwargs):
"""Return True if the spy was called with the specified args/kwargs.
Otherwise raise VerificationError.
"""
expected_call = Call(*args, **kwargs)
if expected_call in calls(self.spy):
return True
raise VerificationError... | Return True if the spy was called with the specified args/kwargs.
Otherwise raise VerificationError. |
def create_user(name, groups=None, key_file=None):
"""Create a user. Adds a key file to authorized_keys if given."""
groups = groups or []
if not user_exists(name):
for group in groups:
if not group_exists(group):
sudo(u"addgroup %s" % group)
groups = groups and ... | Create a user. Adds a key file to authorized_keys if given. |
def _script_load(script):
'''
Borrowed/modified from my book, Redis in Action:
https://github.com/josiahcarlson/redis-in-action/blob/master/python/ch11_listing_source.py
Used for Lua scripting support when writing against Redis 2.6+ to allow
for multiple unique columns per model.
'''
script... | Borrowed/modified from my book, Redis in Action:
https://github.com/josiahcarlson/redis-in-action/blob/master/python/ch11_listing_source.py
Used for Lua scripting support when writing against Redis 2.6+ to allow
for multiple unique columns per model. |
def _fusion_range_to_dsl(tokens) -> FusionRangeBase:
"""Convert a PyParsing data dictionary into a PyBEL.
:type tokens: ParseResult
"""
if FUSION_MISSING in tokens:
return missing_fusion_range()
return fusion_range(
reference=tokens[FUSION_REFERENCE],
start=tokens[FUSION_ST... | Convert a PyParsing data dictionary into a PyBEL.
:type tokens: ParseResult |
def read_partial_map(filenames, column, fullsky=True, **kwargs):
"""
Read a partial HEALPix file(s) and return pixels and values/map. Can
handle 3D healpix maps (pix, value, zdim). Returned array has
shape (dimz,npix).
Parameters:
-----------
filenames : list of input filenames
colu... | Read a partial HEALPix file(s) and return pixels and values/map. Can
handle 3D healpix maps (pix, value, zdim). Returned array has
shape (dimz,npix).
Parameters:
-----------
filenames : list of input filenames
column : column of interest
fullsky : partial or fullsky map
... |
def clean(self, value):
"""Take a dirty value and clean it."""
if (
self.base_type is not None and
value is not None and
not isinstance(value, self.base_type)
):
if isinstance(self.base_type, tuple):
allowed_types = [typ.__name__ fo... | Take a dirty value and clean it. |
def register_view(self, view):
"""Called when the View was registered
Can be used e.g. to connect signals. Here, the destroy signal is connected to close the application
:param rafcon.gui.views.state_editor.semantic_data_editor.SemanticDataEditorView view: An view to show all
seman... | Called when the View was registered
Can be used e.g. to connect signals. Here, the destroy signal is connected to close the application
:param rafcon.gui.views.state_editor.semantic_data_editor.SemanticDataEditorView view: An view to show all
semantic data of a state |
def disable_if_no_tty(cls):
"""Disable all colors only if there is no TTY available.
:return: True if colors are disabled, False if stderr or stdout is a TTY.
:rtype: bool
"""
if sys.stdout.isatty() or sys.stderr.isatty():
return False
cls.disable_all_colors(... | Disable all colors only if there is no TTY available.
:return: True if colors are disabled, False if stderr or stdout is a TTY.
:rtype: bool |
def render_done(self, form, **kwargs):
"""
When rendering the done view, we have to redirect first (if the URL
name doesn't fit).
"""
if kwargs.get('step', None) != self.done_step_name:
return redirect(self.url_name, step=self.done_step_name)
return super(Name... | When rendering the done view, we have to redirect first (if the URL
name doesn't fit). |
def bulk_write(self, requests, **kwargs):
"""
See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.bulk_write
Warning: this is wrapped in mongo_retry, and is therefore potentially unsafe if the write you want to execute
isn't idempotent.
... | See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.bulk_write
Warning: this is wrapped in mongo_retry, and is therefore potentially unsafe if the write you want to execute
isn't idempotent. |
def time_correlation_by_diagonalization(P, pi, obs1, obs2=None, time=1, rdl=None):
"""
calculates time correlation. Raises P to power 'times' by diagonalization.
If rdl tuple (R, D, L) is given, it will be used for
further calculation.
"""
if rdl is None:
raise ValueError("no rdl decompo... | calculates time correlation. Raises P to power 'times' by diagonalization.
If rdl tuple (R, D, L) is given, it will be used for
further calculation. |
def date_time_this_year():
"""
获取当前年的随机时间字符串
:return:
* date_this_year: (datetime) 当前月份的随机时间
举例如下::
print('--- GetRandomTime.date_time_this_year demo ---')
print(GetRandomTime.date_time_this_year())
print('---')
执行结果::
... | 获取当前年的随机时间字符串
:return:
* date_this_year: (datetime) 当前月份的随机时间
举例如下::
print('--- GetRandomTime.date_time_this_year demo ---')
print(GetRandomTime.date_time_this_year())
print('---')
执行结果::
--- GetRandomTime.date_time_thi... |
def QA_SU_save_future_day(engine, client=DATABASE):
"""save future_day
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
engine = select_save_engine(engine)
engine.QA_SU_save_future_day(client=client) | save future_day
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE}) |
def calculate_job_input_hash(job_spec, workflow_json):
"""Calculate md5 hash of job specification and workflow json."""
if 'workflow_workspace' in job_spec:
del job_spec['workflow_workspace']
job_md5_buffer = md5()
job_md5_buffer.update(json.dumps(job_spec).encode('utf-8'))
job_md5_buffer.up... | Calculate md5 hash of job specification and workflow json. |
def get_unique_backends():
"""Gets the unique backends that are available.
Returns:
list: Unique available backends.
Raises:
QiskitError: No backends available.
"""
backends = IBMQ.backends()
unique_hardware_backends = []
unique_names = []
for back in backends:
... | Gets the unique backends that are available.
Returns:
list: Unique available backends.
Raises:
QiskitError: No backends available. |
def xbm(self, scale=1, quiet_zone=4):
"""Returns a string representing an XBM image of the QR code.
The XBM format is a black and white image format that looks like a
C header file.
Because displaying QR codes in Tkinter is the
primary use case for this renderer, this m... | Returns a string representing an XBM image of the QR code.
The XBM format is a black and white image format that looks like a
C header file.
Because displaying QR codes in Tkinter is the
primary use case for this renderer, this method does not take a file
parameter. Ins... |
def BGPNeighborPrefixExceeded_originator_switch_info_switchIpV4Address(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
BGPNeighborPrefixExceeded = ET.SubElement(config, "BGPNeighborPrefixExceeded", xmlns="http://brocade.com/ns/brocade-notification-stream")
... | Auto Generated Code |
def square_batch_region(data, region, bam_files, vrn_files, out_file):
"""Perform squaring of a batch in a supplied region, with input BAMs
"""
from bcbio.variation import sentieon, strelka2
if not utils.file_exists(out_file):
jointcaller = tz.get_in(("config", "algorithm", "jointcaller"), data)... | Perform squaring of a batch in a supplied region, with input BAMs |
def run_sparql_on(q, ontology):
"""
Run a SPARQL query (q) on a given Ontology (Enum EOntology)
"""
logging.info("Connecting to " + ontology.value + " SPARQL endpoint...")
sparql = SPARQLWrapper(ontology.value)
logging.info("Made wrapper: {}".format(sparql))
sparql.setQuery(q)
sparql.set... | Run a SPARQL query (q) on a given Ontology (Enum EOntology) |
def delete_namespaced_role_binding(self, name, namespace, **kwargs):
"""
delete a RoleBinding
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_namespaced_role_binding(name, namespace,... | delete a RoleBinding
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_namespaced_role_binding(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
... |
def returner(ret):
'''
Send a Telegram message with the data.
:param ret: The data to be sent.
:return: Boolean if message was sent successfully.
'''
_options = _get_options(ret)
chat_id = _options.get('chat_id')
token = _options.get('token')
if not chat_id:
log... | Send a Telegram message with the data.
:param ret: The data to be sent.
:return: Boolean if message was sent successfully. |
def _set_dhcpd(self, v, load=False):
"""
Setter method for dhcpd, mapped from YANG variable /rbridge_id/dhcpd (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_dhcpd is considered as a private
method. Backends looking to populate this variable should
do... | Setter method for dhcpd, mapped from YANG variable /rbridge_id/dhcpd (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_dhcpd is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_dhcpd() directly. |
def rowget(self,tables_dict,row_list,index):
"row_list in self.row_order"
tmp=row_list
for i in self.index_tuple(tables_dict,index,False): tmp=tmp[i]
return tmp | row_list in self.row_order |
def fmt_val(val, shorten=True):
"""Format a value for inclusion in an
informative text string.
"""
val = repr(val)
max = 50
if shorten:
if len(val) > max:
close = val[-1]
val = val[0:max-4] + "..."
if close in (">", "'", '"', ']', '}', ')'):
... | Format a value for inclusion in an
informative text string. |
def rebase_all_branches(self):
""" Rebase all branches, if possible. """
col_width = max(len(b.name) for b in self.branches) + 1
if self.repo.head.is_detached:
raise GitError("You're not currently on a branch. I'm exiting"
" in case you're in the middl... | Rebase all branches, if possible. |
def select_logfile(self, logfile):
"""
Parameters
----------
logfile : str
Returns
-------
dict
"""
data = 'logFileSelect,' + logfile
r = self._basic_post(url='logBrowser', data=data)
return r.json() | Parameters
----------
logfile : str
Returns
-------
dict |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.