content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _get_data_tuple(sptoks, asp_termIn, label):
"""
Method obtained from Trusca et al. (2020), no original docstring provided.
:param sptoks:
:param asp_termIn:
:param label:
:return:
"""
# Find the ids of aspect term.
aspect_is = []
asp_term = ' '.join(sp for sp in asp_termIn).... | 33,400 |
def setup_environment(new_region: Path) -> bool:
"""Try to create new_region folder"""
if new_region.exists():
print(f"{new_region.resolve()} exists, this may cause problems")
proceed = input("Do you want to proceed regardless? [y/N] ")
sep()
return proceed.startswith("y")
n... | 33,401 |
def main():
"""Function: main
Description: Initializes program-wide used variables and processes command
line arguments and values.
Variables:
dir_chk_list -> contains options which will be directories.
dir_crt_list -> contain options that require directory to be created.
... | 33,402 |
def is_favorable_halide_environment(
i_seq,
contacts,
pdb_atoms,
sites_frac,
connectivity,
unit_cell,
params,
assume_hydrogens_all_missing=Auto):
"""
Detects if an atom's site exists in a favorable environment for a halide
ion. This includes coordinating by a positively charged sid... | 33,403 |
def interlock(word_list):
"""Finds all pairs of words that interlock to form a word also in the list"""
for word in word_list:
first_word = word[0::2]
second_word = word[1::2]
if first_word in word_list and second_word in word_list:
print(word, first_word, second_word) | 33,404 |
def headers():
"""Default headers for making requests."""
return {
'content-type': 'application/json',
'accept': 'application/json',
} | 33,405 |
def merge_two_lists(l1: ListNode, l2: ListNode) -> ListNode:
"""Returns a single sorted, in-place merged linked list of two sorted input linked lists
The linked list is made by splicing together the nodes of l1 and l2
Args:
l1:
l2:
Examples:
>>> l1 = linked_list.convert_list_t... | 33,406 |
def write_database_integrity_violation(results, headers, reason_message, action_message=None):
"""Emit a integrity violation warning and write the violating records to a log file in the current directory
:param results: a list of tuples representing the violating records
:param headers: a tuple of strings ... | 33,407 |
def test_merge():
""" testing the merge helper function of merge_sort """
assert merge([1], [2]) == [1, 2]
assert merge([1, 2, 4], [3, 5]) == [1, 2, 3, 4, 5] | 33,408 |
def map_SOPR_to_firm():
"""
Map SOPR identifiers to a lobbying CUID.
Return a dictionnary.
"""
firms = {}
with open(DATASET_PATH_TO['LOBBYING_FIRMS'], 'rb') as f:
reader = csv.reader(f, delimiter='%', quoting=csv.QUOTE_NONE)
for record in reader:
SOPR_reports = record[3].sp... | 33,409 |
def specialbefores_given_external_square(
befores: Set[Before],
directly_playable_squares: Set[Square],
external_directly_playable_square: Square) -> Set[Specialbefore]:
"""
Args:
befores (Set[Before]): a set of Befores used to create Specialbefores.
directly_playable_sq... | 33,410 |
def test_exit_status_unknown_user(salt_factories, master_id):
"""
Ensure correct exit status when the master is configured to run as an unknown user.
"""
with pytest.raises(FactoryNotStarted) as exc:
factory = salt_factories.get_salt_master_daemon(
master_id, config_overrides={"user"... | 33,411 |
def load_sets(path: WindowsPath = project_dir / 'data/processed') -> \
Tuple[pd.DataFrame,
pd.DataFrame,
pd.Series,
pd.Series]:
"""
:param path:
:return:
"""
import os
X_train = pd.read_csv(os.path.join(path, "X_train.csv"))
X_test = pd.r... | 33,412 |
def check_if_all_tests_pass(option='-x'):
"""Runs all of the tests and only returns True if all tests pass.
The -x option is the default, and -x will tell pytest to exit on the first encountered failure.
The -s option prints out stdout from the tests (normally hidden.)"""
import pytest
options... | 33,413 |
def register_metrics():
"""Registers all metrics used with package 'trackstats'.
Make sure this is called before using metrics.
Returns
-------
None
"""
from trackstats.models import Domain, Metric
Domain.objects.REQUESTS = Domain.objects.register(
ref='requests',
... | 33,414 |
def prim_roots(modulo: int) -> tp.Iterable[int]:
"""Calculate all :term:`primitive roots <primitive root>` for the given modulo
"""
if is_prime(modulo):
required = set(range(1, modulo))
for g in range(modulo):
powers = get_powers_modulo(g, modulo)
if powers == require... | 33,415 |
def array_to_tiff(arr, outputTiff):
"""Transform a density map array into a tiff image, to be visualized."""
arr = np.array(arr)
arr *=10000
arr = arr.astype('uint16')
arr[arr > 60000] = 0
tifffile.imsave(outputTiff, arr) | 33,416 |
def init(api, _cors, impl):
"""Configures REST handlers for allocation resource."""
namespace = webutils.namespace(
api, __name__, 'Local nodeinfo redirect API.'
)
@namespace.route('/<hostname>/<path:path>')
class _NodeRedirect(restplus.Resource):
"""Redirects to local nodeinfo end... | 33,417 |
def split_matrix_2(input1):
"""
Split matrix.
Args:
inputs:tvm.Tensor of type float32.
Returns:
akg.tvm.Tensor of type float32 with 3d shape.
"""
dim = input1.shape[0]
split_num = dim // split_dim
result_3 = allocate((split_num, split_dim, split_dim), input1.dtype, 'loc... | 33,418 |
def load_all(path, jobmanager=None):
"""Load all jobs from *path*.
This function works as a multiple execution of |load_job|. It searches for ``.dill`` files inside the directory given by *path*, yet not directly in it, but one level deeper. In other words, all files matching ``path/*/*.dill`` are used. That w... | 33,419 |
def process_img(img1, img2):
"""
图片处理
:param img1: 处理后图片
:param img2: 待处理图片
:return:
"""
cv2.imwrite(img1, img2)
target = cv2.imread(img1)
target = cv2.cvtColor(target, cv2.COLOR_BGR2GRAY)
target = abs(255 - target)
cv2.imwrite(img1, target) | 33,420 |
def relative_error(estimate, exact):
"""
Compute the relative error of an estimate, in percent.
"""
tol = 1e-15
if numpy.abs(exact) < tol:
if numpy.abs(estimate - exact) < tol:
relative_error = 0.0
else:
relative_error = numpy.inf
else:
relative_e... | 33,421 |
def AddTrainingOperators(model, softmax, label):
"""Adds training operators to the model."""
xent = model.LabelCrossEntropy([softmax, label], 'xent')
# compute the expected loss
loss = model.AveragedLoss(xent, "loss")
# track the accuracy of the model
AddAccuracy(model, softmax, label)
# use... | 33,422 |
def extract_sample_paths(seq_dir):
""" Obtain the sample paths.
Parameters
----------
seq_dir : str
Input directory containing all of the sample files.
Returns
-------
dict of list of str
Samples with a list of their forward and reverse files.
"""
fps = os.listdir(seq... | 33,423 |
def list_users(cursor):
"""
Returns the current roles
"""
cursor.execute(
"""
SELECT
r.rolname AS name,
r.rolcanlogin AS login,
ARRAY(
SELECT b.rolname
FROM pg_catalog.pg_auth_members m
JOIN pg_catalog.pg_roles b ON (m.roleid = b.oid)
W... | 33,424 |
def get_stack_policy(ctx, environment, stack):
"""
Displays the stack policy used.
Prints ENVIRONMENT/STACK policy.
"""
env = get_env(ctx.obj["sceptre_dir"], environment, ctx.obj["options"])
response = env.stacks[stack].get_policy()
write(response.get('StackPolicyBody', {})) | 33,425 |
def getVelocityRange(vis, options={}):
"""
Parse the velocity range from uvlist.
Useful when resampling and re-binning data in `line` selections
Returns a tuple of the form (starting velocity, end velocity)
"""
options['vis'] = vis
options['options'] = 'spec'
specdata = uvlist(options, stdout=subprocess.PIPE)... | 33,426 |
def polynomial_classification():
"""Classification using the Perceptron algorithm and polynomial features
"""
students_data_set = load_grades()
students_data_set = preprocess_data(students_data_set, poly_features=True)
X_train = students_data_set['train_data']
X_test = students_data_set['t... | 33,427 |
def get_job_exe_output_vol_name(job_exe):
"""Returns the container output volume name for the given job execution
:param job_exe: The job execution model (must not be queued) with related job and job_type fields
:type job_exe: :class:`job.models.JobExecution`
:returns: The container output volume name
... | 33,428 |
def bytes2human(n, format='%(value).1f %(symbol)s', symbols='customary'):
"""
Convert n bytes into a human readable string based on format.
symbols can be either "customary", "customary_ext", "iec" or "iec_ext",
see: http://goo.gl/kTQMs
>>> bytes2human(0)
'0.0 B'
>>> bytes2human(0.9)
... | 33,429 |
def test_example(save_to_file, progress_bar, tmp_path, file_cache):
"""basic test: retrieve an example dataset """
# get the reference dataset
dataset_id, ref_csv, ref_df, ref_shape = ref_dataset_public_platform()
# check the cache status
cached_entry = None
if file_cache:
cache_root =... | 33,430 |
def check_if_free(driver, available, movie_hulu_url):
"""
Check if "Watch Movie" button is there
if not, it's likely available in a special package (Starz etc) or availabe for Rent on Hulu.
"""
is_free = False
if available:
driver.get(movie_hulu_url)
sleep(3)
watch_movie_button = driver.find_elements_... | 33,431 |
def scatter_add(data, indices, updates, axis=0):
"""Update data by adding values in updates at positions defined by indices
Parameters
----------
data : relay.Expr
The input data to the operator.
indices : relay.Expr
The index locations to update.
updates : relay.Expr
... | 33,432 |
def LTE_end(verbose=False):
"""Clean disconnection of the LTE network. This is required for
future successful connections without a complete power cycle between.
Parameters
----------
verbose : bool, print debug statements
"""
if verbose: print("Disonnecting LTE ... ", end='')
lte_modem... | 33,433 |
def generate_test_linked_list(size=5, singly=False):
"""
Generate node list for test case
:param size: size of linked list
:type size: int
:param singly: whether or not this linked list is singly
:type singly: bool
:return: value list and generated linked list
"""
assert size >= 1
... | 33,434 |
def write_galaxy_provenance(gi,history_id,output_dir):
"""
Writes provenance information from Galaxy to JSON output files.
:param history_id: The history id in Galaxy to examine.
:param output_dir: The directory to write the output files.
:return: None.
"""
histories_provenance_file=out... | 33,435 |
def process_install_task(self):
"""Creates the installation task for the current task generator; uses :py:func:`waflib.Build.add_install_task` internally."""
self.add_install_task(**self.__dict__) | 33,436 |
def build(build_args=None, docs_dir=None, build_dir=None, fmt=None, open_url=False):
"""Use sphinx-build to build the documentation."""
status = sphinx_build(build_args)
if status:
sys.exit(status)
if open_url and fmt == 'html':
webbrowser.open(str(build_dir / 'index.html')) | 33,437 |
def _bytes_to_long(bytestring, byteorder):
"""Convert a bytestring to a long
For use in python version prior to 3.2
"""
result = []
if byteorder == 'little':
result = (v << i * 8 for (i, v) in enumerate(bytestring))
else:
result = (v << i * 8 for (i, v) in enumerate(reversed(byt... | 33,438 |
def cli():
"""Utility to update dependency requirements for `aiida-core`.
Since `aiida-core` fixes the versions of almost all of its dependencies, once in a while these need to be updated.
This is a manual process, but this CLI attempts to simplify it somewhat. The idea is to remote all explicit version
... | 33,439 |
def process_manifest_for_key(manifest, manifest_key, installinfo,
parentcatalogs=None):
"""Processes keys in manifests to build the lists of items to install and
remove.
Can be recursive if manifests include other manifests.
Probably doesn't handle circular manifest referen... | 33,440 |
def SoS_exec(script: str, _dict: dict = None, return_result: bool = True) -> None:
"""Execute a statement."""
if _dict is None:
_dict = env.sos_dict.dict()
if not return_result:
if env.verbosity == 0:
with contextlib.redirect_stdout(None):
exec(
... | 33,441 |
def main():
"""hash-it main entry point"""
try:
from hashit.cli.cli import cli_main
sys.exit(cli_main(docopt(__doc__)))
except KeyboardInterrupt:
sys.exit(130) | 33,442 |
def aten_dim(mapper, graph, node):
""" 构造获取维度的PaddleLayer。
TorchScript示例:
%106 : int = aten::dim(%101)
参数含义:
%106 (int): 输出,Tensor的维度。
%101 (Tensor): 输入的Tensor。
"""
scope_name = mapper.normalize_scope_name(node)
output_name = mapper._get_outputs_name(node)[0]
lay... | 33,443 |
def test_iterdict(reference):
""" GIVEN a dict for iteration """
# WHEN passing dict to this function
dict_gen = iterdict(reference)
# THEN it will create dict generator, we can iterate it, get the key, values as string
for key, value in dict_gen:
assert isinstance(key, str)
assert ... | 33,444 |
def create_config(config: HMAConfig) -> None:
"""
Creates a config, exception if one exists with the same type and name
"""
_assert_initialized()
config._assert_writable()
# TODO - we should probably sanity check here to make sure all the fields
# are the expected types, because lolpy... | 33,445 |
def regenerate():
"""Automatically regenerate site upon file modification"""
local('pelican -r -s pelicanconf.py') | 33,446 |
def calcBlockingMatrix(vs , NC = 1 ):
"""Calculate the blocking matrix for a distortionless beamformer,
and return its Hermitian transpose."""
vsize = len(vs)
bsize = vsize - NC
blockMat = numpy.zeros((vsize,bsize), numpy.complex)
# Calculate the perpendicular projection operator 'PcPerp'... | 33,447 |
def test_main_expression_parser_if_not():
"""
UT for main
"""
tree = ET.parse(os.path.join(os.path.split(__file__)[0], "tc1_exec_type_driver.xml"))
# get root element
root = tree.getroot()
# getting steps
steps = root.find("Steps")
sstep = steps[6]
data_repository = {'step_1_resu... | 33,448 |
def plot_LA(mobile, ref, GDT_TS, GDT_HA, GDT_ndx,
sel1="protein and name CA", sel2="protein and name CA",
cmap="GDT_HA", **kwargs):
"""
Create LocalAccuracy Plot (heatmap) with
- xdata = residue ID
- ydata = frame number
- color = color-coded pair distance
.. Note... | 33,449 |
def calculate_psfs(output_prefix):
"""Tune a family of comparable line-STED vs. point-STED psfs.
"""
comparison_filename = os.path.join(output_prefix, 'psf_comparisons.pkl')
if os.path.exists(comparison_filename):
print("Loading saved PSF comparisons...")
comparisons = pickle.load(open(c... | 33,450 |
def update(uuid: UUID, obj: BaseModel, db_table: DeclarativeMeta, db: Session):
"""Updates the object with the given UUID in the database.
Designed to be called only by the API since it raises an HTTPException."""
# Try to perform the update
try:
result = db.execute(
sql_update(db_t... | 33,451 |
def simulateGVecs(pd, detector_params, grain_params,
ome_range=[(-np.pi, np.pi), ],
ome_period=(-np.pi, np.pi),
eta_range=[(-np.pi, np.pi), ],
panel_dims=[(-204.8, -204.8), (204.8, 204.8)],
pixel_pitch=(0.2, 0.2),
... | 33,452 |
def get_logger(name: str):
"""Get logger call.
Args:
name (str): Module name
Returns:
Logger: Return Logger object
"""
logger = logging.getLogger(name)
logger.setLevel(logging.INFO)
logger.addHandler(get_file_handler())
logger.addHandler(get_stream_handler())
return... | 33,453 |
def intel(csifile, index, ntxnum=2):
"""csitool"""
print("="*40+"[intel]")
members = [s for s in dir(csiread.Intel) if not s.startswith("__") and callable(getattr(csiread.Intel, s))]
print("Methods: \n ", members)
print('Time:')
last = default_timer()
csidata = csiread.Intel(csifile, ntxnum... | 33,454 |
def create_label_colormap(dataset=_PASCAL):
"""Creates a label colormap for the specified dataset.
Args:
dataset: The colormap used in the dataset.
Returns:
A numpy array of the dataset colormap.
Raises:
ValueError: If the dataset is not supported.
"""
if dataset == _PASCAL:
return create... | 33,455 |
async def delete_messages_by(context, target: int, name=None):
"""Delete all messages from a user."""
guild = context.guild
async with context.typing():
delete_gen = _delete_messages(guild, delete_messages_by_target(target))
member = guild.get_member(target)
target_user = bot.get_use... | 33,456 |
def verify_access_profile(access_profile):
"""
Verify IdentityNow Access profile.
"""
assert access_profile['id'] is not None
assert access_profile['name'] is not None
assert access_profile['source'] is not None
assert access_profile['entitlements'] is not None
assert access_profile['ent... | 33,457 |
def test_continuousopacityflags():
"""Code coverage tests for ContinuousOpacityFlags() class and methods.
"""
cof = ContinuousOpacityFlags()
assert cof.smelib[2] == 1
cof['H-'] = False
assert cof.smelib[2] == 0
with raises(ValueError):
cof['H++'] = True
with raises(ValueError):
... | 33,458 |
def SDM_lune(params, dvals, title=None, label_prefix='ham='):
"""Exact calculation for SDM circle intersection. For some reason mine is a slight upper bound on the results found in the book. Uses a proof from Appendix B of the SDM book (Kanerva, 1988). Difference is neglible when norm=True."""
res = expected_i... | 33,459 |
def font_match(obj):
"""
Matches the given input againts the available
font type matchers.
Args:
obj: path to file, bytes or bytearray.
Returns:
Type instance if matches. Otherwise None.
Raises:
TypeError: if obj is not a supported type.
"""
return match(obj, f... | 33,460 |
async def insert_new_idol(*args):
"""
Insert a new idol.
"""
await self.conn.execute(f"INSERT INTO groupmembers.member({', '.join(IDOL_COLUMNS)}) VALUES "
f"({', '.join([f'${value}' for value in range(1, len(IDOL_COLUMNS) + 1)])})", *args) | 33,461 |
def test_pde_vector():
""" test PDE with a single vector field """
eq = PDE({"u": "vector_laplace(u) + exp(-t)"})
assert eq.explicit_time_dependence
assert not eq.complex_valued
grid = grids.UnitGrid([8, 8])
field = VectorField.random_normal(grid)
res_a = eq.solve(field, t_range=1, dt=0.01,... | 33,462 |
def process_image(debug=False):
"""Processes an image by:
-> sending the file to Vision Azure api
-> returns a dictionary containing the caption
and confidence level associated with that image
TODO implement
"""
# get the json data
json_data = response.json()
if json_... | 33,463 |
def time_monotonically_increases(func_or_granularity):
"""
Decorate a unittest method with this function to cause the value
of :func:`time.time` and :func:`time.gmtime` to monotonically
increase by one each time it is called. This ensures things like
last modified dates always increase.
We make... | 33,464 |
def vis_step(writer, step, dicts):
"""
Add several curves.
"""
for k in dicts:
writer.add_scalar(k, dicts[k], step) | 33,465 |
def rotate_coordinates(coords: np.ndarray, axis_coords: np.ndarray) -> np.ndarray:
"""
Given a set of coordinates, `coords`, and the eigenvectors of the principal
moments of inertia tensor, use the scipy `Rotation` class to rotate the
coordinates into the principal axis frame.
Parameters
------... | 33,466 |
def get_maggy_ddp_wrapper(module: Type[TorchModule]):
"""Factory function for MaggyDDPModuleWrapper.
:param module: PyTorch module passed by the user.
"""
class MaggyDDPModuleWrapper(TorchDistributedDataParallel):
"""Wrapper around PyTorch's DDP Module.
The wrapper replaces the user's... | 33,467 |
def random_jitter(cv_img, saturation_range, brightness_range, contrast_range):
"""
图像亮度、饱和度、对比度调节,在调整范围内随机获得调节比例,并随机顺序叠加三种效果
Args:
cv_img(numpy.ndarray): 输入图像
saturation_range(float): 饱和对调节范围,0-1
brightness_range(float): 亮度调节范围,0-1
contrast_range(float): 对比度调节范围,0-1
Retur... | 33,468 |
def render_orchestrator_inputs() -> Union[Driver, None]:
""" Renders input form for collecting orchestrator-related connection
metadata, and assembles a Synergos Driver object for subsequent use.
Returns:
Connected Synergos Driver (Driver)
"""
with st.sidebar.beta_container():
... | 33,469 |
def json_cache_wrapper(func, intf, cache_file_ident):
"""
Wrapper for saving/restoring rpc-call results inside cache files.
"""
def json_call_wrapper(*args, **kwargs):
cache_file = intf.config.cache_dir + '/insight_dash_' + cache_file_ident + '.json'
try: # looking into cache first
... | 33,470 |
def recode_graph(dot, new_dot, pretty_names, rules_to_drop, color=None, use_pretty_names=True):
"""Change `dot` label info to pretty_names and alter styling."""
if color is None:
color = "#50D0FF"
node_patterns_to_drop = []
with open(dot, mode='r') as dot:
with open(new_dot, mode='w') ... | 33,471 |
def type_assert_dict(
d,
kcls=None,
vcls=None,
allow_none: bool=False,
cast_from=None,
cast_to=None,
dynamic=None,
objcls=None,
ctor=None,
desc: str=None,
false_to_none: bool=False,
check=None,
):
""" Checks that every key/value in @d is an instance of @kcls: @vcls
... | 33,472 |
def get_missing_ids(raw, results):
"""
Compare cached results with overall expected IDs, return missing ones.
Returns a set.
"""
all_ids = set(raw.keys())
cached_ids = set(results.keys())
print("There are {0} IDs in the dataset, we already have {1}. {2} are missing.".format(len(all_ids), len... | 33,473 |
def _spaghettinet_edgetpu_s():
"""Architecture definition for SpaghettiNet-EdgeTPU-S."""
nodes = collections.OrderedDict()
outputs = ['c0n1', 'c0n2', 'c0n3', 'c0n4', 'c0n5']
nodes['s0'] = SpaghettiStemNode(kernel_size=5, num_filters=24)
nodes['n0'] = SpaghettiNode(
num_filters=48,
level=2,
l... | 33,474 |
def test_memoryview_supports_bytes(valid_bytes_128):
"""
Assert that the `bytes` representation of a :class:`~ulid.ulid.MemoryView` is equal to the
result of the :meth:`~ulid.ulid.MemoryView.bytes` method.
"""
mv = ulid.MemoryView(valid_bytes_128)
assert bytes(mv) == mv.bytes | 33,475 |
def edges(nodes, score) -> Iterable[Tuple[int, int]]:
"""
Return the edges of the tree with the desires score.
1. Check if the score is possible.
2. Determine the highest edge, that I can insert.
3. Insert the edge with the highest possible score.
:time: O(n)
:space: O(n)
"""
if sc... | 33,476 |
def instance_of(type):
"""
A validator that raises a :exc:`TypeError` if the initializer is called
with a wrong type for this particular attribute (checks are perfomed using
:func:`isinstance` therefore it's also valid to pass a tuple of types).
:param type: The type to check for.
:type type: t... | 33,477 |
def execute_command(command):
"""
execute command
"""
output = subprocess.PIPE
flag = 0
# for background execution
if("nohup" in command) or ("\&" in command):
output = open('result.log', 'w')
flag = 1
child = subprocess.Popen(command.split(), shell=False, stdou... | 33,478 |
def ass(stream: Stream, *args, **kwargs) -> FilterableStream:
"""https://ffmpeg.org/ffmpeg-filters.html#ass"""
return filter(stream, ass.__name__, *args, **kwargs) | 33,479 |
def record_generator(rec):
"""
Creates BioRec from SeqRec
"""
# Already in the correct format
if isinstance(rec, BioRec):
yield rec
else:
# Handling single or nested records.
if not rec.features:
# Attempts to read annotations from description.
... | 33,480 |
def resultcallback(group):
"""Compatibility layer for Click 7 and 8."""
if hasattr(group, "result_callback") and group.result_callback is not None:
decorator = group.result_callback()
else:
# Click < 8.0
decorator = group.resultcallback()
return decorator | 33,481 |
def test_non_existent_weight(base_clumper):
"""
Make sure that providing non existent weight key throws error
"""
with pytest.raises(KeyError):
base_clumper.sample(n=len(base_clumper) - 1, replace=False, weights="my-key") | 33,482 |
def get_license_matches(location=None, query_string=None):
"""
Return a sequence of LicenseMatch objects.
"""
if not query_string:
return []
from licensedcode import cache
idx = cache.get_index()
return idx.match(location=location, query_string=query_string) | 33,483 |
def deploy():
"""Run deployment tasks."""
setup_app() | 33,484 |
def bond_topology_summaries_from_csv(filename):
"""Beam DoFn for generating bare BondTopologySummary.
Args:
filename: csv file of bond topologies to read
Yields:
dataset_pb2.Entry
"""
for bt in smu_utils_lib.generate_bond_topologies_from_csv(filename):
summary = dataset_pb2.BondTopologySummary()... | 33,485 |
def test_read_additional_molecules_invalid() -> None:
"""Raises ValueError for profiles without additional molecules."""
with pytest.raises(ValueError):
read_additional_molecules(Identifier.DAY_200KM) | 33,486 |
def compute_corrector_prf(results, logger, on_detected=True):
"""
References:
https://github.com/sunnyqiny/
Confusionset-guided-Pointer-Networks-for-Chinese-Spelling-Check/blob/master/utils/evaluation_metrics.py
"""
TP = 0
FP = 0
FN = 0
all_predict_true_index = []
all_gol... | 33,487 |
def task_ut():
"""run unit-tests"""
for test in TEST_FILES:
yield {'name': test,
'actions': [(run_test, (test,))],
'file_dep': PY_FILES,
'verbosity': 0} | 33,488 |
def nonzero_sign(x, name=None):
"""Returns the sign of x with sign(0) defined as 1 instead of 0."""
with tf.compat.v1.name_scope(name, 'nonzero_sign', [x]):
x = tf.convert_to_tensor(value=x)
one = tf.ones_like(x)
return tf.compat.v1.where(tf.greater_equal(x, 0.0), one, -one) | 33,489 |
def compile_modules(current_dir: str, use_cgo: bool = False) -> None:
"""
Compile modules via GNU Make
"""
for root, dirs, files in os.walk(os.path.join(current_dir, "modules"), topdown=False):
for name in files:
if name == "Makefile":
os.chdir(root)
p... | 33,490 |
def tls_control_system_tdcops(tls_control_system):
"""Control system with time-dependent collapse operators"""
objectives, controls, _ = tls_control_system
c_op = [[0.1 * sigmap(), controls[0]]]
c_ops = [c_op]
H1 = objectives[0].H
H2 = objectives[1].H
objectives = [
krotov.Objective(... | 33,491 |
def test_verify_test_data_sanity():
"""Checks all test data is consistent.
Keys within each test category must be consistent, but keys can vary
category to category. E.g date-based episodes do not have a season number
"""
from helpers import assertEquals
for test_category, testcases in files.i... | 33,492 |
def create_new_credential(site_name,account_name, account_password):
"""Function to create a new account and its credentials"""
new_credential = Credentials(site_name,account_name, account_password)
return new_credential | 33,493 |
def test_enum_strings_changed(qtbot, signals, values, selected_index, expected):
"""
Test the widget's handling of enum strings, which are choices presented to the user, and the widget's ability to
update the selected enum string when the user provides a choice index.
This test will also cover value_ch... | 33,494 |
def create_inception_graph():
""""Creates a graph from saved GraphDef file and returns a Graph object.
Returns:
Graph holding the trained Inception network, and various tensors we'll be
manipulating.
"""
with tf.Session() as sess:
model_filename = os.path.join(
'imagenet... | 33,495 |
def prepare_request_params(
request_params: Dict, model_id: Text, model_data: Dict
) -> Dict:
""" reverse hash names and correct types of input params """
request_params = correct_types(request_params, model_data["columns_data"])
if model_data["hashed_indexes"]:
request_params = reverse_hash_nam... | 33,496 |
def get_new_data_NC():
"""Updates the global variable 'data' with new data"""
global EN_NC_df
EN_NC_df = pd.read_csv('https://en2020.s3.amazonaws.com/ncar_dash.csv')
EN_NC_df['County'] = EN_NC_df.CountyName | 33,497 |
def fib_demo():
"""使用生成器的方式生成斐波那契数列"""
ret = generator.get_sequence(20)
print(ret) | 33,498 |
def help_full(path):
"""Health Evaluation and Linkage to Primary Care
The HELP study was a clinical trial for adult inpatients recruited from
a detoxification unit. Patients with no primary care physician were
randomized to receive a multidisciplinary assessment and a brief
motivational intervention or usual... | 33,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.