positive stringlengths 100 30.3k | anchor stringlengths 1 15k |
|---|---|
def _as_log_entry(self, name, now):
"""Makes a `LogEntry` from this instance for the given log_name.
Args:
rules (:class:`ReportingRules`): determines what labels, metrics and
logs to include in the report request.
now (:class:`datetime.DateTime`): the current time
... | Makes a `LogEntry` from this instance for the given log_name.
Args:
rules (:class:`ReportingRules`): determines what labels, metrics and
logs to include in the report request.
now (:class:`datetime.DateTime`): the current time
Return:
a ``LogEntry`` generated ... |
def _update(collection_name, upsert, multi, spec, doc, check_keys, opts):
"""Get an OP_UPDATE message."""
flags = 0
if upsert:
flags += 1
if multi:
flags += 2
encode = _dict_to_bson # Make local. Uses extensions.
encoded_update = encode(doc, check_keys, opts)
return b"".join... | Get an OP_UPDATE message. |
def get_padding_lengths(self) -> Dict[str, int]:
"""
The ``TextField`` has a list of ``Tokens``, and each ``Token`` gets converted into arrays by
(potentially) several ``TokenIndexers``. This method gets the max length (over tokens)
associated with each of these arrays.
"""
... | The ``TextField`` has a list of ``Tokens``, and each ``Token`` gets converted into arrays by
(potentially) several ``TokenIndexers``. This method gets the max length (over tokens)
associated with each of these arrays. |
def apply_changes(self, other, with_buffer=False):
"""Applies updates from the buffer of another filter.
Params:
other (MeanStdFilter): Other filter to apply info from
with_buffer (bool): Flag for specifying if the buffer should be
copied from other.
Exa... | Applies updates from the buffer of another filter.
Params:
other (MeanStdFilter): Other filter to apply info from
with_buffer (bool): Flag for specifying if the buffer should be
copied from other.
Examples:
>>> a = MeanStdFilter(())
>>> a... |
def GuinierPorod(q, G, Rg, alpha):
"""Empirical Guinier-Porod scattering
Inputs:
-------
``q``: independent variable
``G``: factor of the Guinier-branch
``Rg``: radius of gyration
``alpha``: power-law exponent
Formula:
--------
``G * exp(-q^2*Rg^2/3)`` if ``... | Empirical Guinier-Porod scattering
Inputs:
-------
``q``: independent variable
``G``: factor of the Guinier-branch
``Rg``: radius of gyration
``alpha``: power-law exponent
Formula:
--------
``G * exp(-q^2*Rg^2/3)`` if ``q<q_sep`` and ``a*q^alpha`` otherwise.
... |
def update_dict(self, label: Dict, pred: Dict):
"""
If label is missing the right name, copy it from the prediction.
"""
if not set(self.label_names).issubset(set(label.keys())):
label.update({name:pred[name] for name in self.label_names})
super().update_dict(label, p... | If label is missing the right name, copy it from the prediction. |
def get_page(search_text):
"""
formats the entire search result in a table output
"""
lst = search_aikif(search_text)
txt = '<table class="as-table as-table-zebra as-table-horizontal">'
for result in lst:
txt += '<TR><TD>' + result + '</TD></TR>'
txt += '</TABLE>\n\n'
return txt | formats the entire search result in a table output |
def docker_monitor(self, cidfile, tmpdir_prefix, cleanup_cidfile, process):
# type: (Text, Text, bool, subprocess.Popen) -> None
"""Record memory usage of the running Docker container."""
# Todo: consider switching to `docker create` / `docker start`
# instead of `docker run` as `docker ... | Record memory usage of the running Docker container. |
def generate_downloader(headers: Dict[str, str], args: Any, max_per_hour: int=30
) -> Callable[..., None]:
"""Create function to download with rate limiting and text progress."""
def _downloader(url: str, dest: str) -> None:
@rate_limited(max_per_hour, args)
def _rate_l... | Create function to download with rate limiting and text progress. |
def paired_reader_from_bamfile(args,
log,
usage_logger,
annotated_writer):
'''Given a BAM file, return a generator that yields filtered, paired reads'''
total_aligns = pysamwrapper.total_align_count(args.input_bam)
... | Given a BAM file, return a generator that yields filtered, paired reads |
def data_import(self, json_response):
"""Import scenes from JSON response."""
if 'data' not in json_response:
raise PyVLXException('no element data found: {0}'.format(
json.dumps(json_response)))
data = json_response['data']
for item in data:
self.... | Import scenes from JSON response. |
def wr_tex(self, fout_tex="gos_depth01.tex"):
"""write text table of depth-01 GO terms and their letter representation."""
data_nts = self.get_d1nts()
joinchr = " & "
#pylint: disable=anomalous-backslash-in-string
eol = " \\\\\n"
with open(fout_tex, 'w') as prt:
... | write text table of depth-01 GO terms and their letter representation. |
def copyFile(input, output, replace=None):
"""Copy a file whole from input to output."""
_found = findFile(output)
if not _found or (_found and replace):
shutil.copy2(input, output) | Copy a file whole from input to output. |
def compile_binary(source):
"""
Prepare chkrootkit binary
$ tar xzvf chkrootkit.tar.gz
$ cd chkrootkit-0.52
$ make sense
sudo mv chkrootkit-0.52 /usr/local/chkrootkit
sudo ln -s
"""
cmd = 'make sense'
slink = '/usr/local/bin/chkrootkit'
target = '/usr/local/chkrootkit/chkroot... | Prepare chkrootkit binary
$ tar xzvf chkrootkit.tar.gz
$ cd chkrootkit-0.52
$ make sense
sudo mv chkrootkit-0.52 /usr/local/chkrootkit
sudo ln -s |
def ComponentsToPath(components):
"""Converts a list of path components to a canonical path representation.
Args:
components: A sequence of path components.
Returns:
A canonical MySQL path representation.
"""
precondition.AssertIterableType(components, Text)
for component in components:
if not... | Converts a list of path components to a canonical path representation.
Args:
components: A sequence of path components.
Returns:
A canonical MySQL path representation. |
def cares_about(self, delta):
"""Return True if this observer "cares about" (i.e. wants to be
called) for a this delta.
"""
if (self.entity_id and delta.get_id() and
not re.match(self.entity_id, str(delta.get_id()))):
return False
if self.entity_type... | Return True if this observer "cares about" (i.e. wants to be
called) for a this delta. |
def get(self,
singleExposure=False):
"""
*get the orbfitPositions object*
**Key Arguments:**
- ``singleExposure`` -- only execute fot a single exposure (useful for debugging)
**Return:**
- None
**Usage:**
See class docstring
... | *get the orbfitPositions object*
**Key Arguments:**
- ``singleExposure`` -- only execute fot a single exposure (useful for debugging)
**Return:**
- None
**Usage:**
See class docstring |
def run_experiment(self):
"""
Run the job specified in experiment_script
"""
data=self.data
options=self.options
result=self.result
command = open(self.options.experiment_script).read()
result["experiment_script"]=command
t0=time.time()
ex... | Run the job specified in experiment_script |
def create(self, path, mode): # pragma: no cover
"""
This is currently a read-only filessytem.
GetAttr will return a stat for everything
if getattr raises FuseOSError(ENOENT)
OS may call this function and the write function
"""
# print("create {}".format(path))
... | This is currently a read-only filessytem.
GetAttr will return a stat for everything
if getattr raises FuseOSError(ENOENT)
OS may call this function and the write function |
def remove(self):
"""remove item from its class
"""
DoubleLinkedListItem.remove(self) # remove from double linked list
if self.succ is self: # list was a singleton
self.theclass.items = None # class is empty
elif self.theclass.items is self:... | remove item from its class |
def multi_path_generator(pathnames):
"""
yields (name,chunkgen) for all of the files found under the list
of pathnames given. This is recursive, so directories will have
their contents emitted. chunkgen is a function that can called and
iterated over to obtain the contents of the file in multiple
... | yields (name,chunkgen) for all of the files found under the list
of pathnames given. This is recursive, so directories will have
their contents emitted. chunkgen is a function that can called and
iterated over to obtain the contents of the file in multiple
reads. |
async def blobize(self, elem=None, elem_type=None, params=None):
"""
Main blobbing
:param elem:
:param elem_type:
:param params:
:return:
"""
if self.writing:
await self.field(elem=elem, elem_type=elem_type, params=params)
return by... | Main blobbing
:param elem:
:param elem_type:
:param params:
:return: |
def create_token_mapping(docgraph_with_old_names, docgraph_with_new_names,
verbose=False):
"""
given two document graphs which annotate the same text and which use the
same tokenization, creates a dictionary with a mapping from the token
IDs used in the first graph to the token ... | given two document graphs which annotate the same text and which use the
same tokenization, creates a dictionary with a mapping from the token
IDs used in the first graph to the token IDs used in the second graph.
Parameters
----------
docgraph_with_old_names : DiscourseDocumentGraph
a docu... |
def stop(self, container, instances=None, map_name=None, **kwargs):
"""
Stops instances for a container configuration.
:param container: Container name.
:type container: unicode | str
:param instances: Instance names to stop. If not specified, will stop all instances as specifie... | Stops instances for a container configuration.
:param container: Container name.
:type container: unicode | str
:param instances: Instance names to stop. If not specified, will stop all instances as specified in the
configuration (or just one default instance).
:type instances:... |
def copy_and_sum_families(family_source, family_target):
""" methods iterates thru source family and copies its entries to target family
in case key already exists in both families - then the values are added"""
for every in family_source:
if every not in family_target:
family_target[eve... | methods iterates thru source family and copies its entries to target family
in case key already exists in both families - then the values are added |
def _bbvi_fit(self, posterior, optimizer='RMSProp', iterations=1000,
map_start=True, batch_size=12, mini_batch=None, learning_rate=0.001,
record_elbo=False, quiet_progress=False, **kwargs):
""" Performs Black Box Variational Inference
Parameters
----------
posterior : ... | Performs Black Box Variational Inference
Parameters
----------
posterior : method
Hands bbvi_fit a posterior object
optimizer : string
Stochastic optimizer: one of RMSProp or ADAM.
iterations: int
How many iterations for BBVI
map_st... |
def can_be_executed_by(self, thread_id):
'''By default, it must be in the same thread to be executed
'''
return self.thread_id == thread_id or self.thread_id.endswith('|' + thread_id) | By default, it must be in the same thread to be executed |
def randomprune(self,n):
"""prune down to n items at random, disregarding their score"""
self.data = random.sample(self.data, n) | prune down to n items at random, disregarding their score |
def allocate(self, nodes, append=True):
# TODO: check docstring
"""Allocates all nodes from `nodes` list in this route
Parameters
----------
nodes : type
Desc
append : bool, defaults to True
Desc
"""
nodes_demand ... | Allocates all nodes from `nodes` list in this route
Parameters
----------
nodes : type
Desc
append : bool, defaults to True
Desc |
def delete_agile_board(self, board_id):
"""
Delete agile board by id
:param board_id:
:return:
"""
url = 'rest/agile/1.0/board/{}'.format(str(board_id))
return self.delete(url) | Delete agile board by id
:param board_id:
:return: |
def _ConvertParamType(self, paramType):
"""
Convert vmodl.reflect.DynamicTypeManager.ParamTypeInfo to pyVmomi param
definition
"""
if paramType:
name = paramType.name
version = paramType.version
aType = paramType.type
flags = self._ConvertAnnotations(par... | Convert vmodl.reflect.DynamicTypeManager.ParamTypeInfo to pyVmomi param
definition |
def start_dag(self, dag, *, data=None):
""" Schedule the execution of a dag by sending a signal to the workflow.
Args:
dag (Dag, str): The dag object or the name of the dag that should be started.
data (MultiTaskData): The data that should be passed on to the new dag.
R... | Schedule the execution of a dag by sending a signal to the workflow.
Args:
dag (Dag, str): The dag object or the name of the dag that should be started.
data (MultiTaskData): The data that should be passed on to the new dag.
Returns:
str: The name of the successfull... |
def run_network_operation(self, task, wait_timeout=None,
close_timeout=None,
name='Network operation'):
'''Run the task and raise appropriate exceptions.
Coroutine.
'''
if wait_timeout is not None and close_timeout is not None:... | Run the task and raise appropriate exceptions.
Coroutine. |
def fix_orientation(image):
""" adapted from https://stackoverflow.com/a/30462851/318857
Apply Image.transpose to ensure 0th row of pixels is at the visual
top of the image, and 0th column is the visual left-hand side.
Return the original image if unable to determine the orientation.
... | adapted from https://stackoverflow.com/a/30462851/318857
Apply Image.transpose to ensure 0th row of pixels is at the visual
top of the image, and 0th column is the visual left-hand side.
Return the original image if unable to determine the orientation.
As per CIPA DC-008-2012, the orie... |
def plt_goids(gosubdag, fout_img, goids, **kws_plt):
"""Plot GO IDs in a DAG (Directed Acyclic Graph)."""
gosubdag_plt = GoSubDag(goids, gosubdag.go2obj, rcntobj=gosubdag.rcntobj, **kws_plt)
godagplot = GoSubDagPlot(gosubdag_plt, **kws_plt)
godagplot.plt_dag(fout_img)
return godagplot | Plot GO IDs in a DAG (Directed Acyclic Graph). |
def forum_id(self):
"""小组发帖要用的 forum_id"""
html = self.request(self.team_url).text
soup = BeautifulSoup(html)
return soup.find(id='forum_id').attrs['value'] | 小组发帖要用的 forum_id |
def visitIriRange(self, ctx: ShExDocParser.IriRangeContext):
""" iriRange: iri (STEM_MARK iriExclusion*)? """
baseiri = self.context.iri_to_iriref(ctx.iri())
if not ctx.STEM_MARK():
vsvalue = baseiri # valueSetValue = objectValue / objectValue = IRI
else:
... | iriRange: iri (STEM_MARK iriExclusion*)? |
def elementTypeName(self):
""" String representation of the element type.
"""
if self._array is None:
return super(ArrayRti, self).elementTypeName
else:
dtype = self._array.dtype
return '<structured>' if dtype.names else str(dtype) | String representation of the element type. |
def upsert_users_from_legacy_publication_trigger(plpy, td):
"""A compatibility trigger to upsert users from legacy persons table."""
modified_state = "OK"
authors = td['new']['authors'] and td['new']['authors'] or []
maintainers = td['new']['maintainers'] and td['new']['maintainers'] or []
licensors... | A compatibility trigger to upsert users from legacy persons table. |
def _ctypes_out(parameter):
"""Returns a parameter variable declaration for an output variable for the specified
parameter.
"""
if (parameter.dimension is not None and ":" in parameter.dimension
and "out" in parameter.direction and ("allocatable" in parameter.modifiers or
... | Returns a parameter variable declaration for an output variable for the specified
parameter. |
def _show_or_dump(self, dump=False, indent=3,
lvl="", label_lvl="", first_call=True):
""" Reproduced from packet.py """
ct = AnsiColorTheme() if dump else conf.color_theme
s = "%s%s %s %s \n" % (label_lvl, ct.punct("###["),
ct.layer_name(self.... | Reproduced from packet.py |
def get_orthology_matrix(self, pid_cutoff=None, bitscore_cutoff=None, evalue_cutoff=None, filter_condition='OR',
remove_strains_with_no_orthology=True,
remove_strains_with_no_differences=False,
remove_genes_not_in_base_model=True):
... | Create the orthology matrix by finding best bidirectional BLAST hits. Genes = rows, strains = columns
Runs run_makeblastdb, run_bidirectional_blast, and calculate_bbh for protein sequences.
Args:
pid_cutoff (float): Minimum percent identity between BLAST hits to filter for in the range [0,... |
def set_selection(self, time, freqs, blarr, calname='', radec=(), dist=1, spwind=[], pols=['XX','YY']):
""" Set select parameter that defines time, spw, and pol solutions to apply.
time defines the time to find solutions near in mjd.
freqs defines frequencies to select bandpass solution
... | Set select parameter that defines time, spw, and pol solutions to apply.
time defines the time to find solutions near in mjd.
freqs defines frequencies to select bandpass solution
blarr is array of size 2xnbl that gives pairs of antennas in each baseline (a la tpipe.blarr).
radec (radian... |
def _raw_sql(self, values):
"""Prepare SQL statement consisting of a sequence of WHEN .. THEN statements."""
if isinstance(self.model._meta.pk, CharField):
when_clauses = " ".join(
[self._when("'{}'".format(x), y) for (x, y) in values]
)
else:
... | Prepare SQL statement consisting of a sequence of WHEN .. THEN statements. |
def get_input_kwargs(self, key=None, default=None):
"""
Deprecated. Use `get_catalog_info` instead.
Get information from the catalog config file.
If *key* is `None`, return the full dict.
"""
warnings.warn("`get_input_kwargs` is deprecated; use `get_catalog_info` instead... | Deprecated. Use `get_catalog_info` instead.
Get information from the catalog config file.
If *key* is `None`, return the full dict. |
def assessModel(self, target: str, prediction: str, nominal: bool = True, event: str = '', **kwargs):
"""
This method will calculate assessment measures using the SAS AA_Model_Eval Macro used for SAS Enterprise Miner.
Not all datasets can be assessed. This is designed for scored data that includ... | This method will calculate assessment measures using the SAS AA_Model_Eval Macro used for SAS Enterprise Miner.
Not all datasets can be assessed. This is designed for scored data that includes a target and prediction columns
TODO: add code example of build, score, and then assess
:param target:... |
def format_price(self, price):
"""Formats the price with the set decimal mark and correct currency
"""
return u"{} {}{}{:02d}".format(
self.currency_symbol,
price[0],
self.decimal_mark,
price[1],
) | Formats the price with the set decimal mark and correct currency |
def _cross_check(self, pub_key):
"""
In Ecdsa, both the key and the algorithm define the curve.
Therefore, we must cross check them to make sure they're the same.
:param key:
:raises: ValueError is the curves are not the same
"""
if self.curve_name != pub_key.cur... | In Ecdsa, both the key and the algorithm define the curve.
Therefore, we must cross check them to make sure they're the same.
:param key:
:raises: ValueError is the curves are not the same |
def map_gid2(self, tiled_gid):
""" WIP. need to refactor the gid code
:param tiled_gid:
:return:
"""
tiled_gid = int(tiled_gid)
# gidmap is a default dict, so cannot trust to raise KeyError
if tiled_gid in self.gidmap:
return self.gidmap[tiled_gid]
... | WIP. need to refactor the gid code
:param tiled_gid:
:return: |
def eye(N, M=0, k=0, dtype=None, **kwargs):
"""Returns a new symbol of 2-D shpae, filled with ones on the diagonal and zeros elsewhere.
Parameters
----------
N: int
Number of rows in the output.
M: int, optional
Number of columns in the output. If 0, defaults to N.
k: int, optio... | Returns a new symbol of 2-D shpae, filled with ones on the diagonal and zeros elsewhere.
Parameters
----------
N: int
Number of rows in the output.
M: int, optional
Number of columns in the output. If 0, defaults to N.
k: int, optional
Index of the diagonal: 0 (the default) ... |
def render(self, mode='human'):
"""
Render the environment.
Args:
mode (str): the mode to render with:
- human: render to the current display
- rgb_array: Return an numpy.ndarray with shape (x, y, 3),
representing RGB values for an x-by-y pixel ... | Render the environment.
Args:
mode (str): the mode to render with:
- human: render to the current display
- rgb_array: Return an numpy.ndarray with shape (x, y, 3),
representing RGB values for an x-by-y pixel image
Returns:
a numpy array if... |
def calculate_single_terms(self):
"""Lines of model method with the same name."""
lines = self._call_methods('calculate_single_terms',
self.model.PART_ODE_METHODS)
if lines:
lines.insert(1, (' self.numvars.nmb_calls ='
... | Lines of model method with the same name. |
def remove_files(root_dir):
"""
Remove all files and directories in supplied root directory.
"""
for dirpath, dirnames, filenames in os.walk(os.path.abspath(root_dir)):
for filename in filenames:
os.remove(os.path.join(root_dir, filename))
for dirname in dirnames:
... | Remove all files and directories in supplied root directory. |
def gauge(self, stats, value):
"""
Log gauges
>>> client = StatsdClient()
>>> client.gauge('example.gauge', 47)
>>> client.gauge(('example.gauge41', 'example.gauge43'), 47)
"""
self.update_stats(stats, value, self.SC_GAUGE) | Log gauges
>>> client = StatsdClient()
>>> client.gauge('example.gauge', 47)
>>> client.gauge(('example.gauge41', 'example.gauge43'), 47) |
def handle_error(self, error, req, schema, error_status_code, error_headers):
"""Handles errors during parsing. Raises a `tornado.web.HTTPError`
with a 400 error.
"""
status_code = error_status_code or self.DEFAULT_VALIDATION_STATUS
if status_code == 422:
reason = "Un... | Handles errors during parsing. Raises a `tornado.web.HTTPError`
with a 400 error. |
def operands(self, value):
"""Set instruction operands.
"""
if len(value) != 3:
raise Exception("Invalid instruction operands : %s" % str(value))
self._operands = value | Set instruction operands. |
def field_types(self):
"""
Access the field_types
:returns: twilio.rest.autopilot.v1.assistant.field_type.FieldTypeList
:rtype: twilio.rest.autopilot.v1.assistant.field_type.FieldTypeList
"""
if self._field_types is None:
self._field_types = FieldTypeList(sel... | Access the field_types
:returns: twilio.rest.autopilot.v1.assistant.field_type.FieldTypeList
:rtype: twilio.rest.autopilot.v1.assistant.field_type.FieldTypeList |
def profile_solver(ml, accel=None, **kwargs):
"""Profile a particular multilevel object.
Parameters
----------
ml : multilevel
Fully constructed multilevel object
accel : function pointer
Pointer to a valid Krylov solver (e.g. gmres, cg)
Returns
-------
residuals : arra... | Profile a particular multilevel object.
Parameters
----------
ml : multilevel
Fully constructed multilevel object
accel : function pointer
Pointer to a valid Krylov solver (e.g. gmres, cg)
Returns
-------
residuals : array
Array of residuals for each iteration
... |
def get_all_parents(self):
"""Return all parent GO IDs."""
all_parents = set()
for parent in self.parents:
all_parents.add(parent.item_id)
all_parents |= parent.get_all_parents()
return all_parents | Return all parent GO IDs. |
def item_land_adapter(obj, request):
"""
Adapter for rendering an item of
:class: `pycountry.db.Data` to json.
"""
return {
'id': obj.alpha_2,
'alpha2': obj.alpha_2,
'alpha3': obj.alpha_3,
'naam': _(obj.name)
} | Adapter for rendering an item of
:class: `pycountry.db.Data` to json. |
def generate_data(path, tokenizer, char_vcb, word_vcb, is_training=False):
'''
Generate data
'''
global root_path
qp_pairs = data.load_from_file(path=path, is_training=is_training)
tokenized_sent = 0
# qp_pairs = qp_pairs[:1000]1
for qp_pair in qp_pairs:
tokenized_sent += 1
... | Generate data |
def runExperiment5A(dirName):
"""
This runs the first experiment in the section "Simulations with Sensorimotor
Sequences", an example sensorimotor sequence.
"""
# Results are put into a pkl file which can be used to generate the plots.
# dirName is the absolute path where the pkl file will be placed.
resu... | This runs the first experiment in the section "Simulations with Sensorimotor
Sequences", an example sensorimotor sequence. |
def _get_stddevs(self, C, stddev_types, num_sites):
"""
Return total standard deviation.
"""
stddevs = []
for stddev_type in stddev_types:
assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
stddevs.append(np.log(10 ** C['sigma']) + np.zeros(nu... | Return total standard deviation. |
def change_env(name, val):
"""
Args:
name(str), val(str):
Returns:
a context where the environment variable ``name`` being set to
``val``. It will be set back after the context exits.
"""
oldval = os.environ.get(name, None)
os.environ[name] = val
yield
if oldval ... | Args:
name(str), val(str):
Returns:
a context where the environment variable ``name`` being set to
``val``. It will be set back after the context exits. |
def reindex(self, ind):
"""reindex
Arguments:
ind {[type]} -- [description]
Raises:
RuntimeError -- [description]
RuntimeError -- [description]
Returns:
[type] -- [description]
"""
if isinstance(ind, pd.MultiIndex):
... | reindex
Arguments:
ind {[type]} -- [description]
Raises:
RuntimeError -- [description]
RuntimeError -- [description]
Returns:
[type] -- [description] |
def analyze(self, scratch, **kwargs):
"""Categorize instances of attempted say and sound synchronization."""
errors = Counter()
for script in self.iter_scripts(scratch):
prev_name, prev_depth, prev_block = '', 0, script.blocks[0]
gen = self.iter_blocks(script.blocks)
... | Categorize instances of attempted say and sound synchronization. |
def _expand_endpoint_name(endpoint_name, flags):
"""
Populate any ``{endpoint_name}`` tags in the flag names for the given
handler, based on the handlers module / file name.
"""
return tuple(flag.format(endpoint_name=endpoint_name) for flag in flags) | Populate any ``{endpoint_name}`` tags in the flag names for the given
handler, based on the handlers module / file name. |
def encrypt(self, plaintext):
"""Return ciphertext for given plaintext."""
# String to bytes.
plainbytes = plaintext.encode('utf8')
# Compress plaintext bytes.
compressed = zlib.compress(plainbytes)
# Construct AES-GCM cipher, with 96-bit nonce.
cipher = AES.ne... | Return ciphertext for given plaintext. |
def _auth(profile=None):
'''
Set up neutron credentials
'''
if profile:
credentials = __salt__['config.option'](profile)
user = credentials['keystone.user']
password = credentials['keystone.password']
tenant = credentials['keystone.tenant']
auth_url = credentials[... | Set up neutron credentials |
def sequence(start, stop, step=None):
"""
Generate a sequence of integers from `start` to `stop`, incrementing by `step`.
If `step` is not set, incrementing by 1 if `start` is less than or equal to `stop`,
otherwise -1.
>>> df1 = spark.createDataFrame([(-2, 2)], ('C1', 'C2'))
>>> df1.select(seq... | Generate a sequence of integers from `start` to `stop`, incrementing by `step`.
If `step` is not set, incrementing by 1 if `start` is less than or equal to `stop`,
otherwise -1.
>>> df1 = spark.createDataFrame([(-2, 2)], ('C1', 'C2'))
>>> df1.select(sequence('C1', 'C2').alias('r')).collect()
[Row(r... |
def parse(self, parser):
"""Main method to render data into the template."""
lineno = next(parser.stream).lineno
if parser.stream.skip_if('name:short'):
parser.stream.skip(1)
short = parser.parse_expression()
else:
short = nodes.Const(False)
... | Main method to render data into the template. |
def remove_rally(self, key):
'''remove a rally point'''
a = key.split(' ')
if a[0] != 'Rally' or len(a) != 2:
print("Bad rally object %s" % key)
return
i = int(a[1])
self.mpstate.functions.process_stdin('rally remove %u' % i) | remove a rally point |
def c32checkDecode(c32data):
"""
>>> c32checkDecode('P2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKNRV9EJ7')
(22, 'a46ff88886c2ef9762d970b4d2c63678835bd39d')
>>> c32checkDecode('02J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKPVKG2CE')
(0, 'a46ff88886c2ef9762d970b4d2c63678835bd39d')
>>> c32checkDecode('Z2J6ZY48GV1EZ5V2V5RB... | >>> c32checkDecode('P2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKNRV9EJ7')
(22, 'a46ff88886c2ef9762d970b4d2c63678835bd39d')
>>> c32checkDecode('02J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKPVKG2CE')
(0, 'a46ff88886c2ef9762d970b4d2c63678835bd39d')
>>> c32checkDecode('Z2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQ9H6DPR')
(31, 'a46ff888... |
def delete_view(self, request, object_id, extra_context=None):
"""
Overrides the default to enable redirecting to the directory view after
deletion of a image.
we need to fetch the object and find out who the parent is
before super, because super will delete the object and make ... | Overrides the default to enable redirecting to the directory view after
deletion of a image.
we need to fetch the object and find out who the parent is
before super, because super will delete the object and make it
impossible to find out the parent folder to redirect to. |
def _make_request(self, method, params):
"""Make request to API endpoint
Note: Ignoring SSL cert validation due to intermittent failures
http://requests.readthedocs.org/en/latest/user/advanced/#ssl-cert-verification
"""
if self.blocked_until is not None and \
dat... | Make request to API endpoint
Note: Ignoring SSL cert validation due to intermittent failures
http://requests.readthedocs.org/en/latest/user/advanced/#ssl-cert-verification |
def get_qpimage(self, idx=0):
"""Return background-corrected QPImage"""
if self._bgdata:
# The user has explicitly chosen different background data
# using `get_qpimage_raw`.
qpi = super(SingleHdf5Qpimage, self).get_qpimage()
else:
# We can use the... | Return background-corrected QPImage |
def _equaBreaks(self, orbit_index_period=24.):
"""Determine where breaks in an equatorial satellite orbit occur.
Looks for negative gradients in local time (or longitude) as well as
breaks in UT.
Parameters
----------
orbit_index_period : float
The change in... | Determine where breaks in an equatorial satellite orbit occur.
Looks for negative gradients in local time (or longitude) as well as
breaks in UT.
Parameters
----------
orbit_index_period : float
The change in value of supplied index parameter for a single orbit |
def gen_psi(self, x):
"""Generates the activity of the basis functions for a given
canonical system rollout.
x float, array: the canonical system state or path
"""
if isinstance(x, np.ndarray):
x = x[:,None]
return np.exp(-self.h * (x - self.c)*... | Generates the activity of the basis functions for a given
canonical system rollout.
x float, array: the canonical system state or path |
def import_single_vpn_path_to_all_vrfs(self, vpn_path, path_rts=None):
"""Imports *vpn_path* to qualifying VRF tables.
Import RTs of VRF table is matched with RTs from *vpn4_path* and if we
have any common RTs we import the path into VRF.
"""
LOG.debug('Importing path %s to qual... | Imports *vpn_path* to qualifying VRF tables.
Import RTs of VRF table is matched with RTs from *vpn4_path* and if we
have any common RTs we import the path into VRF. |
def qsub(script, job_name, dryrun=False, *args, **kwargs):
"""Submit a job via qsub."""
print("Preparing job script...")
job_string = gen_job(script=script, job_name=job_name, *args, **kwargs)
env = os.environ.copy()
if dryrun:
print(
"This is a dry run! Here is the generated job... | Submit a job via qsub. |
def collapse(self, remove=False):
"""
Move all ``sequence_ids`` in the subtree below this node to this node.
If ``remove`` is True, nodes below this one are deleted from the
taxonomy.
"""
descendants = iter(self)
# Skip this node
assert next(descendants) ... | Move all ``sequence_ids`` in the subtree below this node to this node.
If ``remove`` is True, nodes below this one are deleted from the
taxonomy. |
def _cwl_workflow_template(inputs, top_level=False):
"""Retrieve CWL inputs shared amongst different workflows.
"""
ready_inputs = []
for inp in inputs:
cur_inp = copy.deepcopy(inp)
for attr in ["source", "valueFrom", "wf_duplicate"]:
cur_inp.pop(attr, None)
if top_le... | Retrieve CWL inputs shared amongst different workflows. |
def values(self):
"""Return a list of all the message's header values.
These will be sorted in the order they appeared in the original
message, or were added to the message, and may contain duplicates.
Any fields deleted and re-inserted are always appended to the header
list.
... | Return a list of all the message's header values.
These will be sorted in the order they appeared in the original
message, or were added to the message, and may contain duplicates.
Any fields deleted and re-inserted are always appended to the header
list. |
def _board_from_game_image(self, game_image):
"""Return a board object matching the board in the game image.
Return None if any tiles are not identified.
"""
# board image
board_rect = self._board_tools['board_region'].region_in(game_image)
t, l, b, r = board_rect
... | Return a board object matching the board in the game image.
Return None if any tiles are not identified. |
def script_and_notebook_to_rst(spth, npth, rpth):
"""
Convert a script and the corresponding executed notebook to rst.
The script is converted to notebook format *without* replacement
of sphinx cross-references with links to online docs, and the
resulting markdown cells are inserted into the execute... | Convert a script and the corresponding executed notebook to rst.
The script is converted to notebook format *without* replacement
of sphinx cross-references with links to online docs, and the
resulting markdown cells are inserted into the executed notebook,
which is then converted to rst. |
def inasafe_analysis_summary_field_value(field, feature, parent):
"""Retrieve a value from a field in the analysis summary layer.
e.g. inasafe_analysis_summary_field_value('total_not_exposed') -> 3
"""
_ = feature, parent # NOQA
project_context_scope = QgsExpressionContextUtils.projectScope(
... | Retrieve a value from a field in the analysis summary layer.
e.g. inasafe_analysis_summary_field_value('total_not_exposed') -> 3 |
def forward(self, x, **kwargs):
"""
Perform a forward pass through the network.
The forward pass in recursive som is based on a combination between
the activation in the last time-step and the current time-step.
Parameters
----------
x : numpy array
... | Perform a forward pass through the network.
The forward pass in recursive som is based on a combination between
the activation in the last time-step and the current time-step.
Parameters
----------
x : numpy array
The input data.
prev_activation : numpy arra... |
def pos3(self):
''' Use pos-sc1-sc2 as POS '''
parts = [self.pos]
if self.sc1 and self.sc1 != '*':
parts.append(self.sc1)
if self.sc2 and self.sc2 != '*':
parts.append(self.sc2)
return '-'.join(parts) | Use pos-sc1-sc2 as POS |
def search_individuals(self, dataset_id, name=None):
"""
Returns an iterator over the Individuals fulfilling the specified
conditions.
:param str dataset_id: The dataset to search within.
:param str name: Only Individuals matching the specified name will
be returned.... | Returns an iterator over the Individuals fulfilling the specified
conditions.
:param str dataset_id: The dataset to search within.
:param str name: Only Individuals matching the specified name will
be returned.
:return: An iterator over the :class:`ga4gh.protocol.Biosample`
... |
def _set_apply_exp_dscp_map_name(self, v, load=False):
"""
Setter method for apply_exp_dscp_map_name, mapped from YANG variable /qos_mpls/map_apply/apply_exp_dscp_map_name (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_apply_exp_dscp_map_name is considered a... | Setter method for apply_exp_dscp_map_name, mapped from YANG variable /qos_mpls/map_apply/apply_exp_dscp_map_name (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_apply_exp_dscp_map_name is considered as a private
method. Backends looking to populate this variable ... |
def fetch(self, url, listener, chunk_size_bytes=None, timeout_secs=None):
"""Fetches data from the given URL notifying listener of all lifecycle events.
:param string url: the url to GET data from
:param listener: the listener to notify of all download lifecycle events
:param chunk_size_bytes: the chun... | Fetches data from the given URL notifying listener of all lifecycle events.
:param string url: the url to GET data from
:param listener: the listener to notify of all download lifecycle events
:param chunk_size_bytes: the chunk size to use for buffering data, 10 KB by default
:param timeout_secs: the m... |
def add_candidate_peer_endpoints(self, peer_endpoints):
"""Adds candidate endpoints to the list of endpoints to
attempt to peer with.
Args:
peer_endpoints ([str]): A list of public uri's which the
validator can attempt to peer with.
"""
if self._topol... | Adds candidate endpoints to the list of endpoints to
attempt to peer with.
Args:
peer_endpoints ([str]): A list of public uri's which the
validator can attempt to peer with. |
def flatten_dict(x):
"""Flatten a dict
Flatten an arbitrarily nested dict as output by to_dict
.. note::
Keys in the flattened dict may get very long.
Args:
x (dict): Arbitrarily nested dict (maybe resembling a tree) with literal/scalar leaf values
Retu... | Flatten a dict
Flatten an arbitrarily nested dict as output by to_dict
.. note::
Keys in the flattened dict may get very long.
Args:
x (dict): Arbitrarily nested dict (maybe resembling a tree) with literal/scalar leaf values
Returns:
dict: flattened... |
def run(self):
"""Threading callback"""
self.viewing = True
while self.viewing and self._lock.acquire():
try:
line = self._readline()
except:
pass
else:
logger.info(line)
self._lock.release()
... | Threading callback |
def info(self):
"""Delivers some info to you about the class."""
print("Sorry, but I don't have much to share.")
print("This is me:")
print(self)
print("And these are the experiments assigned to me:")
print(self.experiments) | Delivers some info to you about the class. |
def _op_to_matrix(self,
op: Optional[ops.Operation],
qubits: Tuple[ops.Qid, ...]
) -> Optional[np.ndarray]:
"""Determines the effect of an operation on the given qubits.
If the operation is a 1-qubit operation on one of the given qubits,... | Determines the effect of an operation on the given qubits.
If the operation is a 1-qubit operation on one of the given qubits,
or a 2-qubit operation on both of the given qubits, and also the
operation has a known matrix, then a matrix is returned. Otherwise None
is returned.
A... |
def weather_history_at_place(self, name, start=None, end=None):
"""
Queries the OWM Weather API for weather history for the specified location
(eg: "London,uk"). A list of *Weather* objects is returned. It is
possible to query for weather history in a closed time period, whose
bo... | Queries the OWM Weather API for weather history for the specified location
(eg: "London,uk"). A list of *Weather* objects is returned. It is
possible to query for weather history in a closed time period, whose
boundaries can be passed as optional parameters.
:param name: the location's ... |
def _get_sorted_actions_list(self, raw_set):
"""
This returns a list of dictionaries with the actions got in the
raw_set.
:raw_set: is the dict representing a set of rules and conditions.
"""
keys_list = raw_set.keys()
# actions_dicts_l is the final list which wil... | This returns a list of dictionaries with the actions got in the
raw_set.
:raw_set: is the dict representing a set of rules and conditions. |
def CryptProtectData(
data, description=None, optional_entropy=None,
prompt_struct=None, flags=0,
):
"""
Encrypt data
"""
data_in = DATA_BLOB(data)
entropy = DATA_BLOB(optional_entropy) if optional_entropy else None
data_out = DATA_BLOB()
res = _CryptProtectData(
data_in,
description,
entropy,
None, ... | Encrypt data |
def disable_host_flap_detection(self, host):
"""Disable flap detection for a host
Format of the line that triggers function call::
DISABLE_HOST_FLAP_DETECTION;<host_name>
:param host: host to edit
:type host: alignak.objects.host.Host
:return: None
"""
i... | Disable flap detection for a host
Format of the line that triggers function call::
DISABLE_HOST_FLAP_DETECTION;<host_name>
:param host: host to edit
:type host: alignak.objects.host.Host
:return: None |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.