content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def build_app_models_environment():
"""
Build a full test model environment for vcftestmodels.
Uses vcftestmodels.models.get_app_models_environment, which returns
an empty base.tests.helpers.AppModelsEnvironment object. Model
classes are created here but must by initialized via the object's
`mi... | 70,500 |
def extract_feats(ffs, direc="train", global_feat_dict=None):
"""
arguments:
ffs are a list of feature-functions.
direc is a directory containing xml files (expected to be train or test).
global_feat_dict is a dictionary mapping feature_names to column-numbers; it
should only be provided... | 70,501 |
def check_isis_version(major, minor=0, patch=0):
"""Checks that the current isis version is equal to or above the suplied
version."""
if ISIS_VERSION and (major, minor, patch) <= ISIS_VERISON_TUPLE:
return
msg = 'Version %s.%s.%s of isis required (%s found).'
raise VersionError(msg % (major... | 70,502 |
def print_error(msg): # pragma: no cover
""" Print error in red"""
print('{}{}{}'.format(BColors.FAIL, msg, BColors.ENDC)) | 70,503 |
def create_random_direction(weights, args, ignore='biasbn', norm='filter', model=None):
"""
Setup a random (normalized) direction with the same dimension as the weights.
Args:
weights: the given trained model
ignore: 'biasbn', ignore biases and BN parameters.
Returns:
... | 70,504 |
def test_sample_shape_array_arguments_no_sample_shape(rng_key, case):
"""Test the correctness of broadcasting when arguments can be arrays."""
samples = HalfNormal(case["sigma"]).sample(rng_key, case["sample_shape"])
assert samples.shape == case["expected_shape"] | 70,505 |
def wait_key_pressed_logical(key_name, timeout: float = None) -> bool:
"""Wait for a key or mouse/joystick button logical state to be pressed."""
return _wait_for(timeout, functools.partial(is_key_pressed_logical, key_name)) or False | 70,506 |
def calc_fc_from_fixed_Q_Brune(event_inv_params, Qs_curr_event, density, Vp, A_rad_point, surf_inc_angle_rad=0., verbosity_level=0):
"""Function to calculate fc by fitting Brune model to spectra with fixed Q."""
# Calculate f_c based on curve-fit of spectra with Brune model for fixed Q:
# Setup some data ou... | 70,507 |
def test_mobius_transformer_reference(batch_size, n_features, blocks, gate):
"""Compare PyTorch and reference implementation of sum-of-squares transformer."""
x, w, gate = create_random_input(batch_size, n_features, gate=gate,
n_parameters=1, seed=0, par_func=torch.rand)
... | 70,508 |
def github_tree():
"""return `github_tree` string for a current directory. git remote required"""
fullname = github_name.get()
if not fullname:
return ""
relpath = os.path.relpath(os.getcwd(), git_root())
return "/".join([fullname, "tree/master", relpath]) | 70,509 |
def GetDefaultGithubAccessToken(
extra_access_token_paths: Optional[Iterable[Union[str, pathlib.Path]]] = None
) -> AccessToken:
"""Get a Github access token from environment variables or flags.
This function provides a uniform means to get a Github access token, resolving
the access token in the following ord... | 70,510 |
def compute_d(a, b):
"""Compute value d for golden section search."""
d = a + ((b - a) / 1.618)
return d, f(d) | 70,511 |
def test_connection_execute(mocker: MockerFixture) -> None:
"""
Test the ``execute`` method.
"""
Cursor = mocker.patch("datajunction.sql.dbapi.connection.Cursor")
connection = connect("http://localhost:8000/")
connection.execute(
"SELECT * FROM some_table WHERE name = %(name)s",
... | 70,512 |
def convert_2D_polar_line_to_conformal_line(rho, theta):
""" Converts a 2D polar line to a conformal line """
line_val = val_convert_2D_polar_line_to_conformal_line(rho, theta)
return layout.MultiVector(line_val) | 70,513 |
def B_m_def(tau, phi, **params):
"""
Implements Eq. 9.159 from Nawalka, Beliaeva, Soto (pg. 471)
"""
beta1 = beta1m(**params)
beta2 = beta2m(beta1, **params)
beta3 = beta3m(beta1, **params)
beta4 = beta4m(phi, beta1, **params)
exp_term = np.exp(beta1 * tau)
denominator = b... | 70,514 |
def get_lsf_master_url(run):
"""
path to master script
"""
d=get_lsf_dir(run)
return os.path.join(d,'%s.sh' % run) | 70,515 |
def capture_value(value, name):
"""Hygienically capture a run-time value. Used by `h[]`.
`value`: A run-time value. Must be picklable.
`name`: For human-readability.
The return value is an AST that, when compiled and run, returns the
captured value (even in another Python process later).
"""
... | 70,516 |
def delete_crime_collection():
"""
Helper function to delete crime collection in db.
"""
count = len(Crime.objects())
check_crime_duration()
for crime in Crime.objects():
duration = check_filter(crime.incident_type_primary)
if (crime.duration == None or crime.duration == ... | 70,517 |
def lzo_stream(*, length: int = 4096):
"""
Compress a string of null bytes, the length being defined by the
argument to this function.
"""
compressor = Popen(["lzop", "-c"], stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = compressor.communicate(input=b"\x00" * length)
if stderr:
... | 70,518 |
async def buy(client, event, item: (ShopItem.item_choices(), "Buy cat items with your Neko coins (NC).")):
"""Buy cat items with your Neko coins (NC)."""
neko_coins = await get_coins_helper(event.user.id)
selected_item: ShopItem = ShopItem[item]
new_balance = neko_coins - selected_item.price
if new_... | 70,519 |
def config_val(attr):
"""Query HTCondor for the value of a configuration variable using the python
bindings if available, condor_config_val otherwise
"""
try:
import htcondor
# Necessary for checking config between different flavors of HTCondor
htcondor.reload_config()
t... | 70,520 |
def upload_logs():
"""
Upload experiment logs and events to remote server.
"""
pass | 70,521 |
def like(lhs: str,
pattern: str,
wildcard: str,
singlechar: str,
escapechar: str,
not_: bool = False,
) -> 'elasticsearch_dsl.query.Query':
""" Create a filter to filter elements according to a string attribute using
wildcard expressions.
:param... | 70,522 |
def bug_to_response(bug, detailed=True):
"""Convert a Bug entity to a response object."""
response = osv.vulnerability_to_dict(bug.to_vulnerability())
response.update({
'isFixed': bug.is_fixed,
'invalid': bug.status == osv.BugStatus.INVALID
})
if detailed:
add_links(response)
add_source_i... | 70,523 |
def get_current_path() -> str:
"""Get current path of script/executable"""
application_path = ""
if getattr(sys, "frozen", False):
application_path = path.dirname(sys.executable)
elif __file__:
application_path = path.dirname(__file__)
return application_path | 70,524 |
def get_pmc(uid, metadata_df, directory='data/cord-19/'):
"""
In:
uid [str]: cord-uid of required file
metadata_df: DataFrame containing metadata for file
Returns:
json of required file"""
uid_df = metadata_df[metadata_df.cord_uid == uid]
pmc = uid_df.iloc[0].pmc_json_files
... | 70,525 |
def parse_cidr(value):
"""Process cidr ranges."""
klass = IPv4Network
if '/' not in value:
klass = ipaddress.ip_address
try:
v = klass(str(value))
except (ipaddress.AddressValueError, ValueError):
v = None
return v | 70,526 |
def lab_mean_std(im_input, mask_out=None):
"""Compute the mean and standard deviation of the intensities.
... of each channel of the given RGB image in LAB color space.
The outputs of this function is for reinhard normalization.
Parameters
----------
im_input : array_like
An RGB image
... | 70,527 |
def extract_frames(src_video_path, every_nth=(5, 64)):
"""Save every 5th and 64th frame from a video as images."""
print('Processing', src_video_path)
video_name = pathlib.Path(src_video_path).stem
dst_folder_path = pathlib.Path(src_video_path).parents[1] / 'Images' / video_name
os.makedirs(dst_fold... | 70,528 |
def test_one_parse_invalid(parse: comb.Parser,
source: t.Iterable[str],
) -> None:
"""One(f) parser must raise CantParse."""
with pytest.raises(comb.CantParse):
parse(as_tokens(source)) | 70,529 |
def sel(host, args, session):
"""
prints out the bmc alerts
@param host: string, the hostname or IP address of the bmc
@param args: contains additional arguments used by the sel sub command
@param session: the active session to use
@param args.json: boolean, ... | 70,530 |
def main():
"""
This function replace code from MySQL generate
by MySQL Workbench to PostgreSQL SQL
with some modifications to Pauliceia
"""
with open(__OUTPUT_SQL_FILE__, 'a') as file_output, open(__READ_SQL_FILE__, 'r') as file_read:
text = file_read.read() # read everything in the fi... | 70,531 |
def read_order_metrics(csvfile, required=False):
"""
Read oredred metrics.
Routine to read in ordered list of metrics csv file.
Not really csv but easily read in by csv package. This is a line by line
ordered list of the metrics that will be plotted on a NAC plot. It should
be read in and out ... | 70,532 |
def _enable_logging(out_dir, debug, overwrite):
"""
Turns on logging, sets debug levels and assigns a log file
"""
logger = logging.getLogger()
log_file = os.path.join(out_dir, "STRdust.log")
log_formatter = logging.Formatter("[%(asctime)s] %(name)s: %(levelname)s: "
... | 70,533 |
def request_passes_test(test_func, login_url=None,
redirect_field_name=REDIRECT_FIELD_NAME):
"""
Decorator for views that checks that the request passes the given test,
redirecting to the log-in page if necessary. The test should be a callable
that takes the requst object and ret... | 70,534 |
def main(val_file, res_file, numRecom):
""" Main function of the evalrecom script """
numRecom = float(numRecom)
res_files = os.listdir(res_file)
print("\tFiles to work: ")
print(res_files)
lst_val = readValFile(val_file)
print("\n\tNumber of lines in validation file: {}".format(len(lst_val... | 70,535 |
def generate_dataset_code(id): # noqa: E501
"""generate_dataset_code
Generate sample code to use dataset in a pipeline # noqa: E501
:param id:
:type id: str
:rtype: ApiGenerateCodeResponse
"""
return util.invoke_controller_impl() | 70,536 |
def GetManagedRelationalDbClass(cloud):
"""Get the ManagedRelationalDb class corresponding to 'cloud'.
Args:
cloud: name of cloud to get the class for
"""
return resource.GetResourceClass(BaseManagedRelationalDb, CLOUD=cloud) | 70,537 |
def main():
""" Main route """
# Query logs
query_logs = []
# Update params with user's settings
params = get_params()
# Get query
default_user_query = "What do we know about Chloroquine to treat covid-19?"
try:
user_query = str(
request.form["user_query"]
... | 70,538 |
def normalize_summary(summary):
"""Return normalized docstring summary."""
# Remove newlines
summary = re.sub(r'\s*\n\s*', ' ', summary.rstrip())
# Add period at end of sentence
if (
summary and
(summary[-1].isalnum() or summary[-1] in ['"', "'"]) and
(not summary.startswith... | 70,539 |
def compute_metrics(data , pred_transforms):
"""
Compute metrics required in the paper
"""
def square_distance(src, dst):
return torch.sum((src[:, :, None, :] - dst[:, None, :, :]) ** 2, dim=-1)
with torch.no_grad():
pred_transforms = pred_transforms
gt_transforms = data['tr... | 70,540 |
def get_datetime_timedelta_conversion(datetime_unit, timedelta_unit):
"""
Compute a possible conversion for combining *datetime_unit* and
*timedelta_unit* (presumably for adding or subtracting).
Return (result unit, integer datetime multiplier, integer timedelta
multiplier). RuntimeError is raised i... | 70,541 |
def create_workflow_to_resample_baw_files(name="ResampleBAWOutputs"):
"""
This function...
:param name:
:return:
"""
workflow = Workflow(name)
inputs_to_resample = ["t1_file", "t2_file", "hncma_file", "abc_file"]
other_inputs = ["reference_file", "acpc_transform"]
label_maps = ["hnc... | 70,542 |
def absorb(expression):
"""
A AND (A OR B) -> A
A OR (A AND B) -> A
A AND (NOT A OR B) -> A AND B
A OR (NOT A AND B) -> A OR B
"""
if isinstance(expression, exp.And):
return _absorb(expression, exp.Or)
if isinstance(expression, exp.Or):
return _absorb(expression, exp.And)... | 70,543 |
def test_rollback_from_delete_parent(fx_session, tmp_store):
"""When the transaction fails, file should not be deleted."""
with store_context(tmp_store):
something = Something(name='some name')
with open(os.path.join(sample_images_dir, 'iu.jpg'), 'rb') as f:
expected = f.read()
... | 70,544 |
def gen_data(shape_matrix, shape_diagonal, dtype):
"""generate valid data to test"""
input_matrix = random_gaussian(shape_matrix, miu=10, sigma=0.3).astype(dtype)
input_diagonal = random_gaussian(shape_diagonal, miu=5, sigma=0.3).astype(dtype)
# make shape_diagonal can support broadcast
if shape_mat... | 70,545 |
def pe_7():
"""Return the 10,001st prime number."""
primes = list(lpe.prime_sieve(2_000_00))
primes.sort()
return f'The 10,001st prime number is {primes[10_000]:,}.' | 70,546 |
def minimal_stat_test(agonists, antagonists, stat_test, start, stop, threshold=0.05, cache=None):
"""
Inputs a list of agonists and a list of antagonists and finds the most significant residues. We do not return
the p_value but only the residue ids.
.. note::
RMSF calculations are cached to a... | 70,547 |
def variance(values):
"""
Variance function.
"""
mean_value = mean(values)
var = 0.0
for value in values:
var = var + torch.sum(torch.sqrt(torch.pow(value-mean_value,2))).item()/len(values)
return var | 70,548 |
def task_lint():
"""Check linting"""
def run(args):
args = args or []
subprocess.run(
['flake8', 'ruly', 'test', 'setup.py', 'dodo.py', *args])
return {'actions': [run], 'pos_arg': 'args'} | 70,549 |
def update_link():
"""
This is a route for ALL NODES. When a new node is inserted in
the RING (via the '/bootstrap/node/join' route), then the neighbors of that
node must update their links, so that they point at that new node.
"""
prev_or_next = request.form['prev_or_next']
if prev_or_next... | 70,550 |
def instances_to_boxes_np(
seg: np.ndarray,
dim: int = None,
instances: Optional[Sequence[int]] = None,
) -> Tuple[np.ndarray, np.ndarray]:
"""
Convert instance segmentation to bounding boxes (not batched)
Args
seg: instance segmentation of individual classes [..., dims]
dim: number... | 70,551 |
def main():
"""Performs the auto parsing of data control to generate telemetry definitions within a python c-type for valid structures."""
##################################
# sample usage: "python basicTypes.py --bindir .\sample --objdir C:\Users\jdtarang\Intel\mono_telemetry-major2-minor0_decode\nand\g... | 70,552 |
def parseargs(description: Text) -> argparse.ArgumentParser:
""" Parse arguments """
parser = argparse.ArgumentParser(
allow_abbrev=False,
description=description
)
parser.add_argument("--server", help="Mattermost Server")
parser.add_argument("--user", help="Mattermost User")
pa... | 70,553 |
def process_log_file(cur, filepath):
"""
Process event log files and insert records into the Postgres database
:param cur: cursor reference
:param filepath: complete file path for the file to load
"""
# open log file
df = df = pd.read_hdf(filepath, lines=True)
# filter by next song act... | 70,554 |
def md5_key(string):
"""
Use this to generate filenae keys
"""
m = hashlib.md5()
m.update(string.encode('utf-8'))
return m.hexdigest() | 70,555 |
def run_all_gluon_nn_loss_operations_benchmarks(ctx, inputs):
"""Helper to run all Gluon Loss Layer benchmarks. Just runs the benchmarks with default input values.
This is just a utility to run benchmarks with all default input values.
:return: list[dict], list of dictionary of benchmark results. Each item... | 70,556 |
def usage(msgarg):
"""Print usage and exit."""
me = os.path.basename(sys.argv[0])
if msgarg:
sys.stderr.write("error: %s\n" % msgarg)
print("""\
usage: %s [options] < input > output
options:
-d increase debug msg verbosity level
-i F read from input file F
-o G write to output fil... | 70,557 |
def name_to_hash(name: str) -> int:
"""
given a name, generate a unique-ish number.
cannot simply use hash(), since that is different each
time we re-run the process...
"""
hash_v = sum([ord(c) for c in name])
print('hash_v', hash_v)
return hash_v | 70,558 |
def attack_targets_by_country(country):
"""Returns the targets list with the corresponding number of attacks in descending order of the given country."""
cur = get_db().execute('SELECT targtype1_txt, num_attacks FROM (SELECT targtype1_txt, COUNT(targtype1_txt) num_attacks FROM Attacks WHERE iso_code="{}" GROUP ... | 70,559 |
def calculate_average(list_of_nums):
"""Calculates the average of a list of numbers."""
average = calculate_sum(list_of_nums) / len(list_of_nums)
return average | 70,560 |
def delete_case_bg_job(_self, delete_case_bg_job_pk, export_job_pk):
"""Task to delete a case."""
models.run_delete_case_bg_job(pk=delete_case_bg_job_pk)
compute_project_variants_stats.delay(export_job_pk=export_job_pk) | 70,561 |
def copy_global(source: netCDF4.Dataset,
target: netCDF4.Dataset,
attributes: tuple) -> None:
"""Copies global attributes from one file to another.
Args:
source: Source object.
target: Target object.
attributes: List of attributes to be copied.
"""
... | 70,562 |
def query_introspection() -> str:
"""Retrieve available queries."""
return """query {
__type(name: "Query") {
kind
name
fields {
name
description
args {
name
description
defaultValue
}
... | 70,563 |
def re_exp_matching_backward(s, p):
"""
:type s: str for match
:type p: pattern str
:rtype: match or not
"""
def is_match(chr_for_match, match_pattern):
return match_pattern == '.' or match_pattern == chr_for_match
def match_core(str, pattern):
if pattern < 0:
re... | 70,564 |
def _batched_table_lookup(tbl, row, col):
"""Mapped 2D table lookup.
Args:
tbl: a `Tensor` of shape `[r, s, t]`.
row: a `Tensor` of dtype `int32` with shape `[r]` and values in
the range `[0, s - 1]`.
col: a `Tensor` of dtype `int32` with shape `[r]` and values in
the range `[0, t - 1]`.
... | 70,565 |
def avg_pool2d(inputs,
kernel_size,
scope,
stride=[2, 2],
padding='VALID'):
""" 2D avg pooling.
Args:
inputs: no_dropout-D tensor BxHxWxC
kernel_size: a list of 128 ints
stride: a list of 128 ints
Returns:
Variable tensor
... | 70,566 |
def repressilator():
"""Replaces the plot of the protein-only repressilator. Replaces
Python code:
def repressilator_rhs(x, t, beta, n):
'''
Returns 3-array of (dx_1/dt, dx_2/dt, dx_3/dt)
'''
x_1, x_2, x_3 = x
return np.array(
[
beta / (1... | 70,567 |
def test_url():
"""test getter/setter for the url attribute"""
url = wraptext("http://example.com/")
node1 = ExternalLink(url, brackets=False)
node2 = ExternalLink(url, wraptext("Example"))
assert url is node1.url
assert url is node2.url
node1.url = "mailto:héhehé@spam.com"
node2.url = "... | 70,568 |
def date_list(start, end):
"""
:param start: year start; format: 2017, int
:param end: year end; format: 2019, int
:return: a list include all the month
"""
assert int(start / 1000) == 0 or type(start) is int, 'start error'
assert int(end / 1000) == 0 or type(end) is int, 'end error'
... | 70,569 |
def get_y_axis_max(x, chr=None, start=0, end=0, fix_end=True):
"""
Parameters
----------
x : list
A list of bigwig files
chr : str
The name of chromosome
start : int
The start position
end : int
The end position, 0 indicate t... | 70,570 |
def index():
""" Module's Home Page """
response.view = "mad/index.html"
module_name = deployment_settings.modules[module].name_nice
response.title = module_name
return dict(module_name=module_name) | 70,571 |
def reflect_coef(ip):
"""
Computes the reflection coefficient for a plane incident P-wave.
Parameters
----------
ip : array
P-impedance.
Returns
-------
rc : array
The reflection coefficient
"""
rc=(ip[1:]-ip[:-1])/(ip[1:]+ip[:-1])
rc=np.a... | 70,572 |
def test_classifier():
"""Test that the predictions of the old and new Classifier without ADVERSARY match.
"""
old_adv_deb = OldAdversarialDebiasing(unprivileged_groups=[{'sex': 0}],
privileged_groups=[{'sex': 1}],
num_... | 70,573 |
def test_renders_svg(app, context):
"""An svg extension results in an SVG doctype and mimetype"""
with app.test_request_context():
rendered = render_response("test.svg", context)
# Remove leading indentation and encode since `render_response` returns bytes
expected_data = cleandoc(
... | 70,574 |
def subsequent_mask(size: int) -> Tensor:
"""
Mask out subsequent positions (to prevent attending to future positions)
Transformer helper function.
:param size: size of mask (2nd and 3rd dim)
:return: Tensor with 0s and 1s of shape (1, size, size)
"""
mask = np.triu(np.ones((1, size, size))... | 70,575 |
def list_reuters_codes(codes=None, report_types=None, statement_types=None):
"""
List available Chart of Account (COA) codes from the Reuters financials database
and/or indicator codes from the Reuters estimates/actuals database
Note: you must collect Reuters financials into the database before you can... | 70,576 |
def waveletdec(s, wavelet, lvl, coord):
"""
Decompose .
Args:
s (list): list of numbers representing time-series signal
wavelet (string): name of the wavelet; ex: 'sym2', 'bior1.3', etc.
lvl (int): level of decomposition; length of coeffs will be lvl+1
coord (str): genomic coordi... | 70,577 |
def _generate_samples_with_demonstrations(
demonstration_iterator: Iterator[types.Transition],
replay_iterator: Iterator[reverb.ReplaySample],
policy_to_expert_data_ratio: int,
batch_size) -> Iterator[reverb.ReplaySample]:
"""Generator which creates the sample having demonstrations in them.
It take... | 70,578 |
def concatenate_datasets(current_images, current_labels, prev_images, prev_labels):
"""
Concatnates current dataset with the previous one. This will be used for
adding important samples from the previous datasets
Args:
current_images Images of current dataset
current_labels Lab... | 70,579 |
def register_serializer(cls, *, serializer, deserializer):
"""Use the given serializer to serialize instances of type ``cls``,
and use the deserializer to deserialize the serialized object.
Args:
cls: A Python class/type.
serializer (callable): A function that converts an instances of
... | 70,580 |
def dot(v: Vector, w: Vector) -> float:
"""Returns v_1 * w_1 + ... + v_n * w_n"""
assert len(v) == len(w), "vectors must be same length"
return sum(v_i * w_i for v_i, w_i in zip(v, w)) | 70,581 |
def ww_sim(word, mat, topn=10):
"""Calculate topn most similar words to word"""
index = tok2index[word]
if isinstance(mat, sparse.csr_matrix):
v1 = mat.getrow(index)
else:
v1 = mat[index:index+1, :]
sims = cosine_similarity(mat, v1).flatten()
sindexs = np.argsort(-sims)
sim_w... | 70,582 |
def count_characters(text, whites=False):
"""
Get character count of a text
Args:
whites: If True, whitespaces are not counted
"""
if whites:
return len(text)
else:
return len(re.sub(r"\s", "", text)) | 70,583 |
async def test_import_flow_already_configured(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_setup_entry: AsyncMock,
) -> None:
"""Test the import configuration flow for an already configured entry."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.a... | 70,584 |
def get_posixtime_from_uuid(uuid1):
"""Convert the uuid1 timestamp to a standard posix timestamp
"""
assert uuid1.version == 1, ValueError('only applies to type 1')
t = uuid1.time
t = t - 0x01b21dd213814000
t = t / 1e7
return t | 70,585 |
def store_image(inputkey, inputfile):
"""Function to store the uploaded image"""
folder = storage + inputkey + "/" + inputfile.name
if not os.path.exists(folder):
default_storage.save(folder, inputfile)
else:
raise FileExistsError | 70,586 |
def remove_html(raw_text):
"""
Remove html tags
"""
text = str(raw_text)
cleaner = re.compile('<.*?>')
text = re.sub(cleaner, '', text)
return text | 70,587 |
def process_special_event(events_list: str) -> tuple:
"""Gets word list from parse events and turns into list"""
in_key_dicts = [
x in shift_key_codes or x in modifier_codes or x in codes for x in events_list
]
final_keys = []
if False not in in_key_dicts:
for word in events_list:
... | 70,588 |
def run_and_track_terminate():
"""terminate all processes started by run_and_track()"""
with g_lock:
g_state["terminate"] = True
# take reference of all running procs under lock
lst = g_children.values()
# not in lock, g_children can't grow any more once terminate or cancel is set
... | 70,589 |
def pull_words(words_file, word_length):
"""Compile set of words, converted to lower case and matching length of
start and end words.
Args:
words_file: str, name of the file containing all words
word_length: int, length of the start/end words
Returns:
words_set: set, all possible... | 70,590 |
def format_participants_packet(data: PacketParticipantsData, index: int, race: Race,
lap: int):
"""
"""
formatted_data = []
for key, value in data.to_dict().items():
if key == 'm_header':
continue
elif key.endswith('_participants'):
... | 70,591 |
def classify_cells_majority(data, burnt_samples, table, cell_type_name2idx):
"""
This function is an extension of "classify_cells". It extends to the case when you need to ensemble a list of MP trees by majority.
INPUT:
data: N*D np.array
burnt_samples: A list of MP trees
table: a da... | 70,592 |
def create_and_save_nifti(mat, path_target):
"""
Creates a nifti image from numpy array and saves it to given path.
:param mat: Numpy array.
:param path_target: String, path where to store the created nifti.
"""
new_nifti = nib.Nifti1Image(mat, np.eye(4)) # create new nifti from matrix
nib.... | 70,593 |
def display_topics(model, feature_names, no_top_words, topic_names=None):
"""
Takes in a model, feature names and number of top words, returns top words per topic
"""
for ix, topic in enumerate(model.components_):
if not topic_names or not topic_names[ix]:
print("\nTopic ", ix)
... | 70,594 |
def vertices_vector_to_matrix(vertices):
"""vertices_vector_to_matrix(vertices) -> List[List[float]]
PyPRT outputs the GeneratedModel vertex coordinates as a list. The list
contains the x, y, z coordinates of all the vertices. This function converts the
vertex list into a list of N vertex coordina... | 70,595 |
def prettify(where):
"""Prettify code with black"""
def_where = ["app", "manage.py", "config.py"]
extra = where.split(" ") if where else def_where
try:
check_call(["black"] + extra)
except CalledProcessError as e:
exit(e.returncode) | 70,596 |
def random_well_conditioned_matrix(*shape, dtype, device, mean=1.0, sigma=0.001):
"""
Returns a random rectangular matrix (batch of matrices)
with singular values sampled from a Gaussian with
mean `mean` and standard deviation `sigma`.
The smaller the `sigma`, the better conditioned
the output m... | 70,597 |
def get_index_str(n, i):
"""
To convert an int 'i' to a string.
Parameters
----------
n : int
Order to put 0 if necessary.
i : int
The number to convert.
Returns
-------
res : str
The number as a string.
Examples
--------
```python
getI... | 70,598 |
def print_red(text):
""""
Prints a sentence in the color red.
:param: text
:return: Fore.RED + Style.BRIGHT + text + Style.NORMAL + Fore.WHITE
"""
return Fore.RED + Style.BRIGHT + text + Style.NORMAL + Fore.WHITE | 70,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.