Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
343,400 | def quadratic(a, b, c=None):
if c:
a, b = b / float(a), c / float(a)
t = a / 2.0
r = t**2 - b
if r >= 0:
y1 = sqrt(r)
else:
y1 = cmath.sqrt(r)
y2 = -y1
return y1 - t, y2 - t | x^2 + ax + b = 0 (or ax^2 + bx + c = 0)
By substituting x = y-t and t = a/2, the equation reduces to
y^2 + (b-t^2) = 0
which has easy solution
y = +/- sqrt(t^2-b) |
343,401 | def packets(self):
if not self.get_object_by_type():
for index in range(0, self.read_stats()[]):
XenaCapturePacket(parent=self, index=.format(self.index, index))
return {p.id: p for p in self.get_objects_by_type()} | :return: dictionary {id: object} of all packets.
:rtype: dict of (int, xenamanager.xena_port.XenaCapturePacket) |
343,402 | def register_created(cls, key, image):
if key in cls._stock:
logger.info( + str(key))
cls._stock[key] = {: , : image}
logger.info( % (, key)) | Register an already created image using key |
343,403 | def remove_child(self, child):
if not isinstance(child, Node):
raise TypeError("child must be a Node")
try:
self.children.remove(child); child.parent = None
except:
raise RuntimeError("Attempting to remove non-existent child") | Remove child from ``Node`` object
Args:
``child`` (``Node``): The child to remove |
343,404 | def unique_identities(cls, sh_db):
try:
for unique_identity in api.unique_identities(sh_db):
yield unique_identity
except Exception as e:
logger.debug("Unique identities not returned from SortingHat due to %s", str(e)) | List the unique identities available in SortingHat.
:param sh_db: SortingHat database |
343,405 | def connect(self, *, db=None):
if not self.properties.network:
self.new_state(DeviceFromDB)
else:
try:
name = self.properties.network.read(
"{} device {} objectName".format(
self.properties.address, self... | Attempt to connect to device. If unable, attempt to connect to a controller database
(so the user can use previously saved data). |
343,406 | def is_iterable(obj):
return (
hasattr(obj, "__iter__")
and not isinstance(obj, str)
and not isinstance(obj, tuple)
) | Are we being asked to look up a list of things, instead of a single thing?
We check for the `__iter__` attribute so that this can cover types that
don't have to be known by this module, such as NumPy arrays.
Strings, however, should be considered as atomic values to look up, not
iterables. The same goe... |
343,407 | def encode(self, word, max_length=6, zero_pad=True):
dms = []
if max_length != -1:
max_length = min(max(6, max_length), 64)
else:
max_length = 64
word = unicode_normalize(, text_type(word.upper()))
word = word.replace(, )
... | Return the Daitch-Mokotoff Soundex code for a word.
Parameters
----------
word : str
The word to transform
max_length : int
The length of the code returned (defaults to 6; must be between 6
and 64)
zero_pad : bool
Pad the end of th... |
343,408 | def _call(callable_obj, arg_names, namespace):
arguments = {arg_name: getattr(namespace, arg_name)
for arg_name in arg_names}
return callable_obj(**arguments) | Actually calls the callable with the namespace parsed from the command
line.
Args:
callable_obj: a callable object
arg_names: name of the function arguments
namespace: the namespace object parsed from the command line |
343,409 | def _to_dict(self):
_dict = {}
if hasattr(self, ) and self.description is not None:
_dict[] = self.description
if hasattr(self,
) and self.destination_field is not None:
_dict[] = self.destination_field
if hasattr(self, ) and self.sourc... | Return a json dictionary representing this model. |
343,410 | def manage_actors(self, monitor, stop=False):
alive = 0
if self.managed_actors:
for aid, actor in list(self.managed_actors.items()):
alive += self.manage_actor(monitor, actor, stop)
return alive | Remove :class:`Actor` which are not alive from the
:class:`PoolMixin.managed_actors` and return the number of actors
still alive.
:parameter stop: if ``True`` stops all alive actor. |
343,411 | def overall_statistics(
RACC,
RACCU,
TPR,
PPV,
TP,
FN,
FP,
POP,
P,
TOP,
jaccard_list,
CEN_dict,
MCEN_dict,
AUC_dict,
classes,
table):
population = list(POP.values())[0]
overall_ac... | Return overall statistics.
:param RACC: random accuracy
:type RACC : dict
:param TPR: sensitivity, recall, hit rate, or true positive rate
:type TPR : dict
:param PPV: precision or positive predictive value
:type PPV : dict
:param TP: true positive
:type TP : dict
:param FN: false n... |
343,412 | def check(self, req):
if self._cache is None:
return None
if not isinstance(req, sc_messages.ServicecontrolServicesCheckRequest):
raise ValueError(u)
if req.serviceName != self.service_name:
_logger.error(u,
req.serviceName... | Determine if ``req`` is in this instances cache.
Determine if there are cache hits for the request in this aggregator
instance.
Not in the cache
If req is not in the cache, it returns ``None`` to indicate that the
caller should send the request.
Cache Hit; response ha... |
343,413 | def set_country_map(cfrom, cto, name=None, replace=True):
global _country_maps
cdb = countries()
cfrom = str(cfrom).upper()
c = cdb.get(cfrom)
if c:
if name:
c = name
cto = str(cto).upper()
if cto in cdb:
raise CountryError( % cto)
cdb[cto... | Set a mapping between a country code to another code |
343,414 | def get_sid(principal):
s sid
salt.utils.win_dacl.get_sid()
salt.utils.win_dacl.get_sid()
NULL SIDInvalid user/group or sid: %sInvalid user/group or sid: {0}'.format(principal))
except TypeError:
raise CommandExecutionError
return sid | Converts a username to a sid, or verifies a sid. Required for working with
the DACL.
Args:
principal(str):
The principal to lookup the sid. Can be a sid or a username.
Returns:
PySID Object: A sid
Usage:
.. code-block:: python
# Get a user's sid
salt... |
343,415 | def add_model(self, metric_value, model_id):
if self.verbose:
logger.info("Saving model.")
ret = {"model_id": model_id, "metric_value": metric_value}
self.history.append(ret)
if model_id == self.get_best_model_id():
file = open(os.path.join(self... | Add model to the history, x_queue and y_queue
Parameters
----------
metric_value : float
graph : dict
model_id : int
Returns
-------
model : dict |
343,416 | def grow(self, amount):
if self.max > 0:
budget = max(self.max - len(self._threads), 0)
else:
budget = float()
n_new = min(amount, budget)
workers = [self._spawn_worker() for i in range(n_new)]
while not all(worker.ready for worker ... | Spawn new worker threads (not above self.max). |
343,417 | def await_renderer_visible(cli, transform_path, is_visible=DEFAULT_RENDERER_VISIBLE, timeout_seconds=DEFAULT_TIMEOUT_SECONDS):
message_payload = {
"transform_path": transform_path,
"is_visible": is_visible,
"timeout": timeout_seconds
}
msg = message.Message("await.unity.renderer... | Waits for a transform renderer to become visible based on is_visible.
:param cli:
:param transform_path:
:param is_visible: Whether or not to await for visible state (True | False)
:param timeout_seconds: How long until this returns with failure
:return: bool |
343,418 | def competition_leaderboard_view(self, competition):
result = self.process_response(
self.competition_view_leaderboard_with_http_info(competition))
return [LeaderboardEntry(e) for e in result[]] | view a leaderboard based on a competition name
Parameters
==========
competition: the competition name to view leadboard for |
343,419 | def maybe_a(generator):
class MaybeAGenerator(ArbitraryInterface):
@classmethod
def arbitrary(cls):
return arbitrary(one_of(None, generator))
MaybeAGenerator.__name__ = .join([, generator.__name__, ])
return MaybeAGenerator | Generates either an arbitrary value of the specified generator or None.
This is a class factory, it makes a class which is a closure around the
specified generator. |
343,420 | def single_layout(path, files, **kwargs):
two_column_layout(path, [(f,) for f in files], **kwargs) | Make a well layout in single column format
path: str
Location to make the well html file
files: list of pycbc.workflow.core.Files
This list of images to show in order within the well layout html file. |
343,421 | def _trim(self, somestr):
tmp = RE_LSPACES.sub("", somestr)
tmp = RE_TSPACES.sub("", tmp)
return str(tmp) | Trim left-right given string |
343,422 | def run(ctx, cpu, gpu, env, message, data, mode, open_notebook, follow, tensorboard, gpu2, cpu2, max_runtime, task, command):
cli_default = {: , : }
command_str = None
module = Module(name=experiment_name,
description=message or ,
command=comm... | Start a new job on FloydHub.
Floyd will upload contents of the current directory and
run your command. |
343,423 | def get_prep_value(self, value):
if value:
if not isinstance(value, PhoneNumber):
value = to_python(value)
if value.is_valid():
format_string = getattr(settings, "PHONENUMBER_DB_FORMAT", "E164")
fmt = PhoneNumber.format_map[format_... | Perform preliminary non-db specific value checks and conversions. |
343,424 | def p_select_from_statement_1(self, p):
p[0] = SelectFromNode(cardinality=p[2],
variable_name=p[3],
key_letter=p[7]) | statement : SELECT ANY variable_name FROM INSTANCES OF identifier
| SELECT MANY variable_name FROM INSTANCES OF identifier |
343,425 | def query(self, value=None):
if value is not None:
return URL._mutate(self, query=value)
return self._tuple.query | Return or set the query string
:param string value: the new query string to use
:returns: string or new :class:`URL` instance |
343,426 | def display_hook(prompt, session, context, matches, longest_match_len):
match_pattern = "{{0: <{}}} from {{1}}".format(longest_match_len - 1)
matches = sorted(match for match in matches)
session.write_line()
with use_ipopo(context) as ipopo:... | Displays the available services matches and the service details
:param prompt: Shell prompt string
:param session: Current shell session (for display)
:param context: BundleContext of the shell
:param matches: List of words matching the substitution
:param longest_match_len: Len... |
343,427 | def unfederate(self, serverId):
url = self._url + "/servers/{serverid}/unfederate".format(
serverid=serverId)
params = {"f" : "json"}
return self._get(url=url,
param_dict=params,
proxy_port=self._proxy_port,
... | This operation unfederates an ArcGIS Server from Portal for ArcGIS |
343,428 | def set_options(self, force_read=False, force_fulltext=False):
self.options[] = force_read
self.options[] = force_fulltext
return | Set the options for this run. |
343,429 | def call_ext_prog(self, prog, timeout=300, stderr=True,
chroot=True, runat=None):
return self.get_command_output(prog, timeout=timeout, stderr=stderr,
chroot=chroot, runat=runat) | Execute a command independantly of the output gathering part of
sosreport. |
343,430 | def _create_table_setup(self):
column_names_and_types = self._get_column_names_and_types(
self._sql_type_name
)
pat = re.compile(r)
column_names = [col_name for col_name, _, _ in column_names_and_types]
if any(map(pat.search, column_names)):
warn... | Return a list of SQL statements that creates a table reflecting the
structure of a DataFrame. The first entry will be a CREATE TABLE
statement while the rest will be CREATE INDEX statements. |
343,431 | def user_exists(name):
with settings(hide(, , , ),
warn_only=True):
res = _run_as_pg(%(name)s % locals())
return (res == "1") | Check if a PostgreSQL user exists. |
343,432 | def _check_line_for_encoding(line):
i = 0
for i in range(len(line)):
if line[i] == b:
break
if line[i] not in b:
return None, False
return pytokenizer.match_encoding_declaration(line[i:]), True | returns the declared encoding or None |
343,433 | def post(self, path, data, filename=None):
return self._send(, path, data, filename) | Make a POST request.
If a `filename` is not specified, then the data must already be
JSON-encoded. We specify the Content-Type accordingly.
Else, we make a multipart/form-encoded request. In this case, the data
variable must be a dict-like object. The file must already be
suita... |
343,434 | def to_proto(self):
return sorted((s.get_proto() for s in self.values()), key=lambda s: s.name) | Returns a list of SplitInfo protos that we have. |
343,435 | def fwdl_status_output_fwdl_entries_blade_slot(self, **kwargs):
config = ET.Element("config")
fwdl_status = ET.Element("fwdl_status")
config = fwdl_status
output = ET.SubElement(fwdl_status, "output")
fwdl_entries = ET.SubElement(output, "fwdl-entries")
blade_slo... | Auto Generated Code |
343,436 | def uncurry_nested_dictionary(curried_dict):
result = {}
for a, a_dict in curried_dict.items():
for b, value in a_dict.items():
result[(a, b)] = value
return result | Transform dictionary from (key_a -> key_b -> float) to
(key_a, key_b) -> float |
343,437 | def parse(self, scope):
if not self.parsed:
if len(self.tokens) > 2:
property, style, _ = self.tokens
self.important = True
else:
property, style = self.tokens
self.important = False
self.property = .joi... | Parse node
args:
scope (Scope): current scope
raises:
SyntaxError
returns:
self |
343,438 | def discoverEventDependency(sig):
try:
drivers = sig.drivers
except AttributeError:
return
if len(drivers) == 1:
d = drivers[0]
if isinstance(d, Operator):
if isEventDependentOp(d.operator):
yield (d.operator, d.operands[0])
else... | :return: generator of tuples (event operator, signal) |
343,439 | def post_message(message,
channel=None,
username=None,
api_url=None,
hook=None):
Build is done
if not api_url:
api_url = _get_api_url()
if not hook:
hook = _get_hook()
if not username:
username = _get_username(... | Send a message to a Mattermost channel.
:param channel: The channel name, either will work.
:param username: The username of the poster.
:param message: The message to send to the Mattermost channel.
:param api_url: The Mattermost api url, if not specified in the configuration.
:param... |
343,440 | def select_by_key(items, sort_fn=sorted):
itr = anyconfig.utils.concat(((k, v) for k in ks) for ks, v in items)
return list((k, sort_fn(t[1] for t in g))
for k, g
in anyconfig.utils.groupby(itr, operator.itemgetter(0))) | :param items: A list of tuples of keys and values, [([key], val)]
:return: A list of tuples of key and values, [(key, [val])]
>>> select_by_key([(["a", "aaa"], 1), (["b", "bb"], 2), (["a"], 3)])
[('a', [1, 3]), ('aaa', [1]), ('b', [2]), ('bb', [2])] |
343,441 | def get_author_string(self, links=False):
saved_args = locals()
saved_args = saved_args[]
def format_author(author):
if links and author.person.slug:
return % (author.person.slug, author.person.full_name)
return author.person.full_name
... | Returns list of authors as a comma-separated
string (with 'and' before last author). |
343,442 | def feature_importances_table(self):
from . import table
return table.feature_importances(self.estimator,
feature_names=self.feature_names) | Feature importances table |
343,443 | def _subviews_from_utterance_splits(self, splits):
subviews = {}
for idx, subview_utterances in splits.items():
filter = subview.MatchingUtteranceIdxFilter(utterance_idxs=subview_utterances)
split = subview.Subview(self.corpus, filter_criteria=filter)
subvie... | Create subviews from a dict containing utterance-ids for each subview.
e.g. {'train': ['utt-1', 'utt-2'], 'test': [...], ...} |
343,444 | def get_soup(self, *args, **kwargs):
return BeautifulSoup(self.get(*args, **kwargs).text) | Shortcut for ``get`` which returns a ``BeautifulSoup`` element |
343,445 | def set_exception(self, exception, traceback=None):
if not isinstance(exception, BaseException):
raise RuntimeError("Exception must be of BaseException type")
self._exception = exception
self._traceback = traceback
self._event.set()
self._invoke_callbacks() | Sets the exception for this Future in case of errors.
:param exception: (Exception), exception to be threw in case of error.
:param traceback: (Function), function to be called on traceback (optional). |
343,446 | def getIndexedLength(self) :
if self.x1 != None and self.x2 != None:
return self.x2 - self.x1
else :
if len(self.children) == 0 :
return 0
else :
l = self.children[0].x2 - self.children[0].x1
for i in range(1, len(self.children)) :
l += self.children[i].x2 - self.children[i].x1 - max(0,... | Returns the total length of indexed regions |
343,447 | def InjectionStatus(campaign=range(18), model=, purge=False,
depths=[0.01, 0.001, 0.0001], **kwargs):
if not hasattr(campaign, ):
if type(campaign) is int:
all_stars = [s for s in GetK2Campaign(
campaign, split=True, epics_only=True)]
... | Shows the progress of the injection de-trending runs for
the specified campaign(s). |
343,448 | def tox_get_python_executable(envconfig):
try:
pyenv = (getattr(py.path.local.sysfind(), , )
or )
cmd = [pyenv, , envconfig.basepython]
pipe = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
... | Return a python executable for the given python base name.
The first plugin/hook which returns an executable path will determine it.
``envconfig`` is the testenv configuration which contains
per-testenv configuration, notably the ``.envname`` and ``.basepython``
setting. |
343,449 | def delete(self, pid, record, **kwargs):
self.check_etag(str(record.model.version_id))
record.delete()
all_pids = PersistentIdentifier.query.filter(
PersistentIdentifier.object_type == pid.object_type,
PersistentIdentifier.object_uuid == pid.object_uuid... | Delete a record.
Permissions: ``delete_permission_factory``
Procedure description:
#. The record is resolved reading the pid value from the url.
#. The ETag is checked.
#. The record is deleted.
#. All PIDs are marked as DELETED.
:param pid: Persistent iden... |
343,450 | def main(cert, key, pushtoken, url):
try:
worker = APNSWorker(cert=cert, key=key, pushtoken=pushtoken, url=url)
worker.connect()
worker.run_forever()
except KeyboardInterrupt:
worker.close() | Create, connect, and block on the listener worker. |
343,451 | def blob_put(self, table, digest, data):
response = self._request(, _blob_path(table, digest),
data=data)
if response.status == 201:
return True
if response.status == 409:
return False
if response... | Stores the contents of the file like @data object in a blob under the
given table and digest. |
343,452 | def get_actual(cls, trip_list, time):
for trip in trip_list:
if simple_time(trip.departure_time_planned) == time:
return trip
return None | Look for the train actually leaving at time |
343,453 | def find_files(directory, pattern):
for root, __, files in os.walk(directory):
for basename in files:
if fnmatch.fnmatch(basename, pattern):
filename = os.path.join(root, basename)
yield filename | Recusively finds files in a directory re
:param directory: base directory
:param pattern: wildcard pattern
:return: generator with filenames matching pattern |
343,454 | def grading_status_text(self):
if self.assignment.is_graded():
if self.is_grading_finished():
return str(.format(self.grading))
else:
return str()
else:
return str() | A rendering of the grading that is an answer on the question
"Is grading finished?".
Used in duplicate view and submission list on the teacher backend. |
343,455 | def transform(self, m):
if len(m) != 6:
raise ValueError("bad sequ. length")
self.ul *= m
self.ur *= m
self.ll *= m
self.lr *= m
return self | Replace quad by its transformation with matrix m. |
343,456 | def styleProperties(Class, style):
properties = Dict()
for property in style.getProperties(all=True):
stylename = property.name +
properties[stylename] = property.value
if property.priority != :
properties[stylename] = +property.priority
... | return a properties dict from a given cssutils style |
343,457 | def get_class(self, name):
for i in self.classes.class_def:
if i.get_name() == name:
return i
return None | Return a specific class
:param name: the name of the class
:rtype: a :class:`ClassDefItem` object |
343,458 | def deploy_lambda(awsclient, function_name, role, handler_filename,
handler_function,
folders, description, timeout, memory, subnet_ids=None,
security_groups=None, artifact_bucket=None,
zipfile=None,
fail_deployment_on_unsuccessfu... | Create or update a lambda function.
:param awsclient:
:param function_name:
:param role:
:param handler_filename:
:param handler_function:
:param folders:
:param description:
:param timeout:
:param memory:
:param subnet_ids:
:param security_groups:
:param artifact_bucket... |
343,459 | def _get_abs_corr_mat(self, X_filled, tolerance=1e-6):
n_features = X_filled.shape[1]
if (self.n_nearest_features is None or
self.n_nearest_features >= n_features):
return None
abs_corr_mat = np.abs(np.corrcoef(X_filled.T))
abs_corr_mat[np.is... | Get absolute correlation matrix between features.
Parameters
----------
X_filled : ndarray, shape (n_samples, n_features)
Input data with the most recent imputations.
tolerance : float, optional (default=1e-6)
``abs_corr_mat`` can have nans, which will be replac... |
343,460 | def requestViewMenu(self, point):
vitem = self.uiGanttVIEW.itemAt(point)
if vitem:
glbl_pos = self.uiGanttVIEW.mapToGlobal(point)
item = vitem.treeItem()
self.viewMenuRequested.emit(vitem, glbl_pos)
self.itemMenuRequested.emit(item, glbl_po... | Emits the itemMenuRequested and viewMenuRequested signals
for the given item.
:param point | <QPoint> |
343,461 | def make_filled_array(shp, dtype, order, r, g, b, a):
maxv = np.iinfo(dtype).max
bgval = dict(A=int(maxv * a), R=int(maxv * r), G=int(maxv * g),
B=int(maxv * b))
bgtup = tuple([bgval[order[i]] for i in range(len(order))])
if dtype is np.uint8 and len(bgtup) == 4:
... | Return a filled array with a color value. order defines the color
planes in the array. (r, g, b, a) are expected to be in the range
0..1 and are scaled to the appropriate values.
shp can define a 2D or 3D array. |
343,462 | def plot_network_results(network, ds=None, mean=0, std=1, title=, show=True, save=True):
df = sim_network(network=network, ds=ds, mean=mean, std=std)
df.plot()
plt.xlabel()
plt.ylabel()
plt.title(title)
if show:
try:
if isinstance(save, basestring) and os.path.... | Identical to plot_trainer except `network` and `ds` must be provided separately |
343,463 | def get_relativelinenumbertable(self):
lnt = self.get_linenumbertable()
if lnt:
lineoff = lnt[0][1]
return tuple((o, l - lineoff) for (o, l) in lnt)
else:
return tuple() | a sequence of (code_offset, line_number) pairs. Similar to the
get_linenumbertable method, but the line numbers start at 0
(they are relative to the method, not to the class file) |
343,464 | def echo(text, fg=None, bg=None, style=None, file=None, err=False, color=None):
if file and not hasattr(file, "write"):
raise TypeError("Expected a writable stream, received {0!r}".format(file))
if not file:
if err:
file = _text_stderr()
else:
file = _text_s... | Write the given text to the provided stream or **sys.stdout** by default.
Provides optional foreground and background colors from the ansi defaults:
**grey**, **red**, **green**, **yellow**, **blue**, **magenta**, **cyan**
or **white**.
Available styles include **bold**, **dark**, **underline**, **bli... |
343,465 | def decode_list(self, ids):
decoded_ids = []
for id_ in ids:
if 0 <= id_ < self._num_reserved_ids:
decoded_ids.append(RESERVED_TOKENS[int(id_)])
else:
decoded_ids.append(id_ - self._num_reserved_ids)
return [str(d) for d in decoded_ids] | Transform a sequence of int ids into a their string versions.
This method supports transforming individual input/output ids to their
string versions so that sequence to/from text conversions can be visualized
in a human readable format.
Args:
ids: list of integers to be converted.
Returns:
... |
343,466 | def _read_line(self, f):
l = f.readline().strip()
while l == "" or l[0] == "
l = f.readline().strip()
return l | Reads one non empty line (if it's a comment, it skips it). |
343,467 | def shorten(string, maxlen):
if 1 < maxlen < len(string):
string = string[:maxlen - 1] + u
return string[:maxlen] | shortens string if longer than maxlen, appending ellipsis |
343,468 | def coarsegrain(F, sets):
r
nnew = len(sets)
Fin = F.tocsr()
Fc = csr_matrix((nnew, nnew))
for i in range(0, nnew - 1):
for j in range(i, nnew):
I = list(sets[i])
J = list(sets[j])
Fc[i, j] = (Fin[I, :][:, J]).sum()
Fc[j, i] = (Fin[J, :][:, I])... | r"""Coarse-grains the flux to the given sets
$fc_{i,j} = \sum_{i \in I,j \in J} f_{i,j}$
Note that if you coarse-grain a net flux, it does not necessarily have a net
flux property anymore. If want to make sure you get a netflux,
use to_netflux(coarsegrain(F,sets)).
Parameters
----------
F ... |
343,469 | def validate_meta(meta):
if not isinstance(meta, (dict,)):
raise TypeError()
required_keys = ("identifier", "fields")
for key in required_keys:
if key not in meta:
raise KeyError(, key)
if not isinstance(meta["fields"], (list, tuple)):
raise ImproperlyConfigur... | Validates Linguist Meta attribute. |
343,470 | def _get_style_of_faulting_term(self, C, rup):
if (rup.rake > 30.0) and (rup.rake < 150.):
frv = 1.0
fnm = 0.0
elif (rup.rake > -150.0) and (rup.rake < -30.0):
fnm = 1.0
frv = 0.0
else:
fnm = 0.0
frv = 0.0
... | Returns the style-of-faulting scaling term defined in equations 4 to 6 |
343,471 | def filter(self, *args, **kwargs):
if len([x for x in kwargs.values() if x is None]):
raise CQLEngineException("None values on filter are not allowed")
clone = copy.deepcopy(self)
for operator in args:
if not isinstance(operator, WhereClause):
... | Adds WHERE arguments to the queryset, returning a new queryset
#TODO: show examples
:rtype: AbstractQuerySet |
343,472 | def tv(self, **kwargs):
path = self._get_path()
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | Search for TV shows by title.
Args:
query: CGI escpaed string.
page: (optional) Minimum value of 1. Expected value is an integer.
language: (optional) ISO 639-1 code.
first_air_date_year: (optional) Filter the results to only match
... |
343,473 | def handle_update(self, args):
_LOGGER.debug("handle_update %d -- %s" % (self._integration_id, args))
state = int(args[0])
if state != Output._ACTION_ZONE_LEVEL:
return False
level = float(args[1])
_LOGGER.debug("Updating %d(%s): s=%d l=%f" % (
self._integration_id, self._name, st... | Handles an event update for this object, e.g. dimmer level change. |
343,474 | def coverage(ctx, opts=""):
return test(ctx, coverage=True, include_slow=True, opts=opts) | Execute all tests (normal and slow) with coverage enabled. |
343,475 | def login_password(self, value):
password = self.selenium.find_element(*self._password_input_locator)
password.clear()
password.send_keys(value) | Set the value of the login password field. |
343,476 | def data_received(self, data):
self._data_buffer += data.decode()
if not self._data_buffer.endswith():
return
data = self._data_buffer
self._data_buffer =
for cmd in data.strip().split():
data = json.loads(cmd)
if not isinstance(dat... | Handle received data. |
343,477 | def attempt_open_query_permutations(url, orig_file_path, is_header_file):
directory = dirname(convert_to_platform_safe(orig_file_path)) + "/"
try:
filenames = [f for f in os.listdir(directory)
if isfile(join(directory, f))]
except OSError:
return
if ... | Attempt to open a given mock data file with different permutations of the
query parameters |
343,478 | def get(self, request, bot_id, format=None):
return super(TelegramChatStateList, self).get(request, bot_id, format) | Get list of chat state
---
serializer: TelegramChatStateSerializer
responseMessages:
- code: 401
message: Not authenticated |
343,479 | def geturl(self):
if self.retries is not None and len(self.retries.history):
return self.retries.history[-1].redirect_location
else:
return self._request_url | Returns the URL that was the source of this response.
If the request that generated this response redirected, this method
will return the final redirect location. |
343,480 | def lemmatise(self, f, pos=False, get_lemma_object=False, lower=True):
if lower:
yield from self._lemmatise_roman_numerals(f, pos=pos, get_lemma_object=get_lemma_object)
if f.lower() != f:
yield from self.lemmatise(f.lower(), pos=pos, g... | Lemmatise un mot f
:param f: Mot à lemmatiser
:param pos: Récupère la POS
:param get_lemma_object: Retrieve Lemma object instead of string representation of lemma
:param lower: Need to check lowercase version |
343,481 | def slugs_configuration_camera_send(self, target, idOrder, order, force_mavlink1=False):
return self.send(self.slugs_configuration_camera_encode(target, idOrder, order), force_mavlink1=force_mavlink1) | Control for camara.
target : The system setting the commands (uint8_t)
idOrder : ID 0: brightness 1: aperture 2: iris 3: ICR 4: backlight (uint8_t)
order : 1: up/on 2: down/off 3: auto/reset/no action (uint8_t) |
343,482 | def _get_key_props(phase=None, diameter=,
surface_tension=,
contact_angle=):
r
element = diameter.split()[0]
if element == :
if in surface_tension:
sigma = phase.interpolate_data(propname=surface_tension)
else:
sigma = phase[surf... | r"""
Many of the methods are generic to pores and throats. Some information may
be stored on either the pore or throat and needs to be interpolated.
This is a helper method to return the properties in the correct format.
To do:
Check for method to convert throat to pore data |
343,483 | def add_node(self, node, node_data=None):
if node in self.hidden_nodes:
return
if node not in self.nodes:
self.nodes[node] = ([], [], node_data) | Adds a new node to the graph. Arbitrary data can be attached to the
node via the node_data parameter. Adding the same node twice will be
silently ignored.
The node must be a hashable value. |
343,484 | def compose(f, *fs):
rfs = list(chain([f], fs))
rfs.reverse()
def composed(*args, **kwargs):
return reduce(
lambda result, fn: fn(result),
rfs[1:],
rfs[0](*args, **kwargs))
return composed | Compose functions right to left.
compose(f, g, h)(x) -> f(g(h(x)))
Args:
f, *fs: The head and rest of a sequence of callables. The
rightmost function passed can accept any arguments and
the returned function will have the same signature as
this last prov... |
343,485 | def atlas_peer_set_zonefile_status( peer_hostport, zonefile_hash, present, zonefile_bits=None, peer_table=None, con=None, path=None ):
if zonefile_bits is None:
zonefile_bits = atlasdb_get_zonefile_bits( zonefile_hash, con=con, path=path )
with AtlasPeerTableLocked(peer_table) as ptbl:
if ... | Mark a zonefile as being present or absent on a peer.
Use this method to update our knowledge of what other peers have,
based on when we try to ask them for zonefiles (i.e. a peer can
lie about what zonefiles it has, and if it advertizes the availability
of a zonefile but doesn't deliver, then we need t... |
343,486 | def set_data(self, value):
| Sets a new string as response. The value set must either by a
unicode or bytestring. If a unicode string is set it's encoded
automatically to the charset of the response (utf-8 by default).
.. versionadded:: 0.9 |
343,487 | def get_plugin_actions(self):
self.new_action = create_action(
self,
_("&New file..."),
icon=ima.icon(), tip=_("New file"),
triggered=self.new,
context=Qt.WidgetShortcut
)
self.register_sho... | Return a list of actions related to plugin |
343,488 | def fisher_stats(lons, lats, conf=95):
xyz = sph2cart(lons, lats)
xyz = np.vstack(xyz).T
mean_vec = xyz.mean(axis=0)
r_value = np.linalg.norm(mean_vec)
num = xyz.shape[0]
mean_vec = cart2sph(*mean_vec)
if num > 1:
p = (100.0 - conf) / 100.0
vector_sum = xyz.sum(axis=0)
... | Returns the resultant vector from a series of longitudes and latitudes. If
a confidence is set the function additionally returns the opening angle
of the confidence small circle (Fisher, 19..) and the dispersion factor
(kappa).
Parameters
----------
lons : array-like
A sequence of longi... |
343,489 | def add_phase_interconnections(net, snow_partitioning_n, voxel_size=1,
marching_cubes_area=False,
alias=None):
r
im = snow_partitioning_n.im
al = _create_alias_map(im, alias=alias)
conns1 = net[][:, 0]
conns2 = net[][:... | r"""
This function connects networks of two or more phases together by
interconnecting neighbouring nodes inside different phases.
The resulting network can be used for the study of transport and kinetics
at interphase of two phases.
Parameters
----------
network : 2D or 3D network
... |
343,490 | def set(self, value):
self.deadline = self.timer() + self.duration
self.value = value | Set new value and reset the deadline for expiration. |
343,491 | def read_global_register(self, name, overwrite_config=False):
self.register_utils.send_commands(self.register.get_commands("ConfMode"))
with self.readout(fill_buffer=True, callback=None, errback=None):
commands = []
commands.extend(self.register.get_commands("RdRegister", name=name))... | The function reads the global register, interprets the data and returns the register value.
Parameters
----------
name : register name
overwrite_config : bool
The read values overwrite the config in RAM if true.
Returns
-------
register value |
343,492 | def disqus_recent_comments(context, shortname=, num_items=5, excerpt_length=200, hide_avatars=0, avatar_size=32):
shortname = getattr(settings, , shortname)
return {
: shortname,
: num_items,
: hide_avatars,
: avatar_size,
: excerpt_length,
: get_config(cont... | Return the HTML/js code which shows recent comments. |
343,493 | def authors(self):
qs = self._valid_submissions().values_list(,flat=True).distinct()
return qs | Queryset for all distinct authors this course had so far. Important for statistics.
Note that this may be different from the list of people being registered for the course,
f.e. when they submit something and the leave the course. |
343,494 | def stations_listeners(stations):
stations = stations if isinstance(stations, (list, tuple)) else [stations]
listeners = []
for sta in stations:
listeners.append(StationSignalListener(sta))
listeners.append(StationMaxListener(sta))
if sta.mask is not None:
listener... | Function for creating listeners for a a list of station
Args:
stations (iterable): List of TopocentricFrame
Return:
list of Listener |
343,495 | def addError(self, test, err, capt=None):
exc_type, exc_val, tb = err
tb = .join(traceback.format_exception(
exc_type,
exc_val if isinstance(exc_val, exc_type) else exc_type(exc_val),
tb
))
name = id_split(test.id())
group = self.repor... | Add error output to Xunit report. |
343,496 | def _set_peer(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGListType("peer_ip",peer.peer, yang_name="peer", rest_name="peer", parent=self, is_container=, user_ordered=False, path_helper=self._path_helper, yang_keys=, extensions={u: {u: u, u: Non... | Setter method for peer, mapped from YANG variable /bridge_domain/peer (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_peer is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_peer() directly. |
343,497 | def get_default_client(path=None, ui=None, **kwargs):
from .transport import get_transport
from .ui import ClickUI
transport = get_transport(path, prefix_search=True)
if ui is None:
ui = ClickUI()
return TrezorClient(transport, ui, **kwargs) | Get a client for a connected Trezor device.
Returns a TrezorClient instance with minimum fuss.
If no path is specified, finds first connected Trezor. Otherwise performs
a prefix-search for the specified device. If no UI is supplied, instantiates
the default CLI UI. |
343,498 | def record(self, custom_changeset_id: uuid.UUID = None) -> uuid.UUID:
return self.journal.record_changeset(custom_changeset_id) | Starts a new recording and returns an id for the associated changeset |
343,499 | def get_key_index(self, data, key, starting=True):
key = self.opt[key][self.style[]][]
if key.startswith():
data = data.replace(, )
idx = len(data)
ini = 0
loop = True
if key in data:
while loop:
i = data.find(key)
... | Get from a docstring the next option with a given key.
:param data: string to parse
:param starting: does the key element must start the line (Default value = True)
:type starting: boolean
:param key: the key category. Can be 'param', 'type', 'return', ...
:returns: index of fou... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.