content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def gsea_results_to_filtered_df(
dataset,
kegg_manager: Optional[bio2bel_kegg.Manager] = None,
reactome_manager: Optional[bio2bel_reactome.Manager] = None,
wikipathways_manager: Optional[bio2bel_wikipathways.Manager] = None,
p_value: Optional[float] = None,
absolute_nes_f... | 5,312,400 |
def grib_release(msgid):
"""
@brief Free the memory for the message referred to by msgid.
\b Examples: \ref grib_get_keys.py "grib_get_keys.py"
@param msgid id of the message loaded in memory
@exception GribInternalError
"""
GRIB_CHECK(_internal.grib_c_release(msgid)) | 5,312,401 |
def _updateMaskedValueSet():
"""
For every param in conf
has MASK_INPUT enabled keep the user input
in the 'masked_value_set'
"""
global masked_value_set
for confName in controller.CONF:
# Add all needed values to masked_value_set
if (controller.getParamKeyValue(confName, "MA... | 5,312,402 |
def save_send_msg_stats(prof, *args, **kwargs):
"""
Saves _send_msg profiling information in SEND_MSG_STATS_LOG file.
"""
sender = kwargs.get("self", args[0])
encoded_message_wrapper = kwargs.get("message_json", args[1])
recipient = kwargs.get("recipient", args[2])
timestamp = datetime.now... | 5,312,403 |
def create_network(request, id_vlan="0", sf_number='0', sf_name='0', sf_environment='0', sf_nettype='0', sf_subnet='0', sf_ipversion='0', sf_network='0', sf_iexact='0', sf_acl='0'):
""" Set column 'active = 1' in tables """
try:
if request.method == 'POST':
form = CreateForm(request.POST)
... | 5,312,404 |
def build(recipes_dir):
"""
Read the recipes from the dir and make rst files out of them.
"""
sys.stderr.write("\nBUILDING THE COOKBOOK RECIPES:\n")
cbdir = 'cookbook'
# Clean the cookbook dir to remove old files
if os.path.exists(cbdir):
for f in os.listdir(cbdir):
os.re... | 5,312,405 |
def _order_fun(term: List[List[int]], weight: Union[float, complex] = 1.0):
"""
Return a normal ordered single term of the fermion operator.
Normal ordering corresponds to placing the operator acting on the
highest index on the left and lowest index on the right. In addition,
the creation operators ... | 5,312,406 |
def plot_sensors(*sensors, **kwargs):
"""
Plot data of sensor arrays.
Opens a window and plots each sensor array in a different row. The window
builds a subplot for each sensor array.
Parameters
----------
sensors : arrays
Arrays of sensors to plot. Each array is of size M-by-N, wh... | 5,312,407 |
def quick_plot(data):
"""Make a quick plot of the FFI with sane screen stretch
Returns:
None
"""
m, s = np.mean(data), np.std(data)
plt.imshow(data, interpolation='nearest', cmap='gray', vmin=m-s, vmax=m+s, origin='lower')
plt.colorbar(); | 5,312,408 |
def validate(number):
"""Check if the number provided is a valid RNC."""
number = compact(number)
if not number.isdigit():
raise InvalidFormat()
if number in whitelist:
return number
if len(number) != 9:
raise InvalidLength()
if calc_check_digit(number[:-1]) != number[-1]... | 5,312,409 |
def test_initialize_fails(
mock_ote_response: "OTEResponse",
ids: "Callable[[Union[ResourceType, str]], str]",
server_url: str,
testdata: "Callable[[Union[ResourceType, str]], dict]",
) -> None:
"""Check `Filter.fetch()` raises `ApiError` upon request failure."""
from otelib.exceptions import Ap... | 5,312,410 |
def backtrack(p_i, p_c, heads, i, j, complete):
"""Backtrack the position matrix of eisner to generate the tree"""
if i == j:
return
if complete:
r = p_c[i, j]
backtrack(p_i, p_c, heads, i, r, False)
backtrack(p_i, p_c, heads, r, j, True)
else:
r, heads[j] = p_i[i... | 5,312,411 |
def bindwith(*mappings, **kwargs):
"""Bind variables to a function's outer scope, but don't yet call the function.
>>> @bindwith(cheez='cheddar')
... def makez_cheezburger():
... bun = ...
... patty = ...
... cheezburger = [bun, patty, cheez, bun]
>>> makez_cheezburger.outer_sc... | 5,312,412 |
def _call(calls):
"""Make final call"""
final_call = ''
if calls['is_hiv'] == 'No':
final_call = 'NonHIV'
return final_call
if calls['deletion'] == 'Yes':
final_call = 'Large Deletion'
if calls['inversion'] == 'Yes':
final_call += ' with Internal Inversion'
... | 5,312,413 |
def load_madminer_settings(file_name: str, include_nuisance_benchmarks: bool) -> tuple:
"""
Loads the complete set of Madminer settings from a HDF5 data file
Parameters
----------
file_name: str
HDF5 file name to load the settings from
include_nuisance_benchmarks: bool
Whether o... | 5,312,414 |
def namespace2dict(namespace):
"""
Converts recursively namespace to dictionary. Does not work if there is a namespace whose
parent is not a namespace.
"""
d = dict(**namespace)
for k, v in d.items():
if isinstance(v, NamespaceMap):
d[k] = namespace2dict(v)
return d | 5,312,415 |
def editGenre(genre_id):
""" Edits the genre
"""
editedGenre = session.query(Genre).filter_by(id=genre_id).one()
if editedGenre.user_id != login_session['user_id']:
return """<script>(function() {alert("not authorized");})();</script>"""
if request.method == 'POST':
if request.form['... | 5,312,416 |
def potential_fn(scale, coefs, preds, x):
"""Linear regression"""
y = jnp.dot(x, coefs)
logpdf = stats.norm.logpdf(preds, y, scale)
return -jnp.sum(logpdf) | 5,312,417 |
def van32(**kwargs):
"""Constructs a 32 layers vanilla model.
"""
model = Vanilla(*make_layers(32), **kwargs)
return model | 5,312,418 |
def indices(record):
"""
Generalization of Mapping.keys().
@type: record: Record[Any, Any]
@rtype: Iterator[Any]
@raises: TypeError
"""
if isinstance(record, collections.Mapping):
if hasattr(record, 'keys'):
return iter(record.keys())
else:
return iter... | 5,312,419 |
def my_request_classifier(environ):
""" Returns one of the classifiers 'dav', 'xmlpost', or 'browser',
depending on the imperative logic below"""
request_method = REQUEST_METHOD(environ)
if request_method in _DAV_METHODS:
return "dav"
useragent = USER_AGENT(environ)
if useragent:
... | 5,312,420 |
def bisection_solve(x, power, epsilon, low, high):
"""x, epsilon, low, high are floats
epsilon > 0
low <= high and there is an ans between low and high s.t.
ans**power is within epsilon of x
returns ans s.t. ans**power within epsilon of x"""
ans = (high + low)/2
while abs... | 5,312,421 |
def main():
"""
Main process of the game.
Execute all classes and manage event returned by pygame.
"""
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
sound = Sound()
sound.generate_sound()
# Menu
menu = Menu()
game = False
config = True
... | 5,312,422 |
def get_distinct_rotations(structure, symprec=0.1, atol=1e-6):
"""
Get distinct rotations from structure spacegroup operations
Args:
structure (Structure): structure object to analyze and
get corresponding rotations for
symprec (float): symprec for SpacegroupAnalyzer
ato... | 5,312,423 |
def teardown_logging():
"""
Cleanup any logging fixtures created from :func:`initialize_logging()`. Should
be called at the end of your script.
"""
global _LOGGING_HOST, _LOGGING_PORT, _LOGGING_SERVER, _LOGGING_SERVER_THREAD
if _LOGGING_SERVER is not None:
_LOGGING_SERVER.abort = True
... | 5,312,424 |
def get_sierpinski_carpet_set(width, height):
"""
获得谢尔宾斯基地毯点集
:param width:
:param height:
:return: 谢尔宾斯基地毯点集
"""
def get_sierpinski_carpet_points(left, top, right, bottom):
"""
递归获取谢尔宾斯基地毯的点
:param left:
:param top:
:param right:
:param botto... | 5,312,425 |
def find_target_node(ctx, stmt, is_instance_allowed = False):
"""Find the target node for the 'refine' or 'augment' statements"""
parent = stmt.parent
if stmt.arg == '.':
return parent
# parse the path into a list of two-tuples of (prefix,identifier)
pstr = '/' + stmt.arg
path = [... | 5,312,426 |
def destroy_asteroids(angles):
"""Destroy asteroids, start with laser pointing up and rotate clockwise."""
destroy_list = []
sorted_angles = sorted(angles)
while sorted_angles:
for angle in sorted_angles:
if not angles[angle]:
sorted_angles.remove(angle)
e... | 5,312,427 |
def two_color_swap(bt, col1, col2, freq=10, duration=10):
"""[makes the colors swap back and forth next to each other]
Arguments:
col1 {[RGB]} -- [color from RGB class]
col2 {[RGB]} -- [color from RGB class]
freq {[float]} -- [number of times per second transition occurs]
durati... | 5,312,428 |
def zoom(image, zoom_scale):
"""
TODO: Check that this works for odd, even zoom_scale
TODO: write tests
Zooms in on center of image, with a representative zoom_scale.
Inputs:
:image: (numpy array) image to be zoomed in on.
:zoom_scale: (int) length of side of box of zoomed image, i... | 5,312,429 |
def _get_multipart_param(param_name: str, count: int, ssm) -> str:
"""You must pass the count returned from _get_num_multiparts"""
param_value = ""
i = 0
for i in range(count):
param_value += ssm.get_parameter(Name=_get_multipart_param_part_name(param_name, i))[
"Parameter"
]... | 5,312,430 |
def get_lrs(lr:slice, count:Optional[int]=None):
"""
Exponentially increasing lr from
slice.start to slice.stop.
if `count is None` then count = int(stop/start)
"""
lr1 = lr.start
lr2 = lr.stop
if count is None:
count = int(lr2/lr1)
incr = np.exp((np.log(lr2/lr1)/(c... | 5,312,431 |
def install_softcurrent_turn():
"""
turn to current 10 day's line chart of yesterday soft install top 10
:return:
"""
return render_template("cb_soft_install_crnt_line_show.html") | 5,312,432 |
def load_browser(profile, url):
"""open Chrome browser in new window,
with the given user profile and loads the specified URLs
Declaimer: for browser task automation is better to use the built-in webbrowser module
"""
cmd = "google-chrome"
args = "--new-window --profile-directory=" + "'{:s}' {:s}".format... | 5,312,433 |
def setup_rbsite():
"""Set up rb-site's console and logging."""
global console
# Ensure we import djblets.log for it to monkey-patch the logging module.
import_module('djblets.log')
logging.basicConfig(level=logging.INFO)
console = init_console() | 5,312,434 |
def test_file_not_found(tmpdir, parameter):
"""
Test that providing a missing file for a file parameter returns a
non-zero exit code.
:param tmpdir: Temporary directory (pytest built-in fixture)
:type tmpdir: py._path.local.LocalPath
:param parameter: Parameter
:type parameter: str or unico... | 5,312,435 |
def DB_backup(DB_pano_base, DB_panos, DB_connectors, DB_roads):
"""backup the db in the PostgreSQL
Args:
DB_pano_base ([type]): [description]
DB_panos ([type]): [description]
DB_connectors ([type]): [description]
DB_roads ([type]): [description]
"""
config_local = {"con"... | 5,312,436 |
def test_correct_atag():
"""Tests that the correct 'tags' are returned given the specified R group. e.g. A1 would be a correct return for R1
and B3 for R2 etc."""
test_data = pd.read_csv(os.path.join(cwd, 'test_get_selec.csv'))
test_selection = select_mols.get_selection('R1', 3, test_data)
assert (... | 5,312,437 |
def register_model(name, base_filename, models_dir, manager, description=None):
"""Registers a new model in the given models directory.
If the directory does not have a models manifest file, one is created.
Note that new models directories are not automatically added to your
models search path, so mode... | 5,312,438 |
def make_rapl_log(appCfg, rscCfg, frequency, cores):
"""
appCfg - used for path, app, [psize]
rscCfg - used for num_cores to get all rapl core readings
frequency - used to test power with frequency
cores::string - "one" or "all"
"""
rapl_resolution = 0.1
rapl_location = rscCfg['rapl_read... | 5,312,439 |
def add_filename(json_):
"""
Args:
string: json path
Returns:
dict: annotion label
"""
with open(json_) as f:
imgs_anns = json.load(f)
img_extension = json_.split('/')[-1].split('.')[0]+'.jpg'
imgs_anns['filename'] = img_extension
return imgs_anns | 5,312,440 |
def test():
""" Function to execute unitest.
"""
suite = unittest.TestLoader().loadTestsFromTestCase(TestMemory)
runtime = unittest.TextTestRunner(verbosity=2).run(suite)
return runtime.wasSuccessful() | 5,312,441 |
def find_modules(device_path, bundles_list):
"""
Extracts metadata from the connected device and available bundles and
returns this as a list of Module instances representing the modules on the
device.
:param str device_path: The path to the connected board.
:param Bundle bundles_list: List of ... | 5,312,442 |
def sort_ordered_games_list(ordered_games_lists):
""" Reverses as sorts ordered games lists alphabetically """
new_order = OrderedDict()
for group, games in reversed(ordered_games_lists.items()):
new_order[group] = OrderedDict(
sorted(games.items(), key=lambda x: x[1].title))
retu... | 5,312,443 |
def get_challenge_id() -> int:
"""
Get the challenge ID, a number from 1 to NUMBER_OF_CHALLNEGE_VARIANTS.
"""
random_seed = get_random_seed()
random.seed(random_seed)
variant_number = random.randint(0, NUMBER_OF_CHALLENGE_VARIANTS - 1)
return variant_number | 5,312,444 |
def test_target_value_changed(device):
"""Test values changed for climate device."""
assert device.target_temperature == 1
device.values.primary.data = 2
value_changed(device.values.primary)
assert device.target_temperature == 2 | 5,312,445 |
def _conv1(in_channels, out_channels, stride=1, bias=False):
"""point-wise convolution"""
return Conv1d(in_channels, out_channels, kernel_size=1, stride=stride, bias=bias) | 5,312,446 |
def mixer_b16_224_in21k(pretrained=False, **kwargs):
""" Mixer-B/16 224x224. ImageNet-21k pretrained weights.
Paper: 'MLP-Mixer: An all-MLP Architecture for Vision' - https://arxiv.org/abs/2105.01601
"""
model_args = dict(patch_size=16, num_blocks=12, hidden_dim=768, **kwargs)
model = _create_mixer... | 5,312,447 |
def service_proxy_settings(private_base_url):
"""Change api_backend to echo-api for service2."""
return rawobj.Proxy(f"{private_base_url('echo_api')}/service1") | 5,312,448 |
def get_map_mrr(qids, predictions, labels, device=0, keep_results=False):
"""
Get the map and mrr using the trec_eval utility.
qids, predictions, labels should have the same length.
device is not a required parameter, it is only used to prevent potential naming conflicts when you
are calling this co... | 5,312,449 |
def register_app_exception_handlers(app):
"""注册应用的错误处理句柄"""
register_errorhandlers(app) | 5,312,450 |
def glob_suffixes(root_path: Path, suffixes: Union[List[str], str]) -> List[Path]:
"""Returns all suffixes located in the path and in the input variable suffixes"""
if isinstance(suffixes, str):
suffixes = [suffixes]
return sorted([f for f in root_path.glob("**/*") if file_suffix_in(f, suffixes)]) | 5,312,451 |
def init_sdc_unwarp_report_wf(name='sdc_unwarp_report_wf', forcedsyn=False):
"""
Save a reportlet showing how SDC unwarping performed.
This workflow generates and saves a reportlet showing the effect of fieldmap
unwarping a BOLD image.
Workflow Graph
.. workflow::
:graph2use: o... | 5,312,452 |
def maxabs_normalization(X, *Xtest):
"""Scale features in the [-1, 1] range.
Linearly normalize each input feature in the [-1, 1] range by
dividing them by the maximum absolute value. Test features, when
given, are scaled using the statistics computed on X.
Parameters
----------
X : ndarr... | 5,312,453 |
def authenticate_user(email, password):
"""Authenticate user by checking they exist and that the password is correct."""
user = get_user(email)
if not user:
return False
"""If present, verify password against password hash in database."""
password_hash = user.hashed_password
if not ver... | 5,312,454 |
def new_files(filetype):
"""
Find new files to download from the Census' FTP webpage.
Parameters:
filetype (character): The type of file you want to search for (.txt, .zip, ect.)
Returns (list): List of files not found in local directory
"""
pattern = pub_filename(filetype)
pub_lin... | 5,312,455 |
def positive_integer(v):
""" Is arg a positive integer? """
return integer(v) and positive(v) | 5,312,456 |
def precipitation():
"""Get the date and corresponding precipitation level or a 404 if not."""
# Query all dates
query_date = dt.date(2017, 8, 23) - dt.timedelta(days=365)
sel = [Measurement.date, Measurement.prcp]
last_twelve_months = session.query(*sel).\
filter(Measurement.date > qu... | 5,312,457 |
def alias_setup(probs):
"""
Build tables for the alias sampling
:param probs: the probability distribution to build alias table
Returns
-------
alias table and probability table for probs
"""
K = len(probs)
q = np.zeros(K)
J = np.zeros(K, dtype=np.int)
smaller = list()
larger = list()
for k... | 5,312,458 |
def sv_variant(institute_id, case_name, variant_id):
"""Display a specific structural variant."""
data = controllers.sv_variant(store, institute_id, case_name, variant_id)
return data | 5,312,459 |
def test_alm_Cl_outdated_upon_pixel_change(test_canvas):
"""Passes if after setting canvas.pixels
the status of pixels, alms, and Cls are correctly updated """
test_canvas.pixels = 1
assert not test_canvas._pixel_is_outdated
assert test_canvas._alm_is_outdated
assert test_canvas._Cl_is_outdated | 5,312,460 |
def box_yxyx_to_cxcywh(x):
""" Converts bounding box with format [y0, x0, y1, x1] to format [center_x, center_y, w, h] """
y0, x0, y1, x1 = torch.split(x, 1, dim=-1)
b = [
(x0 + x1) / 2,
(y0 + y1) / 2,
x1 - x0,
y1 - y0
]
return torch.cat(b, dim=-1) | 5,312,461 |
def deserialize_attributes(data, sep, original_class=None, original_pk=None):
"""
Deserialize the attributes from the format internally stored in the DB
to the actual format (dictionaries, lists, integers, ...
:param data: must be a dictionary of dictionaries. In the top-level dictionary,
the key... | 5,312,462 |
def get_config_float(
current: Union[int, float], config: Dict[str, str], name: str
) -> Optional[float]:
"""
Convenience function to get config values as float.
:param current: current config value to use when one is not provided
:param config: config to get values from
:param name: name of co... | 5,312,463 |
def getargs():
""" Parse program arguments.
"""
parser = argparse.ArgumentParser(
description=DESCRIPTION,
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('ori_lst', type=str,
help='original image list')
parser.add_argument('tri_lst', type=... | 5,312,464 |
def _collect_finish_info(container_dir):
"""Read exitinfo, aborted, oom and terminated files to check how container
finished.
:returns ``(exitinfo, aborted, oom, terminated)``:
Returns a tuple of exitinfo, a ``(service_name,return_code,signal)`` if
present or None otherwise, aborted reason ... | 5,312,465 |
def _httpserver_do_forests(self, req):
"""Shim this function into the httpserver so that it responds to
the forests command. It gives a list of roots relative to the
self.repo repository, sorted lexigraphically.
"""
resp = ""
if req.form.has_key('walkhg'):
forests = self.repo.forests(b... | 5,312,466 |
def getRatingDistributionOfAMovie(ratingRDD, movieID):
""" Get the rating distribution of a specific movie
Args:
ratingRDD: a RDD containing tuples of (UserID, MovieID, Rating)
movieID: the ID of a specific movie
Returns:
[(rating score, number of this rating score)]
"""
retu... | 5,312,467 |
def decode_fsw(fsw_array):
"""
Parse the array into specific faultgroups
"""
faultGroup = [0] * NUM_OF_FAULTGROUPS;
faultGroup[FAULTGROUP_TRANSIENT] = 0
faultGroup[FAULTGROUP_CRITICAL] = (fsw_array[FSW_CRITICAL_FAULTS_INDEX] & FSW_CRITICAL_FAULTS_MASK) >> FSW_CRITICAL_FAULTS_SHIF... | 5,312,468 |
def lower_allbutfirst_letter(mystring):
"""Lowercase all letters except the first one
"""
return mystring[0].upper() + mystring[1:].lower() | 5,312,469 |
def get_world_size():
"""Replace linklink.get_world_size"""
try:
world_size = get_world_size_from_env()
if world_size is not None:
return world_size
else:
# return link.get_world_size()
return dist.get_world_size()
except Exception as e: # noqa
... | 5,312,470 |
def orginal(S,R,RT,nNodes=20550):
"""
This function is used to calculate the reconstructed data from reduced variables using POD.
This function is used to deal with flow past cylinder data.
Parameters
----------
S : array
The array contains total data that combine two features as a col... | 5,312,471 |
def test_global():
"""
Tests items at the global scope not otherwise fully tested.
"""
# Since only used (right now0 for logger name which is untested code, this
# gives the best chance of detecting a mistake there.
assert main._NAME_MOD_OVERRIDE == 'asana_extensions.main' | 5,312,472 |
def _find_machines():
""" Fill in host globals from docker-machine """
env.user = "ubuntu"
machines = [json.loads(open(m).read())["Driver"]
for m in glob.glob(os.path.expanduser("~/.docker/machine/machines/*/config.json"))]
env.hostnames = [m["MachineName"] for m in machines
... | 5,312,473 |
def strtest(aString):
"""this function takes the string and returns the string in a random order"""
newstring = random.sample(aString, len(aString))
newstring = "".join(newstring)
return(newstring) | 5,312,474 |
def build_url(base_url=DEFAULT_BASE_URL, command=None):
"""Append a command (if it exists) to a base URL.
Args:
base_url (str): Ignore unless you need to specify a custom domain,
port or version to connect to the CyREST API. Default is http://127.0.0.1:1234
and the latest versio... | 5,312,475 |
def get_first_bonding_box(boxes: BoundingBoxes) -> Optional[BoundingBox]:
"""
Get the first bounding box that belongs to the trash class.
:param boxes: the list of detected bounding boxes
:return: the first box that belongs to the trash class. If no valid box can be found, return None
"""
for ... | 5,312,476 |
def svn_diff_contains_diffs(*args):
"""svn_diff_contains_diffs(svn_diff_t diff) -> svn_boolean_t"""
return _diff.svn_diff_contains_diffs(*args) | 5,312,477 |
def test_crypto_errors():
"""
This function raises errors on crypto retrieval functions.
"""
params = [
{
'columns': None,
'as_json': None
},
{
'columns': 'error',
'as_json': False
},
{
'columns': ['erro... | 5,312,478 |
def test_dot_separator():
"""should match verses preceded by dot"""
results = yvs.get_result_list('luke 4.8')
nose.assert_equal(results[0]['title'], 'Luke 4:8 (NIV)')
nose.assert_equal(len(results), 1) | 5,312,479 |
def init_shared_manager(items):
"""Initialize and start shared manager."""
for cls in items:
proxy = create_proxy(cls)
SyncManager.register(cls.__name__, cls, proxy)
manager = SyncManager()
manager.start()
return manager | 5,312,480 |
def create_csv_gpx(sender, instance, created, **kwargs):
""" Parse uploaded DJI log-file when Log was created"""
if created:
instance.create_csv_gpx() | 5,312,481 |
def config_extended_acl(
device,
acl_name,
permission=None,
protocol=None,
src_ip=None,
src_step=None,
src_wildcard=None,
dst_ip=None,
dst_step=None,
dst_wildcard=None,
dst_port=None,
entries=None,
acl_type=None,
sequence_num=None
):
""" Configure extended ACL... | 5,312,482 |
def test_TimeResult_brief(resargs):
"""Check that TimeResult.brief works as expected.
Parameters
----------
resargs : tuple
pytest fixture. See resargs.
"""
# print expected brief string
brief_ex = (
f"{resargs[2]} loops, best of {resargs[3]}: "
f"{resargs[0]:.1f} {r... | 5,312,483 |
def cnn2d(image: np.ndarray,
filters: np.ndarray):
"""
Vanilla convolutions.
Args:
image: (hi, wi, cin).
filters: (hf, wf, cin, cout).
Returns:
(hi, wi, cout)
"""
filter_len, image_padded = pad_image(filters, image)
out = np.zeros([image.shape[0], image.s... | 5,312,484 |
def mongo_uses_error_check(store):
"""
Does mongo use the error check as a separate message?
"""
if hasattr(store, 'modulestores'):
return any(mongo_uses_error_check(substore) for substore in store.modulestores)
return False | 5,312,485 |
def bootstrap_consensus(msa, times, tree_constructor, consensus):
"""Consensus tree of a series of bootstrap trees for a multiple sequence alignment.
:Parameters:
msa : MultipleSeqAlignment
Multiple sequence alignment to generate replicates.
times : int
Number of bootstr... | 5,312,486 |
def reset_start_limit_hit(duthost, service_name, timeout, interval, delay):
"""Reset service if hit start-limit-hit
Args:
duthost: Device Under Test (DUT)
service_name: Service to reset
timeout: Maximum time to wait
interval: Poll interval
delay: Delay time
"""
l... | 5,312,487 |
def get_opportunities_groups_group_id(*,
group_id,
language,
accept_language='en-us',
if_none_match=None):
"""
:param accept_language: ['de', 'en-us', 'fr', 'ja... | 5,312,488 |
def test_numpy_image_container_has_nifti(numpy_image_container: NumpyImageContainer):
""" Test that a nifty is not returned from a NumpyImageContainer """
assert not numpy_image_container.has_nifti | 5,312,489 |
def main(args):
"""
Main function for running via the command line.
`args` is the list of command line arguments.
"""
argparser = argparse.ArgumentParser(description=__doc__, fromfile_prefix_chars='@')
argparser.add_argument("input", help="Input RDF data file")
argparser.add_argument("outp... | 5,312,490 |
def get_snapshot_seconds():
"""Returns the amount of time in seconds between snapshots of a
fuzzer's corpus during an experiment."""
return environment.get('SNAPSHOT_PERIOD', DEFAULT_SNAPSHOT_SECONDS) | 5,312,491 |
def realize_question(dialog, template, filter_objs):
"""Samples attributes for template using filtered objects.
In addition, creates scene graph for the new information added.
Args:
scene: Current scene graph
template: Text template to use to generate questions
filter_objs: Set of objects satisfying... | 5,312,492 |
def coroutine(func):
"""
_coroutine_
Decorator method used to prime coroutines
"""
def start(*args,**kwargs):
cr = func(*args,**kwargs)
next(cr)
return cr
return start | 5,312,493 |
def test_inserts_new_keys():
"""Will it insert new keys by default?"""
aaa = {
'a': 1,
'b': {
'b1': 2,
'b2': 3,
},
}
bbb = {
'a': 1,
'b': {
'b1': 4,
'b3': 5
},
'c': 6,
}
assert dict_merge(aaa... | 5,312,494 |
def check_udf_files(context):
"""
Retrieves and verifies the UDF files referred to by the context.
"""
for path in context:
content = lib.get_udf_file(path)
assert lib.eq(content, context[path]), "UDF file %s has invalid content" % path | 5,312,495 |
def getCountry(isoFile, tzdir, verbose):
"""Get the dictionary containing the iso3166 country code to name conversion
Args:
isoFile (string): file name of the iso3166.tab file
tzdir (string): path holding the zoneFile
verbose (string): verbosity level
Returns:
dict: diction... | 5,312,496 |
def main():
"""
Read input and configuration parameters
"""
parser = argparse.ArgumentParser(description='Run inference with basic UNet with MONAI.')
parser.add_argument('--config', dest='config', metavar='config', type=str,
help='config file')
args = parser.parse_args()... | 5,312,497 |
def bootup():
""" Things to run after booting up
- initializer
- setup (set settings)
"""
init()
settings() | 5,312,498 |
def image_to_tensor(
image: Union[PILImage, np.ndarray, str],
roi: Optional[Rect] = None,
output_size: Optional[Tuple[int, int]] = None,
keep_aspect_ratio: bool = False,
output_range: Tuple[float, float] = (0., 1.),
flip_horizontal: bool = False
) -> ImageTensor:
"""Load an image int... | 5,312,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.