positive stringlengths 100 30.3k | anchor stringlengths 1 15k |
|---|---|
def begin(self, *args, **kwargs):
"""Indicate the beginning of a transaction.
During a transaction, connections won't be transparently
replaced, and all errors will be raised to the application.
If the underlying driver supports this method, it will be called
with the given par... | Indicate the beginning of a transaction.
During a transaction, connections won't be transparently
replaced, and all errors will be raised to the application.
If the underlying driver supports this method, it will be called
with the given parameters (e.g. for distributed transactions). |
def annotate_json(self, text, annotators=None):
"""Return a JSON dict from the CoreNLP server, containing annotations of the text.
:param (str) text: Text to annotate.
:param (list[str]) annotators: a list of annotator names
:return (dict): a dict of annotations
"""
# W... | Return a JSON dict from the CoreNLP server, containing annotations of the text.
:param (str) text: Text to annotate.
:param (list[str]) annotators: a list of annotator names
:return (dict): a dict of annotations |
def do_time(self, params):
"""
\x1b[1mNAME\x1b[0m
time - Measures elapsed seconds after running commands
\x1b[1mSYNOPSIS\x1b[0m
time <cmd1> <cmd2> ... <cmdN>
\x1b[1mEXAMPLES\x1b[0m
> time 'loop 10 0 "create /foo_ bar ephemeral=false sequence=true"'
Took 0.05585 seconds
... | \x1b[1mNAME\x1b[0m
time - Measures elapsed seconds after running commands
\x1b[1mSYNOPSIS\x1b[0m
time <cmd1> <cmd2> ... <cmdN>
\x1b[1mEXAMPLES\x1b[0m
> time 'loop 10 0 "create /foo_ bar ephemeral=false sequence=true"'
Took 0.05585 seconds |
def _parse_tmx(path):
"""Generates examples from TMX file."""
def _get_tuv_lang(tuv):
for k, v in tuv.items():
if k.endswith("}lang"):
return v
raise AssertionError("Language not found in `tuv` attributes.")
def _get_tuv_seg(tuv):
segs = tuv.findall("seg")
assert len(segs) == 1, "In... | Generates examples from TMX file. |
def find_projects(name=None, name_mode='exact', properties=None, tags=None,
level=None, describe=False, explicit_perms=None, region=None,
public=None, created_after=None, created_before=None, billed_to=None,
limit=None, return_handler=False, first_page_size=100, con... | :param name: Name of the project (also see *name_mode*)
:type name: string
:param name_mode: Method by which to interpret the *name* field ("exact": exact match, "glob": use "*" and "?" as wildcards, "regexp": interpret as a regular expression)
:type name_mode: string
:param properties: Properties (key-... |
def encode(self, encoding=None):
r"""Encode into a multihash-encoded digest.
If `encoding` is `None`, a binary digest is produced:
>>> mh = Multihash(0x01, b'TEST')
>>> mh.encode()
b'\x01\x04TEST'
If the name of an `encoding` is specified, it is used to encode the
... | r"""Encode into a multihash-encoded digest.
If `encoding` is `None`, a binary digest is produced:
>>> mh = Multihash(0x01, b'TEST')
>>> mh.encode()
b'\x01\x04TEST'
If the name of an `encoding` is specified, it is used to encode the
binary digest before returning it (se... |
def _parse_dates(self, prop=DATES):
""" Creates and returns a Date Types data structure parsed from the metadata """
return parse_dates(self._xml_tree, self._data_structures[prop]) | Creates and returns a Date Types data structure parsed from the metadata |
def lt(name, value):
'''
Only succeed if the value in the given register location is less than
the given value
USAGE:
.. code-block:: yaml
foo:
check.lt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
... | Only succeed if the value in the given register location is less than
the given value
USAGE:
.. code-block:: yaml
foo:
check.lt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: test.ping
- require:
... |
def get_last(self):
"""
Get the last migration batch.
:rtype: list
"""
query = self.table().where('batch', self.get_last_batch_number())
return query.order_by('migration', 'desc').get() | Get the last migration batch.
:rtype: list |
def find_and_union_paths(self, node_source, nodes_target):
""" Determines shortest paths from `node_source` to all nodes in `node_target` in _graph using find_path().
The branches of all paths are stored in a set - the result is a list of unique branches.
Args
----
node_source:... | Determines shortest paths from `node_source` to all nodes in `node_target` in _graph using find_path().
The branches of all paths are stored in a set - the result is a list of unique branches.
Args
----
node_source: GridDing0
source node, member of _graph
node_targe... |
def gc(cn, ns=None, lo=None, iq=None, ico=None, pl=None):
"""
This function is a wrapper for
:meth:`~pywbem.WBEMConnection.GetClass`.
Retrieve a class.
Parameters:
cn (:term:`string` or :class:`~pywbem.CIMClassName`):
Name of the class to be retrieved (case independent).
... | This function is a wrapper for
:meth:`~pywbem.WBEMConnection.GetClass`.
Retrieve a class.
Parameters:
cn (:term:`string` or :class:`~pywbem.CIMClassName`):
Name of the class to be retrieved (case independent).
If specified as a `CIMClassName` object, its `host` attribute will b... |
def create_zones(self, add_zones):
"""Create instances of additional zones for the receiver."""
for zone, zname in add_zones.items():
# Name either set explicitly or name of Main Zone with suffix
zonename = "{} {}".format(self._name, zone) if (
zname is None) else... | Create instances of additional zones for the receiver. |
def show_firmware_version_output_show_firmware_version_control_processor_memory(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_firmware_version = ET.Element("show_firmware_version")
config = show_firmware_version
output = ET.SubElement(show... | Auto Generated Code |
def register_user(self, user):
"""For new users, append their information into the dictionaries.
Args:
user (User): User.
"""
self.users[user.index] = {'known_items': set()}
self.n_user += 1 | For new users, append their information into the dictionaries.
Args:
user (User): User. |
def hello_world():
"""
Sends a 'hello world' message and then reads it from the queue.
"""
# connect to the RabbitMQ broker
connection = yield from asynqp.connect('localhost', 5672, username='guest', password='guest')
# Open a communications channel
channel = yield from connection.open_chan... | Sends a 'hello world' message and then reads it from the queue. |
def load_glove(file):
"""Loads GloVe vectors in numpy array.
Args:
file (str): a path to a glove file.
Return:
dict: a dict of numpy arrays.
"""
model = {}
with open(file, encoding="utf8", errors='ignore') as f:
for line in f:
line = line.split(' ')
... | Loads GloVe vectors in numpy array.
Args:
file (str): a path to a glove file.
Return:
dict: a dict of numpy arrays. |
def reset_component(self, component):
""" Unset component in this URI
:param component: component name (or component type) to reset
:return: None
"""
if isinstance(component, str) is True:
component = WURI.Component(component)
self.__components[component] = None | Unset component in this URI
:param component: component name (or component type) to reset
:return: None |
def remove(self, *widgets):
'''
Remove @widgets from the blitting hand of the Container(). Each arg
must be a Widget(), a fellow Container(), or an iterable. Else, things
get ugly...
'''
for w in widgets:
if w in self.widgets:
self.widgets.re... | Remove @widgets from the blitting hand of the Container(). Each arg
must be a Widget(), a fellow Container(), or an iterable. Else, things
get ugly... |
def _class_info(self, classes, show_builtins, private_bases, parts, aliases, top_classes):
# type: (List[Any], bool, bool, int, Optional[Dict[unicode, unicode]], List[Any]) -> List[Tuple[unicode, unicode, List[unicode], unicode]] # NOQA
"""Return name and bases for all classes that are ancestors of
... | Return name and bases for all classes that are ancestors of
*classes*.
*parts* gives the number of dotted name parts that is removed from the
displayed node names.
*top_classes* gives the name(s) of the top most ancestor class to traverse
to. Multiple names can be specified sep... |
def getlevel(self, threshold):
"""
Returns all clusters with a maximum distance of *threshold* in between
each other
:param threshold: the maximum distance between clusters.
See :py:meth:`~cluster.cluster.Cluster.getlevel`
"""
# if it's not worth clustering, ju... | Returns all clusters with a maximum distance of *threshold* in between
each other
:param threshold: the maximum distance between clusters.
See :py:meth:`~cluster.cluster.Cluster.getlevel` |
def entry_at(cls, filepath, index):
""":return: RefLogEntry at the given index
:param filepath: full path to the index file from which to read the entry
:param index: python list compatible index, i.e. it may be negative to
specify an entry counted from the end of the list
:... | :return: RefLogEntry at the given index
:param filepath: full path to the index file from which to read the entry
:param index: python list compatible index, i.e. it may be negative to
specify an entry counted from the end of the list
:raise IndexError: If the entry didn't exist
... |
def source_getattr():
"""
Creates a getter that will drop the current value
and retrieve the source's attribute with the context key as name.
"""
def source_getattr(_value, context, **_params):
value = getattr(context["model"].source, context["key"])
return _attr(value)
return ... | Creates a getter that will drop the current value
and retrieve the source's attribute with the context key as name. |
def compute_dual_rmetric(self,Ynew=None):
"""Helper function to calculate the """
usedY = self.Y if Ynew is None else Ynew
rieman_metric = RiemannMetric(usedY, self.laplacian_matrix)
return rieman_metric.get_dual_rmetric() | Helper function to calculate the |
def start(self):
"""Initiate the download."""
log.info("Sending tftp download request to %s" % self.host)
log.info(" filename -> %s" % self.file_to_transfer)
log.info(" options -> %s" % self.options)
self.metrics.start_time = time.time()
log.debug("Set metrics.star... | Initiate the download. |
def simple_spend_p2sh(all_from_pubkeys, from_privkeys_to_use, to_address, to_satoshis,
change_address=None, min_confirmations=0, api_key=None, coin_symbol='btc'):
'''
Simple method to spend from a p2sh address.
all_from_pubkeys is a list of *all* pubkeys for the address in question.
from_privk... | Simple method to spend from a p2sh address.
all_from_pubkeys is a list of *all* pubkeys for the address in question.
from_privkeys_to_use is a list of all privkeys that will be used to sign the tx (and no more).
If the address is a 2-of-3 multisig and you supply 1 (or 3) from_privkeys_to_use this will bre... |
def netmiko_file_transfer(
task: Task, source_file: str, dest_file: str, **kwargs: Any
) -> Result:
"""
Execute Netmiko file_transfer method
Arguments:
source_file: Source file.
dest_file: Destination file.
kwargs: Additional arguments to pass to file_transfer
Returns:
... | Execute Netmiko file_transfer method
Arguments:
source_file: Source file.
dest_file: Destination file.
kwargs: Additional arguments to pass to file_transfer
Returns:
Result object with the following attributes set:
* result (``bool``): file exists and MD5 is valid
... |
def resolve_node_modules(self):
'import the modules specified in init'
if not self.resolved_node_modules:
try:
self.resolved_node_modules = [
importlib.import_module(mod, self.node_package)
for mod in self.node_modules
]... | import the modules specified in init |
def choice(self, message, choices=None, select=None, cancel=None,
msg_position='above', choices_to_return=None):
"""
prompt user to make a choice.
:param message: string to display before list of choices
:type message: unicode
:param choices: dict of possible choi... | prompt user to make a choice.
:param message: string to display before list of choices
:type message: unicode
:param choices: dict of possible choices
:type choices: dict: keymap->choice (both str)
:param choices_to_return: dict of possible choices to return for the
... |
def clean_axis(axis):
"""Remove ticks, tick labels, and frame from axis"""
axis.get_xaxis().set_ticks([])
axis.get_yaxis().set_ticks([])
for spine in list(axis.spines.values()):
spine.set_visible(False) | Remove ticks, tick labels, and frame from axis |
def get_dom(self) -> str:
""" Retrieves the current value of the DOM for the step """
if self.is_running:
return self.dumps()
if self.dom is not None:
return self.dom
dom = self.dumps()
self.dom = dom
return dom | Retrieves the current value of the DOM for the step |
def tab(self, output):
"""Output data in excel-compatible tab-delimited format"""
import csv
csvwriter = csv.writer(self.outfile, dialect=csv.excel_tab)
csvwriter.writerows(output) | Output data in excel-compatible tab-delimited format |
def interact_GxG(pheno,snps1,snps2=None,K=None,covs=None):
"""
Epistasis test between two sets of SNPs
Args:
pheno: [N x 1] SP.array of 1 phenotype for N individuals
snps1: [N x S1] SP.array of S1 SNPs for N individuals
snps2: [N x S2] SP.array of S2 SNPs for N individuals
... | Epistasis test between two sets of SNPs
Args:
pheno: [N x 1] SP.array of 1 phenotype for N individuals
snps1: [N x S1] SP.array of S1 SNPs for N individuals
snps2: [N x S2] SP.array of S2 SNPs for N individuals
K: [N x N] SP.array of LMM-covariance/kinship koefficients (opti... |
def get_page(self, form):
'''Get the requested page'''
page_size = form.cleaned_data['iDisplayLength']
start_index = form.cleaned_data['iDisplayStart']
paginator = Paginator(self.object_list, page_size)
num_page = (start_index / page_size) + 1
return paginator.page(num_pa... | Get the requested page |
def attributes(cls, create=False, extra=None):
"""Build a dict of attribute values, respecting declaration order.
The process is:
- Handle 'orderless' attributes, overriding defaults with provided
kwargs when applicable
- Handle ordered attributes, overriding them with provi... | Build a dict of attribute values, respecting declaration order.
The process is:
- Handle 'orderless' attributes, overriding defaults with provided
kwargs when applicable
- Handle ordered attributes, overriding them with provided kwargs when
applicable; the current list o... |
def read(self, params, args, data):
"""Modifies the parameters and adds metadata for read results."""
result_count = None
result_links = None
if params is None:
params = []
if args:
args = args.copy()
else:
args = {}
ctx = sel... | Modifies the parameters and adds metadata for read results. |
def _get_flags(osm_obj):
"""Create element independent flags output.
Args:
osm_obj (Node): Object with OSM-style metadata
Returns:
list: Human readable flags output
"""
flags = []
if osm_obj.visible:
flags.append('visible')
if osm_obj.user:
flags.append('use... | Create element independent flags output.
Args:
osm_obj (Node): Object with OSM-style metadata
Returns:
list: Human readable flags output |
def deleteNode(self, networkId, nodeId, verbose=None):
"""
Deletes the node specified by the `nodeId` and `networkId` parameters.
:param networkId: SUID of the network containing the node.
:param nodeId: SUID of the node
:param verbose: print more
:returns: default: suc... | Deletes the node specified by the `nodeId` and `networkId` parameters.
:param networkId: SUID of the network containing the node.
:param nodeId: SUID of the node
:param verbose: print more
:returns: default: successful operation |
def make_cutter(self):
"""
Create solid to subtract from material to make way for the fastener's
head (just the head)
"""
return cadquery.Workplane('XY') \
.circle(self.access_diameter / 2) \
.extrude(self.access_height) | Create solid to subtract from material to make way for the fastener's
head (just the head) |
def mgz_to_nifti(filename,prefix=None,gzip=True):
'''Convert ``filename`` to a NIFTI file using ``mri_convert``'''
setup_freesurfer()
if prefix==None:
prefix = nl.prefix(filename) + '.nii'
if gzip and not prefix.endswith('.gz'):
prefix += '.gz'
nl.run([os.path.join(freesurfer_home,'b... | Convert ``filename`` to a NIFTI file using ``mri_convert`` |
def read(self, entity=None, attrs=None, ignore=None, params=None):
"""Get information about the current entity.
1. Create a new entity of type ``type(self)``.
2. Call :meth:`read_json` and capture the response.
3. Populate the entity with the response.
4. Return the entity.
... | Get information about the current entity.
1. Create a new entity of type ``type(self)``.
2. Call :meth:`read_json` and capture the response.
3. Populate the entity with the response.
4. Return the entity.
Step one is skipped if the ``entity`` argument is specified. Step two
... |
def transform(self, X, y=None):
"""
Transform input `X`.
Note: all imputations should have a `fit_transform` method,
but only some (like IterativeImputer) also support inductive mode
using `fit` or `fit_transform` on `X_train` and then `transform`
on new `X_test`.
... | Transform input `X`.
Note: all imputations should have a `fit_transform` method,
but only some (like IterativeImputer) also support inductive mode
using `fit` or `fit_transform` on `X_train` and then `transform`
on new `X_test`. |
def publish(self, topic, schema=None, name=None):
"""
Publish this stream on a topic for other Streams applications to subscribe to.
A Streams application may publish a stream to allow other
Streams applications to subscribe to it. A subscriber
matches a publisher if the topic an... | Publish this stream on a topic for other Streams applications to subscribe to.
A Streams application may publish a stream to allow other
Streams applications to subscribe to it. A subscriber
matches a publisher if the topic and schema match.
By default a stream is published using its sc... |
def getRenderModelName(self, unRenderModelIndex, pchRenderModelName, unRenderModelNameLen):
"""
Use this to get the names of available render models. Index does not correlate to a tracked device index, but
is only used for iterating over all available render models. If the index is out of rang... | Use this to get the names of available render models. Index does not correlate to a tracked device index, but
is only used for iterating over all available render models. If the index is out of range, this function will return 0.
Otherwise, it will return the size of the buffer required for the name. |
async def send_voice(self, chat_id: typing.Union[base.Integer, base.String],
voice: typing.Union[base.InputFile, base.String],
caption: typing.Union[base.String, None] = None,
parse_mode: typing.Union[base.String, None] = None,
... | Use this method to send audio files, if you want Telegram clients to display the file
as a playable voice message.
For this to work, your audio must be in an .ogg file encoded with OPUS
(other formats may be sent as Audio or Document).
Source: https://core.telegram.org/bots/api#sendvoi... |
def abu_profile(self,ixaxis='mass',isos=None,ifig=None,fname=None,logy=False,
colourblind=False):
'''
Plot common abundances as a function of either mass coordiate or radius.
Parameters
----------
ixaxis : string, optional
'mass', 'logradius' or ... | Plot common abundances as a function of either mass coordiate or radius.
Parameters
----------
ixaxis : string, optional
'mass', 'logradius' or 'radius'
The default value is 'mass'
isos : list, optional
list of isos to plot, i.e. ['h1','he4','c12'] f... |
def remove_common_offset(arr):
"""Given an array of data, removes a common offset > 1000, returning the
removed value.
"""
offset = 0
isneg = (arr <= 0).all()
# make sure all values have the same sign
if isneg or (arr >= 0).all():
# only remove offset if the minimum and maximum value... | Given an array of data, removes a common offset > 1000, returning the
removed value. |
def ahrs_encode(self, omegaIx, omegaIy, omegaIz, accel_weight, renorm_val, error_rp, error_yaw):
'''
Status of DCM attitude estimator
omegaIx : X gyro drift estimate rad/s (float)
omegaIy : Y gyro drift estimate rad/s (... | Status of DCM attitude estimator
omegaIx : X gyro drift estimate rad/s (float)
omegaIy : Y gyro drift estimate rad/s (float)
omegaIz : Z gyro drift estimate rad/s (float)
accel_weight : av... |
def _get_shells():
'''
Return the valid shells on this system
'''
start = time.time()
if 'sh.last_shells' in __context__:
if start - __context__['sh.last_shells'] > 5:
__context__['sh.last_shells'] = start
else:
__context__['sh.shells'] = __salt__['cmd.shells'... | Return the valid shells on this system |
def _parse_uri(uri_as_string):
"""
Parse the given URI from a string.
Supported URI schemes are:
* file
* hdfs
* http
* https
* s3
* s3a
* s3n
* s3u
* webhdfs
.s3, s3a and s3n are treated the same way. s3u is s3 but without SSL.
Valid URI ex... | Parse the given URI from a string.
Supported URI schemes are:
* file
* hdfs
* http
* https
* s3
* s3a
* s3n
* s3u
* webhdfs
.s3, s3a and s3n are treated the same way. s3u is s3 but without SSL.
Valid URI examples::
* s3://my_bucket/my_key
... |
def parse_bbt(self, fh):
""" Parse the BioBloom Tools output into a 3D dict """
parsed_data = OrderedDict()
headers = None
for l in fh:
s = l.split("\t")
if headers is None:
headers = s
else:
parsed_data[s[0]] = dict()
... | Parse the BioBloom Tools output into a 3D dict |
def get_smtlib_script_satisfiability(self, extra_constraints=(), extra_variables=()):
"""
Return an smt-lib script that check the satisfiability of the current constraints
:return string: smt-lib script
"""
try:
e_csts = self._solver_backend.convert_list(extra_constr... | Return an smt-lib script that check the satisfiability of the current constraints
:return string: smt-lib script |
def rename(self, name):
"""
Rename this node
:param str name: new name for node
"""
self.update(name='{} node {}'.format(name, self.nodeid)) | Rename this node
:param str name: new name for node |
def open_font(self, name):
"""Open the font identifed by the pattern name and return its
font object. If name does not match any font, None is returned."""
fid = self.display.allocate_resource_id()
ec = error.CatchError(error.BadName)
request.OpenFont(display = self.display,
... | Open the font identifed by the pattern name and return its
font object. If name does not match any font, None is returned. |
def et2lst(et, body, lon, typein, timlen=_default_len_out, ampmlen=_default_len_out):
"""
Given an ephemeris epoch, compute the local solar time for
an object on the surface of a body at a specified longitude.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/et2lst_c.html
:param et: Epoch i... | Given an ephemeris epoch, compute the local solar time for
an object on the surface of a body at a specified longitude.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/et2lst_c.html
:param et: Epoch in seconds past J2000 epoch.
:type et: float
:param body: ID-code of the body of interest.
... |
def latexify(obj, **kwargs):
"""Render an object in LaTeX appropriately.
"""
if hasattr(obj, '__pk_latex__'):
return obj.__pk_latex__(**kwargs)
if isinstance(obj, text_type):
from .unicode_to_latex import unicode_to_latex
return unicode_to_latex(obj)
if isinstance(obj, boo... | Render an object in LaTeX appropriately. |
def runner(fun, arg=None, timeout=5):
'''
Execute a runner on the master and return the data from the runner
function
CLI Example:
.. code-block:: bash
salt publish.runner manage.down
'''
arg = _parse_args(arg)
if 'master_uri' not in __opts__:
return 'No access to mas... | Execute a runner on the master and return the data from the runner
function
CLI Example:
.. code-block:: bash
salt publish.runner manage.down |
def read_config(
config_filepath,
logger=logging.getLogger('ProsperCommon'),
):
"""fetch and parse config file
Args:
config_filepath (str): path to config file. abspath > relpath
logger (:obj:`logging.Logger`): logger to catch error msgs
"""
config_parser = configparse... | fetch and parse config file
Args:
config_filepath (str): path to config file. abspath > relpath
logger (:obj:`logging.Logger`): logger to catch error msgs |
def update(self, other, copy=True, *args, **kwargs):
"""Update this composite model element with other element content.
:param other: element to update with this. Must be the same type of this
or this __contenttype__.
:param bool copy: copy other before updating.
:return: se... | Update this composite model element with other element content.
:param other: element to update with this. Must be the same type of this
or this __contenttype__.
:param bool copy: copy other before updating.
:return: self |
def _channel_loop(detection, template, min_cc, detection_id, interpolate, i,
pre_lag_ccsum=None, detect_chans=0,
horizontal_chans=['E', 'N', '1', '2'], vertical_chans=['Z'],
debug=0):
"""
Inner loop for correlating and assigning picks.
Utility function ... | Inner loop for correlating and assigning picks.
Utility function to take a stream of data for the detected event and write
maximum correlation to absolute time as picks in an obspy.core.event.Event
object.
Only outputs picks for picks above min_cc.
:type detection: obspy.core.stream.Stream
:pa... |
def triangle(rad=0.5):
"""Draw a triangle"""
# half_height = math.sqrt(3) * side / 6
# half_height = side / 2
ctx = _state["ctx"]
side = 3 * rad / math.sqrt(3)
ctx.move_to(0, -rad / 2)
ctx.line_to(-side / 2, -rad / 2)
ctx.line_to(0, rad)
ctx.line_to(side / 2, -rad / 2)
ctx.close_... | Draw a triangle |
def _get_singlekws(skw_matches, spires=False):
"""Get single keywords.
:var skw_matches: dict of {keyword: [info,...]}
:keyword spires: bool, to get the spires output
:return: list of formatted keywords
"""
output = {}
for single_keyword, info in skw_matches:
output[single_keyword.o... | Get single keywords.
:var skw_matches: dict of {keyword: [info,...]}
:keyword spires: bool, to get the spires output
:return: list of formatted keywords |
def render_linked_css(self, css_files: Iterable[str]) -> str:
"""Default method used to render the final css links for the
rendered webpage.
Override this method in a sub-classed controller to change the output.
"""
paths = []
unique_paths = set() # type: Set[str]
... | Default method used to render the final css links for the
rendered webpage.
Override this method in a sub-classed controller to change the output. |
def uddc(udfunc, x, dx):
"""
SPICE private routine intended solely for the support of SPICE
routines. Users should not call this routine directly due to the
volatile nature of this routine.
This routine calculates the derivative of 'udfunc' with respect
to time for 'et', then determines if the ... | SPICE private routine intended solely for the support of SPICE
routines. Users should not call this routine directly due to the
volatile nature of this routine.
This routine calculates the derivative of 'udfunc' with respect
to time for 'et', then determines if the derivative has a
negative value.
... |
def select_nodeids(xmrs, iv=None, label=None, pred=None):
"""
Return the list of matching nodeids in *xmrs*.
Nodeids in *xmrs* match if their corresponding
:class:`~delphin.mrs.components.ElementaryPredication` object
matches its `intrinsic_variable` to *iv*, `label` to *label*,
and `pred` to *... | Return the list of matching nodeids in *xmrs*.
Nodeids in *xmrs* match if their corresponding
:class:`~delphin.mrs.components.ElementaryPredication` object
matches its `intrinsic_variable` to *iv*, `label` to *label*,
and `pred` to *pred*. The *iv*, *label*, and *pred* filters are
ignored if they a... |
def _convert_to_spans(self, tree, start, set, parent = None):
"Convert a tree into spans (X, i, j) and add to a set."
if len(tree) == 3:
# Binary rule.
# Remove unary collapsing.
current = self._remove_vertical_markovization(tree[0]).split("+")
split = s... | Convert a tree into spans (X, i, j) and add to a set. |
def _eq(self, T, P):
"""Procedure for calculate the composition in saturation state
Parameters
----------
T : float
Temperature [K]
P : float
Pressure [MPa]
Returns
-------
Asat : float
Saturation mass fraction of dry ... | Procedure for calculate the composition in saturation state
Parameters
----------
T : float
Temperature [K]
P : float
Pressure [MPa]
Returns
-------
Asat : float
Saturation mass fraction of dry air in humid air [kg/kg] |
def version_option(version=None, *param_decls, **attrs):
"""Adds a ``--version`` option which immediately ends the program
printing out the version number. This is implemented as an eager
option that prints the version and exits the program in the callback.
:param version: the version number to show. ... | Adds a ``--version`` option which immediately ends the program
printing out the version number. This is implemented as an eager
option that prints the version and exits the program in the callback.
:param version: the version number to show. If not provided Click
attempts an auto disc... |
def _freqs_by_chromosome(in_file, params, somatic_info):
"""Retrieve frequencies across each chromosome as inputs to HMM.
"""
freqs = []
coords = []
cur_chrom = None
with pysam.VariantFile(in_file) as bcf_in:
for rec in bcf_in:
if _is_biallelic_snp(rec) and _passes_plus_germl... | Retrieve frequencies across each chromosome as inputs to HMM. |
def fetch(self, is_dl_forced=True):
"""
Fetches data from udp collaboration server,
see top level comments for class for more information
:return:
"""
username = config.get_config()['dbauth']['udp']['user']
password = config.get_config()['dbauth']['udp']['passwor... | Fetches data from udp collaboration server,
see top level comments for class for more information
:return: |
def match(self, other):
"""Returns true iff self (as a pattern) matches other (as a
configuration). Note that this is asymmetric: other is allowed
to have symbols that aren't found in self."""
if len(self) != len(other):
raise ValueError()
for s1, s2 in zip(self, oth... | Returns true iff self (as a pattern) matches other (as a
configuration). Note that this is asymmetric: other is allowed
to have symbols that aren't found in self. |
def getfileversion(self):
"""Get file version info.
Args:
no argument
Returns:
4-element tuple with the following components:
-major version number (int)
-minor version number (int)
-complete library version number (int)
-addit... | Get file version info.
Args:
no argument
Returns:
4-element tuple with the following components:
-major version number (int)
-minor version number (int)
-complete library version number (int)
-additional information (string)
C... |
def atomic_download(handle,
download_fn,
module_dir,
lock_file_timeout_sec=10 * 60):
"""Returns the path to a Module directory for a given TF-Hub Module handle.
Args:
handle: (string) Location of a TF-Hub Module.
download_fn: Callback function tha... | Returns the path to a Module directory for a given TF-Hub Module handle.
Args:
handle: (string) Location of a TF-Hub Module.
download_fn: Callback function that actually performs download. The callback
receives two arguments, handle and the location of a temporary
directory ... |
def legendre_symbol(a, p):
""" Compute the Legendre symbol a|p using
Euler's criterion. p is a prime, a is
relatively prime to p (if p divides
a, then a|p = 0)
Returns 1 if a has a square root modulo
p, -1 otherwise.
"""
ls = pow(a, (p - 1) / 2, p)
return -1 if ls == p - 1 else ls | Compute the Legendre symbol a|p using
Euler's criterion. p is a prime, a is
relatively prime to p (if p divides
a, then a|p = 0)
Returns 1 if a has a square root modulo
p, -1 otherwise. |
def get_getter(cls, prop_name, # @NoSelf
user_getter=None, getter_takes_name=False):
"""This implementation returns the PROP_NAME value if there
exists such property. Otherwise there must exist a logical
getter (user_getter) which the value is taken from. If no
... | This implementation returns the PROP_NAME value if there
exists such property. Otherwise there must exist a logical
getter (user_getter) which the value is taken from. If no
getter is found, None is returned (i.e. the property cannot
be created) |
def open(uri, mode, kerberos=False, user=None, password=None):
"""Implement streamed reader from a web site.
Supports Kerberos and Basic HTTP authentication.
Parameters
----------
url: str
The URL to open.
mode: str
The mode to open using.
kerberos: boolean, optional
... | Implement streamed reader from a web site.
Supports Kerberos and Basic HTTP authentication.
Parameters
----------
url: str
The URL to open.
mode: str
The mode to open using.
kerberos: boolean, optional
If True, will attempt to use the local Kerberos credentials
user... |
def linecol_to_pos(text, line, col):
"""Return the offset of this line and column in text.
Lines are one-based, columns zero-based.
This is how Jedi wants it. Don't ask me why.
"""
nth_newline_offset = 0
for i in range(line - 1):
new_offset = text.find("\n", nth_newline_offset)
... | Return the offset of this line and column in text.
Lines are one-based, columns zero-based.
This is how Jedi wants it. Don't ask me why. |
def function(minargs, maxargs, implicit=False, first=False, convert=None):
"""Function decorator.
minargs -- Minimum number of arguments taken by the function.
maxargs -- Maximum number of arguments taken by the function.
implicit -- True for functions which operate on a nodeset consist... | Function decorator.
minargs -- Minimum number of arguments taken by the function.
maxargs -- Maximum number of arguments taken by the function.
implicit -- True for functions which operate on a nodeset consisting
of the current context node when passed no argument.
... |
def read_turbomole(basis_lines, fname):
'''Reads turbomole-formatted file data and converts it to a dictionary with the
usual BSE fields
Note that the turbomole format does not store all the fields we
have, so some fields are left blank
'''
skipchars = '*#$'
basis_lines = [l for l... | Reads turbomole-formatted file data and converts it to a dictionary with the
usual BSE fields
Note that the turbomole format does not store all the fields we
have, so some fields are left blank |
def write_output(self, data, args=None, filename=None, label=None):
"""Write log data to a log file"""
if args:
if not args.outlog:
return 0
if not filename: filename=args.outlog
lastpath = ''
with open(str(filename), 'w') as output_file:
f... | Write log data to a log file |
def get_last_config_update_time_for_xpaths_output_last_config_update_time_for_xpaths_last_config_update_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_last_config_update_time_for_xpaths = ET.Element("get_last_config_update_time_for_xpaths")
con... | Auto Generated Code |
def ingest(cls, resource, element=None, xpath="ti:citation"):
""" Ingest xml to create a citation
:param resource: XML on which to do xpath
:param element: Element where the citation should be stored
:param xpath: XPath to use to retrieve citation
:return: XmlCtsCitation
... | Ingest xml to create a citation
:param resource: XML on which to do xpath
:param element: Element where the citation should be stored
:param xpath: XPath to use to retrieve citation
:return: XmlCtsCitation |
def get_asset_ddo(self, did):
"""
Retrieve asset ddo for a given did.
:param did: Asset DID string
:return: DDO instance
"""
response = self.requests_session.get(f'{self.url}/{did}').content
if not response:
return {}
try:
parsed_r... | Retrieve asset ddo for a given did.
:param did: Asset DID string
:return: DDO instance |
def _do_analysis_cross_validation(self):
"""
Find the best model (fit) based on cross-valiation (leave one out)
"""
assert len(self.df) < 15, "Cross-validation is not implemented if your sample contains more than 15 datapoints"
# initialization: first model is the mean, but com... | Find the best model (fit) based on cross-valiation (leave one out) |
def create(output_prefix, grid_flux_filename, wavelength_filenames,
clobber=False, grid_flux_filename_format="csv", **kwargs):
"""
Create a new *sick* model from files describing the parameter names, fluxes,
and wavelengths.
"""
if not clobber:
# Check to make sure the output files won'... | Create a new *sick* model from files describing the parameter names, fluxes,
and wavelengths. |
def report_error_event(self, error_report):
"""Report error payload.
:type error_report: dict
:param: error_report:
dict payload of the error report formatted according to
https://cloud.google.com/error-reporting/docs/formatting-error-messages
This object sho... | Report error payload.
:type error_report: dict
:param: error_report:
dict payload of the error report formatted according to
https://cloud.google.com/error-reporting/docs/formatting-error-messages
This object should be built using
:meth:~`google.cloud.err... |
def get_hparams(self, model_hparams=None):
"""Returns problem_hparams."""
if self._hparams is not None:
return self._hparams
if model_hparams is None:
model_hparams = default_model_hparams()
if self._encoders is None:
data_dir = (model_hparams and hasattr(model_hparams, "data_dir") a... | Returns problem_hparams. |
def install():
'''
Install weboob system-wide
'''
tmp_weboob_dir = '/tmp/weboob'
# Check that the directory does not already exists
while (os.path.exists(tmp_weboob_dir)):
tmp_weboob_dir += '1'
# Clone the repository
print 'Fetching sources in temporary dir {}'.format(tmp_w... | Install weboob system-wide |
def BitVecSym(name: str, size: int, annotations: Annotations = None) -> BitVec:
"""Creates a new bit vector with a symbolic value."""
raw = z3.BitVec(name, size)
return BitVec(raw, annotations) | Creates a new bit vector with a symbolic value. |
def initial_bill_date(self):
'''
An estimated initial bill date for an account created today,
based on available plan info.
'''
time_to_start = None
if self.initial_bill_count_unit == 'months':
time_to_start = relativedelta(months=self.initial_bill_co... | An estimated initial bill date for an account created today,
based on available plan info. |
def reset_terminal():
''' Reset the terminal/console screen. (Also aliased to cls.)
Greater than a fullscreen terminal clear, also clears the scrollback
buffer. May expose bugs in dumb terminals.
'''
if os.name == 'nt':
from .windows import cls
cls()
else:
text ... | Reset the terminal/console screen. (Also aliased to cls.)
Greater than a fullscreen terminal clear, also clears the scrollback
buffer. May expose bugs in dumb terminals. |
def filter_params(self, value):
""" return filtering params """
if value is None:
return {}
key = self.target
if self.lookup_type is not None:
key += '__' + self.lookup_type
return { key: value } | return filtering params |
def get_expected_tokens(self, parser, interval_set):
# type: (QuilParser, IntervalSet) -> Iterator
"""
Like the default getExpectedTokens method except that it will fallback to the rule name if the token isn't a
literal. For instance, instead of <INVALID> for integer it will return the ... | Like the default getExpectedTokens method except that it will fallback to the rule name if the token isn't a
literal. For instance, instead of <INVALID> for integer it will return the rule name: INT |
def normal_surface_single(obj, uv, normalize):
""" Evaluates the surface normal vector at the given (u, v) parameter pair.
The output returns a list containing the starting point (i.e. origin) of the vector and the vector itself.
:param obj: input surface
:type obj: abstract.Surface
:param uv: (u,... | Evaluates the surface normal vector at the given (u, v) parameter pair.
The output returns a list containing the starting point (i.e. origin) of the vector and the vector itself.
:param obj: input surface
:type obj: abstract.Surface
:param uv: (u,v) parameter pair
:type uv: list or tuple
:para... |
def set_value(repo_directory, key, value, strict=True):
"""Sets the value of a particular key in the config file. This has no effect when setting to the same value."""
if value is None:
raise ValueError('Argument "value" must not be None.')
# Read values and do nothing if not making any changes
... | Sets the value of a particular key in the config file. This has no effect when setting to the same value. |
def _return_object(self, container, item_name):
"""Helper method to retrieve the object"""
coll = container.get_collection()
for item in coll:
if item.name == item_name:
return item | Helper method to retrieve the object |
def read_exports(self):
"""
Read exports data from a file in .ini format.
:return: A dictionary of exports, mapping an export category to a list
of :class:`ExportEntry` instances describing the individual
export entries.
"""
result = {}
... | Read exports data from a file in .ini format.
:return: A dictionary of exports, mapping an export category to a list
of :class:`ExportEntry` instances describing the individual
export entries. |
def setCurrentSchemaPath(self, path):
"""
Sets the current item based on the inputed column.
:param path | <str>
"""
if not path:
return False
parts = path.split('.')
name = parts[0]
next = parts[1:]
... | Sets the current item based on the inputed column.
:param path | <str> |
def ticket_metrics(self, ticket_id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/ticket_metrics#show-ticket-metrics"
api_path = "/api/v2/tickets/{ticket_id}/metrics.json"
api_path = api_path.format(ticket_id=ticket_id)
return self.call(api_path, **kwargs) | https://developer.zendesk.com/rest_api/docs/core/ticket_metrics#show-ticket-metrics |
def get_by(self, prop, val, raise_exc=False):
'''Retrieve an item from the dictionary with the given metadata
properties. If there is no such item, None will be returned, if there
are multiple such items, the first will be returned.'''
try:
val = self.serialize(val)
... | Retrieve an item from the dictionary with the given metadata
properties. If there is no such item, None will be returned, if there
are multiple such items, the first will be returned. |
def u16le_list_to_byte_list(data):
"""! @brief Convert a halfword array into a byte array"""
byteData = []
for h in data:
byteData.extend([h & 0xff, (h >> 8) & 0xff])
return byteData | ! @brief Convert a halfword array into a byte array |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.