content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def check_preprocessor_settings(settings):
"""Check preprocessor settings."""
for step in settings:
if step not in DEFAULT_ORDER:
raise ValueError(
"Unknown preprocessor function '{}', choose from: {}".format(
step, ', '.join(DEFAULT_ORDER)))
func... | 5,317,500 |
def test_update_user_serializer(
mock_user_sync, settings, user, sample_address, hubspot_api_key
):
""" Test that a UserSerializer can be updated properly and hubspot sync called if appropriate """
settings.HUBSPOT_API_KEY = hubspot_api_key
serializer = UserSerializer(
instance=user,
dat... | 5,317,501 |
def create_mm_sim(molecule):
"""Create vacuum simulation system"""
platform = Platform.getPlatformByName('CPU')
properties={}
properties["Threads"]="2"
integrator = LangevinIntegrator(temperature, collision_rate, stepsize)
topology = molecule.to_topology()
system = forcefield.create_openmm... | 5,317,502 |
def tokenize_iter(document: str) -> Iterator[Token]:
"""Tokenize a JSON document."""
TT = TokenType
tokens = {
TT.LEFT_BRACE: re.escape("{"),
TT.RIGHT_BRACE: re.escape("}"),
TT.LEFT_BRACKET: re.escape("["),
TT.RIGHT_BRACKET: re.escape("]"),
TT.COLON: re.escape(":"),
... | 5,317,503 |
def svm_plotter(df, clf, target=None):
"""plot the support vectors and decision boundary"""
plt.scatter(df['x'], df['y'], c=df['color'], s=30, cmap=plt.cm.Paired)
# plot the decision function
ax = plt.gca()
ax.set_xlim(left=-6, right=8)
ax.set_ylim(bottom=-6, top=8)
xlim = ax.get_xlim()
... | 5,317,504 |
def html_start():
"""Start HTML output."""
global start_done
if start_done:
return
start_done = 1
print(\
"""<html>
<head>
<title>RedBrick Registration System v3.0 - %s</title>
<link rel="stylesheet" href="common.css" type="text/css">
<script language="JavaScript" type="text/javascript">
<... | 5,317,505 |
def team_event_awards(team_key: TeamKey, event_key: EventKey) -> Response:
"""
Returns a list of awards for a team at an event.
"""
track_call_after_response("team/event/awards", f"{team_key}/{event_key}")
awards = TeamEventAwardsQuery(team_key=team_key, event_key=event_key).fetch_dict(
Api... | 5,317,506 |
async def test_lock(hass, device_factory):
"""Test the lock locks successfully."""
# Arrange
device = device_factory("Lock_1", [Capability.lock])
device.status.attributes[Attribute.lock] = Status(
"unlocked",
None,
{
"method": "Manual",
"codeId": None,
... | 5,317,507 |
def version_match(ms_version, mi_version):
"""Judge if the version of Mindinsight and Mindspore is matched."""
if not ms_version:
ms_version = MS_VERSION
# the debugger version in MS 1.4.xxx is still 1.3.xxx
if mi_version.startswith('1.4.') and ms_version.startswith('1.3.'):
return True
... | 5,317,508 |
def add_to_tfrecord(coco, img_id, img_dir, coder, writer, is_train):
"""
Add each "single person" in this image.
coco - coco API
Returns:
The number of people added.
"""
# Get annotation id for this guy
# Cat ids is [1] for human..
ann_id = coco.getAnnIds(imgIds=img_id, catIds=[1]... | 5,317,509 |
def test_cql_filters_function_description(cql_schemas, is_cql):
"""
Assertions for CQL function description schema in OpenAPI 3.0 Document
:param cql_schemas: OpenAPI 3.0 Document schemas
:param is_cql: boolean value
"""
if is_cql:
# assertion for function description
assert 'f... | 5,317,510 |
def partial_es(Y_idx, X_idx, pred, data_in, epsilon=0.0001):
"""
The analysis on the single-variable dependency in the neural network.
The exact partial-related calculation may be highly time consuming, and so the estimated calculation can be used in the bad case.
Args:
Y_idx: index of Y to acce... | 5,317,511 |
def process_source_text(
source_text: str,
endpoint_config: submanager.models.config.FullEndpointConfig,
) -> str:
"""Perform text processing operations on the source text."""
source_text = submanager.sync.utils.replace_patterns(
source_text,
endpoint_config.replace_patterns,
)
s... | 5,317,512 |
def angle(v1, v2, deg=False):
"""
Angle between two N dimmensional vectors.
:param v1: vector 1.
:param v2: vector 2.
:param deg: if True angle is in Degrees, else radians.
:return: angle in radians.
Example::
>>> angle_between((1, 0, 0), (0, 1, 0))
1.5707963267948966
... | 5,317,513 |
async def test_current_fan_mode(opp):
"""Test current_fan_mode property."""
with patch("openpeerpower.components.melissa"):
api = melissa_mock()
device = (await api.async_fetch_devices())[_SERIAL]
thermostat = MelissaClimate(api, _SERIAL, device)
await thermostat.async_update()
... | 5,317,514 |
def __main__():
"""Sanity check"""
_VALIDATOR.check_schema(SCHEMA) | 5,317,515 |
def random_pure_actions(nums_actions, random_state=None):
"""
Return a tuple of random pure actions (integers).
Parameters
----------
nums_actions : tuple(int)
Tuple of the numbers of actions, one for each player.
random_state : int or np.random.RandomState, optional
Random see... | 5,317,516 |
def get_my_process():
"""get process object of current process
Returns:
[psutil.Process] -- process object
"""
return get_process_object(os.getpid()) | 5,317,517 |
def prepare_and_store_dataframe(test_df: pandas.DataFrame, current_datetime: str, prediction: numpy.ndarray,
eval_identity: str, df_output_dir: str):
"""Prepares a dataframe that includes the testing data (timestamp, value), the detected anomalies and the labeled
anomalies from t... | 5,317,518 |
def read_terrace_centrelines(DataDirectory, shapefile_name):
"""
This function reads in a shapefile of terrace centrelines
using shapely and fiona
Args:
DataDirectory (str): the data directory
shapefile_name (str): the name of the shapefile
Returns: shapely polygons with terraces
... | 5,317,519 |
def session_scope(session):
"""Provide a transactional scope around a series of operations."""
try:
yield session
session.commit()
except:
session.rollback()
raise
finally:
session.close() | 5,317,520 |
def learn_embeddings(args, walks):
"""Learn embeddings by optimizing the Skipgram objective using SGD."""
model = node2vec.Word2Vec(
walks,
vector_size=args.dimensions,
window=args.window_size,
min_count=0,
sg=1,
workers=args.workers,
epochs=args.epochs,
... | 5,317,521 |
def ownership_transitions(conn: sqlite3.Connection) -> None:
"""
Derives a table called ownership_transitions which counts the number of transitions in ownership
from address A to address B for each pair of addresses (A, B) for which there was at least
one transfer from A to B.
Requires the followi... | 5,317,522 |
def isfloat(s):
"""
Checks whether the string ``s`` represents a float.
:param s: the candidate string to test
:type s: ``str``
:return: True if s is the string representation of a number
:rtype: ``bool``
"""
try:
x = float(s)
return True
except:
r... | 5,317,523 |
def _heapqmergesorted(key=None, *iterables):
"""Return a single iterator over the given iterables, sorted by the
given `key` function, assuming the input iterables are already sorted by
the same function. (I.e., the merge part of a general merge sort.) Uses
:func:`heapq.merge` for the underlying impleme... | 5,317,524 |
def customization_data(client=None):
"""
Returns a Generator of ImportDefinitions (Customizations).
Install them using `resilient-circuits customize`
IBM Resilient Platform Version: 36.0.0
Contents:
- Message Destinations:
- fn_main_mock_integration
- fn_test_two
- Function... | 5,317,525 |
async def _fetch_team_info(team_id=None):
"""Get general team information"""
url = f"{BASE_URL}teams/{team_id}"
async with aiohttp.ClientSession() as session:
data = await _fetch_data(session, url)
team_info = data['teams'][0]
return team_info | 5,317,526 |
def numeric(typ):
"""Check whether `typ` is a numeric type"""
return typ.tcon in (Bool, Int, Float, Complex) | 5,317,527 |
def quadtree_point_in_polygon(
poly_quad_pairs,
quadtree,
point_indices,
points_x,
points_y,
poly_offsets,
ring_offsets,
poly_points_x,
poly_points_y,
):
""" Test whether the specified points are inside any of the specified
polygons.
Uses the table of (polygon, quadrant)... | 5,317,528 |
def obtain_treasury_maturities(treasuries: Dict) -> pd.DataFrame:
"""Obtain treasury maturity options [Source: EconDB]
Parameters
----------
treasuries: dict
A dictionary containing the options structured {instrument : {maturities: {abbreviation : name}}}
Returns
----------
df: pd.... | 5,317,529 |
def graph(gra):
""" write a molecular graph to a string
"""
gra_str = automol.graph.string(gra)
return gra_str | 5,317,530 |
def diag(v, k=0):
"""
Extract a diagonal or construct a diagonal array.
See syntax here: https://numpy.org/doc/stable/reference/generated/numpy.diag.html
"""
if not is_casadi_type(v):
return _onp.diag(v, k=k)
else:
if k != 0:
raise NotImplementedError(
... | 5,317,531 |
def which_set(connections_list_of_dics):
"""
"""
set_of_derivations=get_set_of_derivations(connections_list_of_dics)
list_of_derivations=[]
list_of_derivations.append("all")
list_of_derivations.append("each")
for this_deriv in list(set_of_derivations):
list_of_derivations.append(this_deriv)
list_of_... | 5,317,532 |
def create_proxy_interface(from_, to, ignore_list=None, override_existing=False):
"""
Copies the public interface of the destination object, excluding names in the ignore_list,
and creates an identical interface in 'src', which forwards calls to dst.
If 'override_existing' is False, then attributes alre... | 5,317,533 |
def ensure_derived_space(func):
"""
Decorator for Surface functions that require ImageSpace arguments.
Internally, Surface objecs store information indexed to a minimal
enclosing voxel grid (referred to as the self.index_grid) based on
some arbitrary ImageSpace. When interacting with other ImageS... | 5,317,534 |
def ShowKdebugTypefilter(cmd_args=None):
""" Show the current kdebug typefilter (or the typefilter at an address)
usage: showkdebugtypefilter [<address>]
"""
if cmd_args:
print GetKdebugTypefilter.header
print '-' * len(GetKdebugTypefilter.header)
typefilter = kern.GetValu... | 5,317,535 |
def IMaximize(InterfaceItemPath, MaximizeSubPalettes):
"""
Locates an interface item and (if possible) maximize its size.
"""
pass | 5,317,536 |
def available_datasets():
"""
Returns the list of available datasets.
"""
return sorted(_datasets.keys()) | 5,317,537 |
def confirm_get_xchain(self, stack, col_x, col_y, others,
rules_values_x, rules_values_y):
"""
Confirms all variations of rules applied with frequency.
"""
keys = ['dk', 'fk', 'xk', 'yk', 'vk']
keys[0] = dk = 'test'
keys[1] = fk = 'no_filter'
keys[2] = xk = col_x
... | 5,317,538 |
def readable_date(input_date):
"""helper method to make a date object more readable
:param input_date: a date object
:return: more readable string representation of a date
"""
return "{} {}, {}".format(month_name[input_date.month], str(input_date.day), str(input_date.year)) | 5,317,539 |
def _add_sigma_interval_predictions(
fig, predictions, sigma, number, opacity, width, visible):
"""
Adds `number`-sigma interval lines of the error model to the measurement
versus predictions plot.
"""
# Add upper limit of interval
fig.add_trace(
go.Scatter(
x=predict... | 5,317,540 |
def get_unicode_from_response(response):
"""Return the requested content back in unicode.
This will first attempt to retrieve the encoding from the response
headers. If that fails, it will use
:func:`requests_toolbelt.utils.deprecated.get_encodings_from_content`
to determine encodings from HTML ele... | 5,317,541 |
def stack_layers(inputs, net_layers, kernel_initializer='glorot_uniform'):
"""Builds the architecture of the network by applying each layer specified in net_layers to inputs.
Args:
inputs: a dict containing input_types and input_placeholders for each key
and value pair, respecively.
net_layers: a li... | 5,317,542 |
def instance_gpu() -> str:
"""
Returns the GPU for the Colab instance.
:return: The GPU model
"""
devices = device_lib.list_local_devices()
gpu = [x.physical_device_desc for x in devices if x.device_type == "GPU"][0]
return gpu.split(",")[1].split(":")[1].strip() | 5,317,543 |
def _get_expected_samples(A_s, b_s, mu_0, sample_shape) -> np.ndarray:
"""
Given an initial `mu_0`, calculate the expected samples from an almost-deterministic
`StateSpaceModel`.
"""
*batch_shape, transitions, state_dim = b_s.shape
means_list = [mu_0]
for i in range(transitions):
mea... | 5,317,544 |
def local_vars(fn: ast.AST):
"""Returns a set of all function local variables."""
return set(_locals_impl(fn)) | 5,317,545 |
def test_check_read_type():
"""test check_read_type"""
# test mix of read types
error_str = f"ERROR: Samplesheet -> Mixed read types.\n\tLINE: HSL-3,wt_DMSO,1,data/HSL-3_R1.fastq.gz,data/HSL-3_R2.fastq.gz\n\tHSL-4,wt_DMSO,2,data/HSL-4_R1.fastq.gz,data/HSL-4_R2.fastq.gz"
with pytest.raises(SystemExit) a... | 5,317,546 |
def swap(size: int, target0: int, target1: int) -> Matrix:
"""
Construct swap gate which swaps two states
:param int size: total number of qubits in circuit
:param int target0: The first target bit to swap
:param int target1: The second target bit to swap
returns:
Matrix: Matrix repres... | 5,317,547 |
def get_ELS_file_name(dt, remove_extension=False):
"""
>>> get_ELS_file_name('28-06-2004/22:00')
'ELS_200418018_V01.DAT'
>>> get_ELS_file_name('28-06-2004/09:00')
'ELS_200418006_V01.DAT'
>>> get_ELS_file_name('29-06-2004/09:00')
'ELS_200418106_V01.DAT'
>>> get_ELS_file_name('29-06-2005/0... | 5,317,548 |
def percentage_to_float(x):
"""Convert a string representation of a percentage to float.
>>> percentage_to_float('55%')
0.55
Args:
x: String representation of a percentage
Returns:
float: Percentage in decimal form
"""
return float(x.strip('%')) / 100 | 5,317,549 |
def _naics_code_to_name(naics_val: str) -> str:
"""Converts NAICS codes to their industry using the _NAICS_MAP.
Args:
naics_val: A NAICS string literal to process.
Expected syntax of naics_val - NAICS/{codes}
'-' can be used to denote range of codes that may or may not belong
... | 5,317,550 |
def threshold_distribution(distribution, target_bin=128):
"""
Return the best threshold value.
Ref: https://github.com//apache/incubator-mxnet/blob/master/python/mxnet/contrib/quantization.py
Args:
distribution: list, activations has been processed by histogram and normalize,size is 2048
... | 5,317,551 |
def get_pragma_spec(source: str) -> Optional[NpmSpec]:
"""
Extracts pragma information from Solidity source code.
Args:
source: Solidity source code
Returns: NpmSpec object or None, if no valid pragma is found
"""
pragma_match = next(re.finditer(r"(?:\n|^)\s*pragma\s*solidity\s*([^;\n]*)... | 5,317,552 |
def delete_form(context, *args, **kwargs):
"""Тег формы удаления объекта.
"""
action = (args[0] if len(args) > 0
else kwargs.get('action'))
if action is None:
raise TemplateSyntaxError(
"delete_form template tag "
"requires at least one argument: "
... | 5,317,553 |
def _ligandscout_xml_tree(pharmacophore):
""" Get an xml element tree necesary to create a ligandscout pharmacophore.
Parameters
----------
pharmacophore : openpharmacophore.Pharmacophore
Pharmacophore object that will be saved to a file.
Returns
-------
... | 5,317,554 |
def create(nncli, title, from_stdin):
"""
Create a new note, either opening the editor or, if - is specified,
reading from stdin.
"""
nncli.cli_note_create(from_stdin, title) | 5,317,555 |
def get_form(line):
"""
gets the form of the word,
can use instead of getLemma
TODO: pick a function naming convention and stick with it
"""
if line == "":
return ""
s = line.split("\t")
return s[0] | 5,317,556 |
def request_get_content(url: str, n_retry: int = 3) -> bytes:
"""Retrieve the binary content at url.
Retry on connection errors.
"""
t0 = time.time()
for i in range(1, n_retry + 1):
try:
r = _session().get(url)
r.raise_for_status()
break
except req... | 5,317,557 |
def _escape_special_chars(content):
"""No longer used."""
content = content.replace("\N{RIGHT-TO-LEFT OVERRIDE}", "")
if len(content) > 300: # https://github.com/discordapp/discord-api-docs/issues/1241
content = content[:300] + content[300:].replace('@', '@ ')
return content | 5,317,558 |
async def async_remove_entry(opp, entry):
"""Remove a rachio config entry."""
if CONF_CLOUDHOOK_URL in entry.data:
await opp.components.cloud.async_delete_cloudhook(entry.data[CONF_WEBHOOK_ID]) | 5,317,559 |
def gather(results_dir):
"""Move all of the files and directories from the present working directory
into results_dir.
If results_dir doesn't exist, create it.
Delete any symbolic links so that the present working directory is empty.
:param results_dir: Path of the directory into which to store t... | 5,317,560 |
def test_solver_creation():
"""Test initializing a solver.
"""
s = Solver()
assert isinstance(s, Solver)
with pytest.raises(TypeError):
Solver(Variable()) | 5,317,561 |
def system_dynamics(t, x, params,):
"""
Parameters
----------
x0 : State vector
t : Current time step
params : Simulation parameters
Returns
-------
dx : State vector dynamics for time step integration
"""
# Extract state variables and parameters
# Python star... | 5,317,562 |
def key():
"""Connection key"""
return ConnectionKey('localhost', 80, False, None, None, None, None) | 5,317,563 |
def _check_deviation(indexesv,
xdatav,
ydatav,
yarray_,
ii,
start_,
end_,
mbf,
dev_thresh,
no_data,
baseline,
... | 5,317,564 |
def test_precip_6group():
"""3 hour precip"""
# 2016-08-12 02:53:00
# KAMW 120253Z AUTO 36012KT 1 1/4SM +TSRA BR SCT005
# SCT009 OVC014 21/21 A2991 RMK AO2 WSHFT 0219 LTG DSNT ALQDS
# RAE00B24 TSE0155B27 SLP119 P0080 60232 T02110211 53037
msg = (
"0463725472949892016081202537+41991-09361... | 5,317,565 |
def crop_boxes_inv(cropped_boxes, crop_shape):
"""
Inverse operation of crop_boxes
"""
crop_x1 = crop_shape[0]
crop_y1 = crop_shape[1]
raw_boxes = np.zeros_like(cropped_boxes)
raw_boxes[:, 0::4] = cropped_boxes[:, 0::4] + crop_x1
raw_boxes[:, 1::4] = cropped_boxes[:, 1::4] + crop_y1
... | 5,317,566 |
def build_paramDict(cur_func):
"""
This function iterates through all inputs of a function,
and saves the default argument names and values into a dictionary.
If any of the default arguments are functions themselves, then recursively (depth-first) adds an extra field to
the dictionary, named <... | 5,317,567 |
def auto_gen_message(open, fill, close):
"""
Produces the auto-generated warning header with language-spcific syntax
open - str - The language-specific opening of the comment
fill - str - The values to fill the background with
close - str - The language-specific closing of the commen... | 5,317,568 |
def fixture_only_binary_sensor(mock_system_manager):
"""Mock vaillant to only handle binary_sensor."""
orig_platforms = vaillant.PLATFORMS
vaillant.PLATFORMS = []
yield
vaillant.PLATFORMS = orig_platforms | 5,317,569 |
def neighbor(matrix, taxa=None, distances=True):
"""
Function clusters data according to the Neighbor-Joining algorithm \
(:evobib:`Saitou1987`).
"""
clusters = dict([(i, [i]) for i in range(len(taxa))])
formatter = "({0}:{2:.4f},{1}:{3:.4f})" if distances else "({0},{1})"
taxa = check_langu... | 5,317,570 |
def cli(ctx: Context, path: str, config_path: str, gpg_email: str, push: bool) -> None:
"""Initializes envadmin git repository."""
if not os.path.isdir(path):
raise click.ClickException("envadmin - Path isn't a directory. Check the '-p/--path' option.")
# Create .envadmin if available.
if not ... | 5,317,571 |
def check_response(resp: Response) -> None:
"""Check if a ``requests.Resonse`` returned an error message."""
if resp.headers["Content-Type"] == "application/xml":
root = etree.fromstring(resp.text)
raise ZeroMatched(root[0][0].text.strip()) | 5,317,572 |
async def gplayer_monitor(players, activity, gap=3):
"""
An asynchronous task to monitor to ...
- Disconnect the player when no users in channel or stopped for timeout.
- Prune the cache of old videos to reclaim space when limit reached.
Args:
players: A reference to the structure c... | 5,317,573 |
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up the deCONZ sensors."""
gateway = get_gateway_from_config_entry(hass, config_entry)
gateway.entities[DOMAIN] = set()
battery_handler = DeconzBatteryHandl... | 5,317,574 |
def mixed_type_frame():
"""
Fixture for DataFrame of float/int/string columns with RangeIndex
Columns are ['a', 'b', 'c', 'float32', 'int32'].
"""
return DataFrame({'a': 1., 'b': 2, 'c': 'foo',
'float32': np.array([1.] * 10, dtype='float32'),
'int32': np.... | 5,317,575 |
def part2():
"""Solution to day 1, part 2."""
result = find_sum(TARGET_VAL, 3)
if result is None:
print("No possible combination found!")
else:
x, y, z= result
product = x * y * z
print(f"Solution found for\nx = {x},\ny = {y},\nz = {z}\n"
f"x * y * z = {pro... | 5,317,576 |
def test_sampling_parameters_trace():
"""Test pypesto.visualize.sampling_parameters_trace"""
result = create_sampling_result()
visualize.sampling_parameters_trace(result)
# call with custom arguments
visualize.sampling_parameters_trace(
result, i_chain=1, stepsize=5, size=(10, 10),
u... | 5,317,577 |
def dar_state():
"""Get DAR state
"""
return jsonify(state=dar.state) | 5,317,578 |
def has_prefix(sub_s):
"""
:param sub_s: the list which includes the permutations of string's alphabet
:return: if the permutations of string's alphabet not exists in dictionary
"""
global d
for word in d:
if d[word].startswith(sub_s):
return True
return False | 5,317,579 |
def bar():
"""
Just says 'hello'
"""
print("hello\n") | 5,317,580 |
def copySourcePy(source, target):
"""Copy python source files to destination respecting the folder structure."""
shutil.copytree(source, target, dirs_exist_ok=True)
cleanSources(target)
copyflareAssets(source, target)
copypackageAssets(source, target) | 5,317,581 |
def MaskStringWithIPs(string):
"""Mask all private IP addresses listed in a string."""
ips = ExtractIPsFromString(string)
for ip in ips:
use_bits = IsPrivateIP(ip)
if use_bits:
masked_ip = MaskIPBits(ip, use_bits)
string = string.replace(ip, masked_ip)
return string | 5,317,582 |
def feature_evaluation(X: pd.DataFrame, y: pd.Series, output_path: str = ".") -> NoReturn:
"""
Create scatter plot between each feature and the response.
- Plot title specifies feature name
- Plot title specifies Pearson Correlation between feature and response
- Plot saved under given f... | 5,317,583 |
def DiagGaussian_UnifBins(mean, stdd, bin_min, bin_max, coding_prec, n_bins, rebalanced=True):
"""
Codec for data from a diagonal Gaussian with uniform bins.
rebalanced=True will ensure no zero frequencies, but is slower.
"""
if rebalanced:
bins = np.linspace(bin_min, bin_max, n_bins)
... | 5,317,584 |
def GetUserFansCount(user_url: str) -> int:
"""获取用户粉丝数
Args:
user_url (str): 用户个人主页 Url
Returns:
int: 用户粉丝数
"""
AssertUserUrl(user_url)
AssertUserStatusNormal(user_url)
json_obj = GetUserJsonDataApi(user_url)
result = json_obj["followers_count"]
return result | 5,317,585 |
def _validate_service_config_problem(problem: configuration_pb2.ProblemSpec,
error_msgs: List[str]) -> None:
"""Validates problem specification within service configuration."""
problem_kind = problem.WhichOneof('problems')
if problem_kind is None:
error_msgs.append('proble... | 5,317,586 |
def run_experiment(
ExperimentModule: LightningModule,
DataModule: LightningDataModule,
args: argparse.Namespace,
name: str,
globs: Optional[Dict] = None,
callback_monitor: Optional[str] = "val_loss_total",
**callback_kwargs,
):
"""Run a LightningModule with a LightningDataModule.
T... | 5,317,587 |
def majority_vote(labels):
"""assumes labels sorted by distance ASC"""
vote_counts = Counter(labels)
winner, winner_count = vote_counts.most_common(1)[0]
num_winners = len([count
for count in vote_counts.values()
if count == winner_count])
... | 5,317,588 |
def primitive_vertices_sphere(
radius: Floating = 0.5,
segments: Integer = 8,
intermediate: Boolean = False,
origin: ArrayLike = np.array([0, 0, 0]),
axis: Union[Literal["+z", "+x", "+y", "yz", "xz", "xy"], str] = "+z",
) -> NDArray:
"""
Returns the vertices of a latitude-longitude sphere pr... | 5,317,589 |
def VtuDiff(vtu1, vtu2, filename = None):
"""
Generate a vtu with fields generated by taking the difference between the field
values in the two supplied vtus. Fields that are not common between the two vtus
are neglected. If probe is True, the fields of vtu2 are projected onto the cell
points of vtu1. Otherwi... | 5,317,590 |
def senv(key, default=NoDefault, required=False, settings=None, _altered_defaults=None, _defaults=None):
"""
return the value for key by checking the following sources:
- the environment
- the settings dictionary
if the key is in _defaults but not in _altered_defaults, don't consider the val... | 5,317,591 |
def average_balance_observer(validator_type):
""" A function factory that returns an observer function"""
def obs_func(state):
validators = state["network"].validators
validator = validators[0]
head = br.specs.get_head(validator.store)
current_state = validator.store.block_states... | 5,317,592 |
def invalidate_model(model):
"""
Invalidates all caches for given model.
NOTE: This is a heavy artilery which uses redis KEYS request,
which could be relatively slow on large datasets.
"""
conjs_keys = redis_client.keys('conj:%s:*' % get_model_name(model))
if isinstance(conjs_keys, str... | 5,317,593 |
def get_channel_members_names(channel):
"""Returns a list of all members of a channel. If the member has a nickname, the nickname is used instead of their name, otherwise their name is used"""
names = []
for member in channel.members:
if member.nick is None:
names.append(member.name)
... | 5,317,594 |
def _build( ):
"""
Build the project.
This step handles:
Checking library dependencies.
Checking which files need to be built.
And spawning a build thread for each one that does.
"""
if _guiModule:
_guiModule.run()
built = False
global _building
_building = True
for project in _shared_globals.sortedPro... | 5,317,595 |
def rodframe_display(parameters):
"""
"""
n.image(pyllusion_path + "frame.png", rotate=-1*parameters["Frame_Angle"], size=parameters["Frame_Size"])
n.image(pyllusion_path + "rod_red.png", rotate=-1*parameters["Rod_Angle"], size=parameters["Rod_Size"]) | 5,317,596 |
def getRaCfg(name, default):
""" Gets a config attribute, if not set, return the default. """
if 'raCfg' in config:
if name in config['raCfg'] and isinstance(config['raCfg'][name], bool):
return config['raCfg'][name]
return default | 5,317,597 |
def quat_mean(quaternions: typing.Sequence[typing.Union[typing.Sequence, np.ndarray]]) -> np.ndarray:
"""
Find the mean of a bunch of quaternions
Fails in some pathological cases where the quats are widely distributed.
:param quaternions:
:return:
"""
if len(quaternions) <= 0:
retur... | 5,317,598 |
def get_element_dict(propname='mass_number'):
""" Obtain dictionary of elements ordered by a property.
"""
prop_dict = {k:getattr(elements[k], propname) for k in elements.keys()}
elems = list(elements.keys())
props = list(prop_dict.values())
# Sort the element list by the masses
srtse... | 5,317,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.