text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def stop(self) -> None:
"""
Stops the running simulation once the current event is done executing.
"""
if self.is_running:
if _logger is not None:
self._log(INFO, "stop", __now=self.now())
self._is_running = False | 0.007018 |
def namingConventionDecorator(self, namingConvention):
"""
:type namingConvention:INamingConvention
"""
def decoratorFunction(cls):
SyntheticClassController(cls).setNamingConvention(namingConvention)
return cls
return decoratorFunction | 0.01 |
def _probe_positions(probe, group):
"""Return the positions of a probe channel group."""
positions = probe['channel_groups'][group]['geometry']
channels = _probe_channels(probe, group)
return np.array([positions[channel] for channel in channels]) | 0.003817 |
def process_action(self, request, queryset):
"""
Publishes the selected objects by passing the value of \
'when' to the object's publish method. The object's \
`purge_archives` method is also called to limit the number \
of old items that we keep around. The action is logged as \... | 0.003896 |
def get(self):
"""Render the List-of-Analyses overview page."""
return self.render(
'index.html',
databench_version=DATABENCH_VERSION,
meta_infos=self.meta_infos(),
**self.info
) | 0.008 |
def _get_whitelist_page_generator(self, start_page=0, page_size=None):
"""
Creates a generator from the |get_whitelist_page| method that returns each successive page.
:param int start_page: The page to start on.
:param int page_size: The size of each page.
:return: The generator... | 0.009501 |
def vtt_formatter(subtitles, padding_before=0, padding_after=0):
"""
Serialize a list of subtitles according to the VTT format, with optional time padding.
"""
text = srt_formatter(subtitles, padding_before, padding_after)
text = 'WEBVTT\n\n' + text.replace(',', '.')
return text | 0.006601 |
def task_id_arg(*args, **kwargs):
"""
This is the `TASK_ID` argument consumed by many Transfer Task operations.
It accept a toggle on whether or not it is required
Usage:
>>> @task_id_option
>>> def command_func(task_id):
>>> ...
or
>>> @task_id_option(required=False)
>>>... | 0.001479 |
def make_id(self):
"""Create a new URL id that is unique to the parent container"""
if self.url_id is None: # Set id only if empty
self.url_id = select([func.coalesce(func.max(self.__class__.url_id + 1), 1)],
self.__class__.parent == self.parent) | 0.013746 |
def customize_lexer_priority(file_name, accuracy, lexer):
"""Customize lexer priority"""
priority = lexer.priority
lexer_name = lexer.name.lower().replace('sharp', '#')
if lexer_name in LANGUAGES:
priority = LANGUAGES[lexer_name]
elif lexer_name == 'matlab':
available_extensions = ... | 0.0012 |
def run_vasp(self, run_dir: PathLike = ".",
vasp_cmd: list = None,
output_file: PathLike = "vasp.out",
err_file: PathLike = "vasp.err"):
"""
Write input files and run VASP.
:param run_dir: Where to write input files and do the run.
:par... | 0.0065 |
async def popHiveKey(self, path):
''' Remove and return the value of a key in the cell default hive '''
perm = ('hive:pop',) + path
self.user.allowed(perm)
return await self.cell.hive.pop(path) | 0.008889 |
def _sanitize_data(self, data):
"""
Some CIF files do not conform to spec. This function corrects
known issues, particular in regards to Springer materials/
Pauling files.
This function is here so that CifParser can assume its
input conforms to spec, simplifying its impl... | 0.001277 |
def sample(self, mu):
"""
Return random samples from this Normal distribution.
Parameters
----------
mu : array-like of shape n_samples or shape (n_simulations, n_samples)
expected values
Returns
-------
random_samples : np.array of same shap... | 0.003623 |
def import_submodules(package_name, *submodules):
"""Import all submodules by package name."""
package = sys.modules[package_name]
return {
name: importlib.import_module(package_name + '.' + name)
for _, name, _ in pkgutil.walk_packages(package.__path__)
if not submodules or name in ... | 0.002976 |
def _steps_to_slices():
"""parse timesteps and snapshots arguments and return slices"""
if not (conf.core.timesteps or conf.core.snapshots):
# default to the last snap
conf.core.timesteps = None
conf.core.snapshots = slice(-1, None, None)
return
elif conf.core.snapshots:
... | 0.001006 |
def lesspager(lines):
"""
Use for streaming writes to a less process
Taken from pydoc.pipepager:
/usr/lib/python2.7/pydoc.py
and
/usr/lib/python3.5/pydoc.py
"""
cmd = "less -S"
if sys.version_info[0] >= 3:
"""Page through text by feeding it to another program."""
impo... | 0.004255 |
def search_cloud_integration_deleted_for_facets(self, **kwargs): # noqa: E501
"""Lists the values of one or more facets over the customer's deleted cloud integrations # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP requ... | 0.001885 |
def _simulate_client(plaintext_password, init_pbkdf2_salt, cnonce, server_challenge):
"""
A implementation of the JavaScript client part.
Needful for finding bugs.
"""
# log.debug("_simulate_client(plaintext_password='%s', init_pbkdf2_salt='%s', cnonce='%s', server_challenge='%s')",
# plaint... | 0.002783 |
def docs(output=DOC_OUTPUT, proj_settings=PROJ_SETTINGS, github=False):
"""Generate API documentation (using Sphinx).
:param output: Output directory.
:param proj_settings: Django project settings to use.
:param github: Convert to GitHub-friendly format?
"""
local("export PYTHONPATH='' && "
... | 0.001795 |
def drop_db(url):
"""Drop specified database
"""
parsed_url = urlparse(url)
db_name = parsed_url.path
db_name = db_name.strip("/")
db = connect("postgresql://" + parsed_url.netloc)
# check that db exists
q = """SELECT 1 as exists
FROM pg_database
WHERE datname = '{d... | 0.001675 |
def _get_new_csv_writers(trans_title, meta_title,
trans_csv_path, meta_csv_path):
"""
Prepare new csv writers, write title rows and return them.
"""
trans_writer = UnicodeWriter(trans_csv_path)
trans_writer.writerow(trans_title)
meta_writer = UnicodeWriter(meta_csv_path... | 0.002525 |
def read(self):
"""
If there is data available to be read from the transport, reads the data and tries to parse it as a protobuf message. If the parsing succeeds, return a protobuf object.
Otherwise, returns None.
"""
if not self.ready_to_read():
return None
... | 0.006961 |
def _X509__asn1date_to_datetime(asn1date):
"""
Converts openssl ASN1_TIME object to python datetime.datetime
"""
bio = Membio()
libcrypto.ASN1_TIME_print(bio.bio, asn1date)
pydate = datetime.strptime(str(bio), "%b %d %H:%M:%S %Y %Z")
return pydate.replace(tzinfo=utc) | 0.006757 |
def add_text_memo(self, memo_text):
"""Set the memo for the transaction to a new :class:`TextMemo
<stellar_base.memo.TextMemo>`.
:param memo_text: The text for the memo to add.
:type memo_text: str, bytes
:return: This builder instance.
"""
memo_text = memo.Text... | 0.005333 |
def free(self):
"""Free the map"""
if self._ptr is None:
return
Gauged.map_free(self.ptr)
SparseMap.ALLOCATIONS -= 1
self._ptr = None | 0.010811 |
def get_allow_repeat_items_metadata(self):
"""get the metadata for allow repeat items"""
metadata = dict(self._allow_repeat_items_metadata)
metadata.update({'existing_id_values': self.my_osid_object_form._my_map['allowRepeatItems']})
return Metadata(**metadata) | 0.010239 |
def main():
""" command line script """
# boilerplate
print("Ontospy " + ontospy.VERSION)
ontospy.get_or_create_home_repo()
ONTOSPY_LOCAL_MODELS = ontospy.get_home_location()
opts, args = parse_options()
sTime = time.time()
# switch dir and start server
startServer(port=DEFAULT_PORT, location=ONTOSPY_LOCAL_M... | 0.036247 |
def get_context_data(self, **kwargs):
""" Returns the context data to provide to the template. """
context = super().get_context_data(**kwargs)
# Insert the considered topic and the associated forum into the context
topic = self.get_topic()
context['topic'] = topic
conte... | 0.004464 |
def activate(self, engine):
"""
Activates the Component.
:param engine: Engine to attach the Component to.
:type engine: QObject
:return: Method success.
:rtype: bool
"""
LOGGER.debug("> Activating '{0}' Component.".format(self.__class__.__name__))
... | 0.006122 |
def predictor(self, (i, j, A, alpha, Bb)):
"Add to chart any rules for B that could help extend this edge."
B = Bb[0]
if B in self.grammar.rules:
for rhs in self.grammar.rewrites_for(B):
self.add_edge([j, j, B, [], rhs]) | 0.007353 |
def init(args=None):
"""Initialize the rabit library with arguments"""
if args is None:
args = []
arr = (ctypes.c_char_p * len(args))()
arr[:] = args
_LIB.RabitInit(len(arr), arr) | 0.004831 |
def verify(self, verifier, consumer_key=None, consumer_secret=None,
access_token=None, access_token_secret=None):
"""
After converting the token into verifier, call this to finalize the
authorization.
"""
# Stored values can be supplied to verify
self.consu... | 0.004299 |
def start_completion(self, buffer_name=None, select_first=False,
select_last=False, insert_common_part=False,
complete_event=None):
"""
Start asynchronous autocompletion of this buffer.
(This will do nothing if a previous completion was still in ... | 0.005533 |
def replace_nones(list_, repl=-1):
r"""
Recursively removes Nones in all lists and sublists and replaces them with
the repl variable
Args:
list_ (list):
repl (obj): replacement value
Returns:
list
CommandLine:
python -m utool.util_list --test-replace_nones
... | 0.001122 |
def do_levmarq(s, param_names, damping=0.1, decrease_damp_factor=10.,
run_length=6, eig_update=True, collect_stats=False, rz_order=0,
run_type=2, **kwargs):
"""
Runs Levenberg-Marquardt optimization on a state.
Convenience wrapper for LMGlobals. Same keyword args, but the defaults
have ... | 0.006032 |
def upload_tree(self, src, dst, ignore=None):
"""Recursively upload a directory tree.
Although similar to shutil.copytree we don't follow symlinks.
"""
names = os.listdir(src)
if ignore is not None:
ignored_names = ignore(src, names)
else:
ignored... | 0.001826 |
def AnalizarRemito(self, ret, archivo=None):
"Extrae el resultado del remito, si existen en la respuesta XML"
if ret:
self.CodRemito = ret.get("codRemito")
self.TipoComprobante = ret.get("tipoComprobante")
self.PuntoEmision = ret.get("puntoEmision")
datos_... | 0.002099 |
def to_source(node, indentation=' ' * 4):
"""Return source code of a given AST."""
if isinstance(node, gast.AST):
node = gast.gast_to_ast(node)
generator = SourceWithCommentGenerator(indentation, False,
astor.string_repr.pretty_string)
generator.visit(node)
generat... | 0.017073 |
def crop(self, doy, depth, lat, lon, var):
""" Crop a subset of the dataset for each var
Given doy, depth, lat and lon, it returns the smallest subset
that still contains the requested coordinates inside it.
It handels special cases like a region around greenwich and
... | 0.003972 |
def extract_variants(pattern):
"""Extract the pattern variants (ie. {foo,bar}baz = foobaz or barbaz)."""
v1, v2 = pattern.find('{'), pattern.find('}')
if v1 > -1 and v2 > v1:
variations = pattern[v1+1:v2].split(',')
variants = [pattern[:v1] + v + pattern[v2+1:] for v in variations]
else:... | 0.002571 |
async def update_websub(self, config, hub):
""" Update WebSub hub to know about this feed """
try:
LOGGER.debug("WebSub: Notifying %s of %s", hub, self.url)
request = await utils.retry_post(
config,
hub,
data={
'... | 0.003386 |
def check_mod_enabled(mod):
'''
Checks to see if the specific mod symlink is in /etc/apache2/mods-enabled.
This will only be functional on Debian-based operating systems (Ubuntu,
Mint, etc).
CLI Examples:
.. code-block:: bash
salt '*' apache.check_mod_enabled status
salt '*' ... | 0.001603 |
def clear_numeric_score_increment(self):
"""Clears the numeric score increment.
raise: NoAccess - ``Metadata.isRequired()`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for ... | 0.006182 |
def QA_util_getBetweenQuarter(begin_date, end_date):
"""
#加上每季度的起始日期、结束日期
"""
quarter_list = {}
month_list = QA_util_getBetweenMonth(begin_date, end_date)
for value in month_list:
tempvalue = value.split("-")
year = tempvalue[0]
if tempvalue[1] in ['01', '02', '03']:
... | 0.001245 |
def ServiceWorker_skipWaiting(self, scopeURL):
"""
Function path: ServiceWorker.skipWaiting
Domain: ServiceWorker
Method name: skipWaiting
Parameters:
Required arguments:
'scopeURL' (type: string) -> No description
No return value.
"""
assert isinstance(scopeURL, (str,)
), "Argu... | 0.051429 |
def _to_dict(objects):
'''
Potentially interprets a string as JSON for usage with mongo
'''
try:
if isinstance(objects, six.string_types):
objects = salt.utils.json.loads(objects)
except ValueError as err:
log.error("Could not parse objects: %s", err)
raise err
... | 0.002967 |
def start_charge(self):
"""Start charging the Tesla Vehicle."""
if not self.__charger_state:
data = self._controller.command(self._id, 'charge_start',
wake_if_asleep=True)
if data and data['response']['result']:
self.__c... | 0.005115 |
def _write_textfile(filename, text):
"""
Write `text` into file `filename`. If the target directory does
not exist, create it.
"""
dirname = os.path.dirname(filename)
if not os.path.exists(dirname):
os.makedirs(dirname)
outf = open(filename, 'w')
outf.write(text)
outf.close() | 0.003125 |
def _start_drag_row(self, event):
"""Start dragging a row"""
self._dragged_row = self.identify_row(event.y) # identify dragged row
bbox = self.bbox(self._dragged_row)
self._dy = bbox[1] - event.y # distance between cursor and row upper border
self._dragged_row_y = bbox[1] # y ... | 0.002974 |
def clear_scroll(self, scroll_id, params=None):
"""
Clear the scroll request created by specifying the scroll parameter to
search.
`<http://www.elasticsearch.org/guide/reference/api/search/scroll/>`_
:arg scroll_id: The scroll ID or a list of scroll IDs
"""
if no... | 0.002162 |
def _set_client_pw(self, v, load=False):
"""
Setter method for client_pw, mapped from YANG variable /cluster/client_pw (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_client_pw is considered as a private
method. Backends looking to populate this variable ... | 0.005727 |
def write(self, buffer_size, window_size, x, y, p, address, data):
"""Write a bytestring to an address in memory.
..note::
This method is included here to maintain API compatibility with an
`alternative implementation of SCP
<https://github.com/project-rig/rig-scp>`_... | 0.001029 |
def wpad_search_urls(subdomain_or_host, fld):
"""
Generate URLs from which to look for a PAC file, based on the subdomain and TLD parts of
a fully-qualified host name.
:param str subdomain_or_host: Subdomain portion of the fully-qualified host name.
For foo.bar.example.com, this is foo.ba... | 0.004711 |
def norm_join(prefix, suffix):
"""
Join ``prefix`` and ``suffix`` paths
and return the resulting path, normalized.
:param string prefix: the prefix path
:param string suffix: the suffix path
:rtype: string
"""
if (prefix is None) and (suffix is None):
return "."
if prefix is... | 0.002053 |
def signable(self, request, authheaders):
"""Creates the signable string for a request and returns it.
Keyword arguments:
request -- A request object which can be consumed by this API.
authheaders -- A string-indexable object which contains the headers appropriate for this signature ver... | 0.004153 |
def _ReadAppJsonFile(self, relative_path):
"""Reads JSON file from an application directory.
Args:
relative_path: file name relative to application root directory.
Returns:
Parsed JSON data or None if the file does not exist, can't be read or
not a valid JSON file.
"""
try:
... | 0.006479 |
def mesh_axis_to_cumprod(self, tensor_shape):
"""For each mesh axis, give the product of previous tensor axes.
Args:
tensor_shape: Shape.
Returns:
list with length self.ndims where each element is an integer or None.
"""
tensor_layout = self.tensor_layout(tensor_shape)
ma2ta = tens... | 0.002119 |
def blend_line(messages, blend_combos=None):
"""
Given a list of messages on the same line, blend them together so that we
end up with one message per actual problem. Note that we can still return
more than one message here if there are two or more different errors for
the line.
"""
blend_co... | 0.002435 |
def find_slave_widgets(self,tab):
"""return all the frontends that do not own the kernel attached to the given widget/tab.
Only find frontends owned by the current application. Selection
based on connection file of the kernel.
This function does the conversion tabNumber/wid... | 0.0104 |
def fail(self, message, status=500, **kw):
"""Set a JSON error object and a status to the response
"""
self.request.response.setStatus(status)
result = {"success": False, "errors": message, "status": status}
result.update(kw)
return result | 0.006969 |
def get_cloud_service(self, cloud_service_id):
'''
The Get Cloud Service operation gets all the resources (job collections)
in the cloud service.
cloud_service_id:
The cloud service id
'''
_validate_not_none('cloud_service_id', cloud_service_id)
path ... | 0.007109 |
def printHistogram(data, bins=10, height=10, logscale=False, minbin=0,
horizontal=False, char=u"\U00002589",
c=None, bold=True, title='Histogram'):
"""
Ascii histogram printing.
:param int bins: number of histogram bins
:param int height: height of the histogram in... | 0.004101 |
def _ReadFileEntry(self, file_object, file_offset):
"""Reads a file entry.
Args:
file_object (FileIO): file-like object.
file_offset (int): offset of the data relative from the start of
the file-like object.
Returns:
CPIOArchiveFileEntry: a file entry.
Raises:
FileFo... | 0.006601 |
def to_etree(self):
"""
creates an etree element of a ``SaltLabel`` that mimicks a SaltXMI
<labels> element
"""
attribs = {
'{{{pre}}}type'.format(pre=NAMESPACES['xsi']): self.xsi_type,
'namespace': self.namespace, 'name': self.name,
'value': s... | 0.00361 |
def trace_function(module, function, tracer=tracer):
"""
Traces given module function using given tracer.
:param module: Module of the function.
:type module: object
:param function: Function to trace.
:type function: object
:param tracer: Tracer.
:type tracer: object
:return: Defin... | 0.001698 |
def predict_size_distribution_component_models(self, model_names, input_columns, output_columns, metadata_cols,
data_mode="forecast", location=6):
"""
Make predictions using fitted size distribution models.
Args:
model_names: Name of... | 0.005308 |
def get_raw_tag_data(filename):
"Return the ID3 tag in FILENAME as a raw byte string."
with open(filename, "rb") as file:
try:
(cls, offset, length) = stagger.tags.detect_tag(file)
except stagger.NoTagError:
return bytes()
file.seek(offset)
return file.rea... | 0.00304 |
def extract_key_values(array_value, separators=(';', ',', ':'), **kwargs):
"""Serialize array of objects with simple key-values
"""
items_sep, fields_sep, keys_sep = separators
return items_sep.join(fields_sep.join(keys_sep.join(x) for x in sorted(it.items()))
for it in array_v... | 0.006154 |
def setReflexAnalysisOf(self, analysis):
"""Sets the analysis that has been reflexed in order to create this
one, but if the analysis is the same as self, do nothing.
:param analysis: an analysis object or UID
"""
if not analysis or analysis.UID() == self.UID():
pass
... | 0.005013 |
def build_lattice(self, x):
""" Construct the list of nodes and edges for input features. """
I, J, _ = x.shape
lattice = self._subset_independent_lattice((I, J))
return lattice | 0.009569 |
def get_contradictory_pairs(graph: BELGraph) -> Iterable[Tuple[BaseEntity, BaseEntity]]:
"""Iterates over contradictory node pairs in the graph based on their causal relationships
:return: An iterator over (source, target) node pairs that have contradictory causal edges
"""
for u, v in graph.edges(... | 0.012723 |
def set_sqlite_pragma(dbapi_connection, connection_record):
"""Allows foreign keys to work in sqlite."""
import sqlite3
if dbapi_connection.__class__ is sqlite3.Connection:
cursor = dbapi_connection.cursor()
cursor.execute("PRAGMA foreign_keys=ON")
cursor.close() | 0.003344 |
def side_effect(self, func, *args, **kwargs):
'''
Wrap side effects for spies.
'''
self._spy_side_effect = func
self._spy_side_effect_args = args
self._spy_side_effect_kwargs = kwargs
return self | 0.007968 |
def plot(self, modelx, dlines=False, xmin=None, xmax=None,
ymin=None, ymax=None, **kwargs):
"""Plot the data and model (requires `omega`).
This assumes that `data` is 1D and that `mfunc` takes one argument
that should be treated as the X variable.
"""
import omega ... | 0.003028 |
def _learning_rate_warmup(warmup_steps, warmup_schedule="exp", hparams=None):
"""Learning rate warmup multiplier."""
if not warmup_steps:
return tf.constant(1.)
tf.logging.info("Applying %s learning rate warmup for %d steps",
warmup_schedule, warmup_steps)
warmup_steps = tf.to_float(warm... | 0.012719 |
def abbreviations(text):
"""Remove periods after an abbreviation from a list of known
abbrevations that can be spoken the same without that period. This
prevents having to handle tokenization of that period.
Note:
Could potentially remove the ending period of a sentence.
Note:
Abbr... | 0.001401 |
def tag(self):
""" Return a (deferred) cached Koji tag name for this change. """
name_or_id = self.task.tag
if name_or_id is None:
return defer.succeed(None)
if isinstance(name_or_id, StringType):
return defer.succeed(name_or_id)
if isinstance(name_or_id, ... | 0.004762 |
def sorted_proposals(proposals, scopepref=None, typepref=None):
"""Sort a list of proposals
Return a sorted list of the given `CodeAssistProposal`\s.
`scopepref` can be a list of proposal scopes. Defaults to
``['parameter_keyword', 'local', 'global', 'imported',
'attribute', 'builtin', 'keyword']... | 0.003215 |
def get_instance(self, payload):
"""
Build an instance of ValidationRequestInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.validation_request.ValidationRequestInstance
:rtype: twilio.rest.api.v2010.account.validation_request.V... | 0.01073 |
def set_display_name(self, display_name):
"""Sets a display name.
arg: display_name (string): the new display name
raise: InvalidArgument - ``display_name`` is invalid
raise: NoAccess - ``display_name`` cannot be modified
raise: NullArgument - ``display_name`` is ``null``
... | 0.002774 |
def build_image_here(source, image,
parent_registry=None, target_registries=None, parent_registry_insecure=False,
target_registries_insecure=False, dont_pull_base_image=False, **kwargs):
"""
build image from provided dockerfile (specified by `source`) in current environ... | 0.007599 |
def parse_field(cls: Type[DocumentType], field_name: str, line: str) -> Any:
"""
Parse a document field with regular expression and return the value
:param field_name: Name of the field
:param line: Line string to parse
:return:
"""
try:
match = cls.f... | 0.003546 |
def get_config_value(config_file, section, variable):
""" extracts a config file value """
try:
parser = ConfigParser.SafeConfigParser()
parser.read(config_file)
return parser.get(section, variable)
except:
return None | 0.007634 |
def new_stats_exporter(option):
""" new_stats_exporter returns an exporter
that exports stats to Prometheus.
"""
if option.namespace == "":
raise ValueError("Namespace can not be empty string.")
collector = new_collector(option)
exporter = PrometheusStatsExporter(options=option,
... | 0.002183 |
def register(self, name):
"""
Register a new hook. Not required (see :py:func:`.connect` method)
:param str name: The hook name
:return: Django signal
:rtype: :py:class:`django.dispatch.Signal`
"""
signal = Signal(providing_args=['args', 'kwargs'])
self._... | 0.005479 |
def remove(self, auto_confirm=False, verbose=False):
"""Remove paths in ``self.paths`` with confirmation (unless
``auto_confirm`` is True)."""
if not self.paths:
logger.info(
"Can't uninstall '%s'. No files were found to uninstall.",
self.dist.project... | 0.001914 |
def connect(self):
"""Connect to the Redis server if necessary.
:rtype: :class:`~tornado.concurrent.Future`
:raises: :class:`~tredis.exceptions.ConnectError`
:class:`~tredis.exceptinos.RedisError`
"""
future = concurrent.Future()
if self.connected:
... | 0.003373 |
def trsm(self,B,trans='N'):
r"""
Solves a triangular system of equations with multiple righthand
sides. Computes
.. math::
B &:= L^{-1} B \text{ if trans is 'N'}
B &:= L^{-T} B \text{ if trans is 'T'}
"""
if trans=='N':
cp... | 0.027496 |
def safe_sum(x, alt_value=-np.inf, name=None):
"""Elementwise adds list members, replacing non-finite results with alt_value.
Typically the `alt_value` is chosen so the `MetropolisHastings`
`TransitionKernel` always rejects the proposal.
Args:
x: Python `list` of `Tensors` to elementwise add.
alt_valu... | 0.004601 |
def set_json(self, reason='', new_page=False):
"""Send the JSON from the cache to the usernotes wiki page.
Arguments:
reason: the change reason that will be posted to the wiki changelog
(str)
Raises:
OverflowError if the new JSON data is greater than max_... | 0.001855 |
def getLogicalLines(fp, allowQP=True, findBegin=False):
"""
Iterate through a stream, yielding one logical line at a time.
Because many applications still use vCard 2.1, we have to deal with the
quoted-printable encoding for long lines, as well as the vCard 3.0 and
vCalendar line folding technique,... | 0.002532 |
def parse_block_scalar_indent(token_class):
"""Process indentation spaces in a block scalar."""
def callback(lexer, match, context):
text = match.group()
if context.block_scalar_indent is None:
if len(text) <= max(context.indent, 0):
context.st... | 0.002567 |
def get_params_type(descriptor):
"""
Return the parameters type of a descriptor (e.g (IC)V)
"""
params = descriptor.split(')')[0][1:].split()
if params:
return [param for param in params]
return [] | 0.004367 |
def enrich_pull_requests(self, ocean_backend, enrich_backend, raw_issues_index="github_issues_raw"):
"""
The purpose of this Study is to add additional fields to the pull_requests only index.
Basically to calculate some of the metrics from Code Development under GMD metrics:
https://gith... | 0.004594 |
def prj_add_user(self, *args, **kwargs):
"""Add more users to the project.
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_prj:
return
dialog = UserAdderDialog(project=self.cur_prj)
dialog.exec_()
users = dialog.users
... | 0.004073 |
def convert_old_command_expansions(command):
"""Convert expansions from !OLD! style to {new}."""
command = command.replace("!VERSION!", "{version}")
command = command.replace("!MAJOR_VERSION!", "{version.major}")
command = command.replace("!MINOR_VERSION!", "{version.minor}")
command = command... | 0.001996 |
def _SetPath(self, path):
"""Sets the current path to watch for new events.
This also records the size of the old path, if any. If the size can't be
found, an error is logged.
Args:
path: The full path of the file to watch.
"""
old_path = self._path
if old_path and not io_wrapper.IsC... | 0.004027 |
def _update_careful(self, dict):
"""
Update the option values from an arbitrary dictionary, but only
use keys from dict that already have a corresponding attribute
in self. Any keys in dict without a corresponding attribute
are silently ignored.
"""
for attr in d... | 0.004211 |
def _append_element(self, render_func, pe):
'''
Append a render function and the parameters to pass
an equivilent PathElement, or the PathElement itself.
'''
self._render_funcs.append(render_func)
self._elements.append(pe) | 0.007407 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.