content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
async def health() -> Dict[str, str]:
"""Health check function
:return: Health check dict
:rtype: Dict[str, str]
"""
health_response = schemas.Health(name=settings.PROJECT_NAME,
api_version=__version__)
return health_response.dict() | 5,347,700 |
def controls(pressed_list):
""" Paddles control function"""
global plr_y, enm_y
if pressed_list[pg.K_w] and plr_y >= 0:
plr_y -= 3
if pressed_list[pg.K_s] and plr_y <= window_h - 20:
plr_y += 3
if pressed_list[pg.K_UP] and enm_y >= 0:
enm_y -= 3
if pressed_list[pg.K_DOWN... | 5,347,701 |
def detail(video_id):
""" return value is
[
{
'video_path' : s
},
{
'person_id': n,
'person_info_list' : [
{
'frame' : n
'millisec' : n
... | 5,347,702 |
def list_terminologies():
""" Get the list of available Amazon Translate Terminologies for this region
Returns:
This is a proxy for boto3 get_terminology and returns the output from that SDK method.
See `the boto3 documentation for details <https://boto3.amazonaws.com/v1/documentation/api/lates... | 5,347,703 |
def RunLinters(prefix, name, data, settings=None):
"""Run linters starting with |prefix| against |data|."""
ret = []
if settings is None:
settings = ParseOptions([])
ret += settings.errors
linters = [x for x in FindLinters(prefix) if x not in settings.skip]
for linter in linters:
functor = glob... | 5,347,704 |
def watchdog_mock():
"""Mock watchdog module."""
with patch.dict('sys.modules', {
'watchdog': MagicMock(),
'watchdog.observers': MagicMock(),
'watchdog.events': MagicMock(),
}):
yield | 5,347,705 |
def customization_data(client=None):
"""Produce any customization definitions (types, fields, message destinations, etc)
that should be installed by `resilient-circuits customize`
"""
# This import data contains:
# Incident fields:
# mock_incident_field
# Action fields:
# ... | 5,347,706 |
def element_norm_spatial_exoao(processes,
comp_sol,
test_time,
test_var_list,
exact_solution,
subel_ints = 1,
zfill=None,
... | 5,347,707 |
def generate_close_coordinates(
draw: st.DrawFn, prev_coord: Coordinates[str, np.float64]
) -> Coordinates[str, np.float64]:
"""Create coordinates using Hypothesis."""
diff = [
draw(hynp.from_dtype(np.dtype(np.float64), min_value=0.1, max_value=1.0)),
draw(hynp.from_dtype(np.dtype(np.float64... | 5,347,708 |
def redistribute_vertices(
geom: Union[LineString, MultiLineString],
distance: float
) -> Union[LineString, MultiLineString]:
"""Redistribute the vertices of input line strings
Parameters
----------
geom : LineString or MultiLineString
Input line strings whose vertices i... | 5,347,709 |
def test_predict_is_intervals_bbvi():
"""
Tests prediction intervals are ordered correctly
"""
model = pf.GASReg(formula="y ~ x1", data=data, family=pf.Poisson())
x = model.fit('BBVI', iterations=100)
predictions = model.predict_is(h=10, intervals=True)
assert(np.all(predictions['99% Predict... | 5,347,710 |
def test_sanity(ec2_resource, args):
"""Test if env vars are set, key exists, and can access ec2"""
if args.profile is None:
for var in mand_vars:
if os.environ.get(var) is None:
print(var + ' must be set as an evironment variable. \nExiting.')
exit(1)
if ... | 5,347,711 |
def get_boolean_value(value):
"""Get the boolean value of the ParameterValue."""
if value.type == ParameterType.PARAMETER_BOOL:
return value.bool_value
else:
raise ValueError('Expected boolean value.') | 5,347,712 |
def test_update_3():
"""
does not update if input is incorrect
"""
table_name = "table_2"
table_name_2 = "table_1"
result_1 = DB.update(
table_name=table_name,
fields={
"field_1": "2",
"field_12": "New Field"
},
where={
"field_8... | 5,347,713 |
def eval_bayesian_optimization(net: torch.nn.Module, input_picture: DATA,\
label_picture: DATA, ) -> float:
""" Compute classification accuracy on provided dataset to find the optimzed hyperparamter
settings.
Args:
net: trained neural network
Input: The image
Label: Th la... | 5,347,714 |
def parse(url):
"""
URL-parsing function that checks that
- port is an integer 0-65535
- host is a valid IDNA-encoded hostname with no null-bytes
- path is valid ASCII
Args:
A URL (as bytes or as unicode)
Returns:
A (scheme, host,... | 5,347,715 |
def show_label_images(input_yaml, wait_ms=10):
"""
Shows and draws pictures with labeled traffic lights.
Can save pictures.
:param input_yaml: Path to yaml file
:param wait_ms: wait time in milliseconds before OpenCV shows next image
"""
label_list = {'off':0, 'green':1, 'yellow':2, 'red':3... | 5,347,716 |
def is_amicable(num: int) -> bool:
""" Returns whether the number is part of an amicable number pair """
friend = sum(divisors(num)) - num
# Only those in pairs are amicable numbers. If the sum is the number itself, it's a perfect number
return friend != num and sum(divisors(friend)) - friend == num | 5,347,717 |
def apply_connector_types(inferred: TypeInferenceDict):
""" Applies the inferred connector types on the SDFG. """
for (node, conn, is_in), dtype in inferred.items():
if dtype.type is None:
continue
if is_in:
node.in_connectors[conn] = dtype
else:
node... | 5,347,718 |
def threaded_encode_job(job):
"""
Given a job, run it through its encoding workflow in a non-blocking manner.
"""
# Update the timestamp for when the node last did something so it
# won't terminate itself.
NodeStateManager.i_did_something()
job.nommer.onomnom() | 5,347,719 |
def no_data_info():
"""Returns information about not having enough information yet to display"""
return html.Div(children=[dcc.Markdown('''
# Please wait a little bit...
The MongoDB database was probably just initialized and is currently empty. You will need to wait a bit (~30 min) for it to pop... | 5,347,720 |
def delta_t(soil_type):
""" Displacement at Tu
"""
delta_ts = {
"dense sand": 0.003,
"loose sand": 0.005,
"stiff clay": 0.008,
"soft clay": 0.01,
}
return delta_ts.get(soil_type, ValueError("Unknown soil type.")) | 5,347,721 |
def extractPlate(imgOriginal, listOfMatchingChars, PlateWidthPaddingFactor, PlateHeightPaddingFactor):
""" Extract license-plate in the provided image, based on given contours group that corresponds for matching characters """
# Sort characters from left to right based on x position:
listOfMatchingChars.so... | 5,347,722 |
def create_stratified_name(stem, stratification_name, stratum_name):
"""
generate a standardised stratified compartment name
:param stem: str
the previous stem to the compartment or parameter name that needs to be extended
:param stratification_name: str
the "stratification" or rational... | 5,347,723 |
def eda_stream_test(freq_hz=4):
"""
Capture EDA data for 30s, check the data for frequency(default 4Hz) mismatch
:param freq_hz: Frequency in which the Sampling should happen(HZ)
:return:
"""
capture_time = 30
common.dcb_cfg('d', 'eda')
common.quick_start_eda(freq_hz)
time.sleep(cap... | 5,347,724 |
def bind_args_kwargs(sig: inspect.Signature, *args: typing.Any, **kwargs: typing.Any) -> typing.List[BoundParameter]:
"""Bind *args and **kwargs to signature and get Bound Parameters.
:param sig: source signature
:type sig: inspect.Signature
:param args: not keyworded arguments
:type args: typing.A... | 5,347,725 |
def user(user_type):
"""
:return: instance of a User
"""
return user_type() | 5,347,726 |
def true_or_false(item):
"""This function is used to assist in getting appropriate
values set with the PythonOption directive
"""
try:
item = item.lower()
except:
pass
if item in ['yes','true', '1', 1, True]:
return True
elif item in ['no', 'false', '0', 0, None, Fal... | 5,347,727 |
def validate_task(task, variables, config=None):
""" Validate that a simulation can be executed with OpenCOR
Args:
task (:obj:`Task`): request simulation task
variables (:obj:`list` of :obj:`Variable`): variables that should be recorded
config (:obj:`Config`, optional): BioSimulators co... | 5,347,728 |
def time_ms():
"""currently pypy only has Python 3.5.3, so we are missing Python 3.7's time.time_ns() with better precision
see https://www.python.org/dev/peps/pep-0564/
the function here is a convenience; you shall use `time.time_ns() // 1e6` if using >=Python 3.7
"""
return int(time.time() * 1e3) | 5,347,729 |
def _fetch_git_repo(uri, version, dst_dir):
"""
Clone the git repo at ``uri`` into ``dst_dir``, checking out commit ``version`` (or defaulting
to the head commit of the repository's master branch if version is unspecified).
Assumes authentication parameters are specified by the environment, e.g. by a Gi... | 5,347,730 |
def _calculate_mk(tp, fp, tn, fn):
"""Calculate mk."""
ppv = np.where((tp + fp) > 0, tp / (tp + fp), np.array(float("nan")))
npv = np.where((tn + fn) > 0, tn / (tn + fn), np.array(float("nan")))
npv = tn / (tn + fn)
numerator = ppv + npv - 1.0
denominator = 1.0
return numerator, denominator | 5,347,731 |
def geometric_progression_for_stepsize(
x, update, dist, decision_function, current_iteration
):
"""Geometric progression to search for stepsize.
Keep decreasing stepsize by half until reaching
the desired side of the boundary.
"""
epsilon = dist / np.sqrt(current_iteration)
while True:
... | 5,347,732 |
def absorption_two_linear_known(freq_list, interaction_strength, decay_rate):
""" The absorption is half the imaginary part of the susecptibility. """
return susceptibility_two_linear_known(freq_list, interaction_strength,
decay_rate).imag/2.0 | 5,347,733 |
def mad(x, mask, base_size=(11, 3), mad_size=(21, 21), debug=False, sigma=True):
"""Calculate the MAD of freq-time data.
Parameters
----------
x : np.ndarray
Data to filter.
mask : np.ndarray
Initial mask.
base_size : tuple
Size of the window to use in (freq, time) when
... | 5,347,734 |
def post_to_conf(post_grid, cell_size):
"""
Converts a N-dimensional grid of posterior values into a grid of confidence levels. The posterior values do not need
to be normalised, i.e. their distribution need not integrate to 1. Works with likelihood values (not log-likelihood)
instead of posteriors, ass... | 5,347,735 |
def test_remaining_segments_with_new_segment_returns_change():
"""
Verifies that moving to a new segment decrements the number of remaining segments.
"""
grid = Grid(((3, -1, -1), (-1, 2, -1), (0, -1, -1)))
# Test first point on second segment
draw_path(grid, ((0, 0), (0, 1), (0, 2), (1, 2)))
... | 5,347,736 |
def get_fuzzer_display(testcase):
"""Return FuzzerDisplay tuple."""
if (testcase.overridden_fuzzer_name == testcase.fuzzer_name or
not testcase.overridden_fuzzer_name):
return FuzzerDisplay(
engine=None,
target=None,
name=testcase.fuzzer_name,
fully_qualified_name=testcase.... | 5,347,737 |
def process_articles_results(articles_list):
"""
Function that processes the articles result and transform them to a list of Objects
Args:
articles_list: A list of dictionaries that contain sources details
Returns :
articles_results: A list of source objects
"""
articles_... | 5,347,738 |
def list_to_bytes_list(strList):
"""
This function turns an array of strings into a pointer array
with pointers pointing to the encodings of those strings
Possibly contained bytes are kept as they are.
:param strList: List of strings that shall be converted
:type strList: List of strings
:r... | 5,347,739 |
def handle_td(element, box, _get_image_from_uri):
"""Handle the ``colspan``, ``rowspan`` attributes."""
if isinstance(box, boxes.TableCellBox):
# HTML 4.01 gives special meaning to colspan=0
# http://www.w3.org/TR/html401/struct/tables.html#adef-rowspan
# but HTML 5 removed it
# ... | 5,347,740 |
def login_flags(db, host, port, user, db_prefix=True):
"""
returns a list of connection argument strings each prefixed
with a space and quoted where necessary to later be combined
in a single shell string with `"".join(rv)`
db_prefix determines if "--dbname" is prefixed to the db argument,
sinc... | 5,347,741 |
def glplot(ncfile, times, colora, label):
"""
add a plot of grounding line points to current axes.
makes use of the numpy.ma.MaskedArray when reading xGL,yGL
"""
try:
ncid = Dataset(ncfile, 'r')
except:
print("Failed to open file: {}. Skipping.".format(ncfile))
return 350.0,... | 5,347,742 |
def roi_intersect(a, b):
"""
Compute intersection of two ROIs.
.. rubric:: Examples
.. code-block::
s_[1:30], s_[20:40] => s_[20:30]
s_[1:10], s_[20:40] => s_[10:10]
# works for N dimensions
s_[1:10, 11:21], s_[8:12, 10:30] => s_[8:10, 11:21]
"""
def slice_inter... | 5,347,743 |
def _create_file(file_name, size):
"""Create a file with the file size is size"""
file = open(file_name, "w")
file.seek(size)
file.write('\x00')
file.close() | 5,347,744 |
def _flows_finished(pgen_grammar, stack):
"""
if, while, for and try might not be finished, because another part might
still be parsed.
"""
for stack_node in stack:
if stack_node.nonterminal in ('if_stmt', 'while_stmt', 'for_stmt', 'try_stmt'):
return False
return Tru... | 5,347,745 |
def PositionToPercentile(position, field_size):
"""Converts from position in the field to percentile.
position: int
field_size: int
"""
beat = field_size - position + 1
percentile = 100.0 * beat / field_size
return percentile | 5,347,746 |
def grid(num, ndim, large=False):
"""Build a uniform grid with num points along each of ndim axes."""
if not large:
_check_not_too_large(np.power(num, ndim) * ndim)
x = np.linspace(0, 1, num, dtype='float64')
w = 1 / (num - 1)
points = np.stack(
np.meshgrid(*[x for _ in range(ndim)], indexing='ij'),... | 5,347,747 |
def rolling_outlier_quantile(x, width, q, m):
"""Detect outliers by multiples of a quantile in a window.
Outliers are the array elements outside `m` times the `q`'th
quantile of deviations from the smoothed trend line, as calculated from
the trend line residuals. (For example, take the magnitude of the... | 5,347,748 |
def append_gopath_to_env(envfile: str):
"""
Append the go path to the user's shell profile.
Args:
envfile (str): path to the env file, auto generated
"""
# open the current active shell source file and append the go path
print('Appending go path to $PATH')
with open(envfile, 'a') as... | 5,347,749 |
def set_parameter(root, name, value):
""" sets parameter to value """
for child in root.iter('Parameter'):
if child.attrib['name'] == name:
child.attrib['value'] = str(value) | 5,347,750 |
def compute_region_classification_len(dataset_output,
dataset_type: str):
"""
Compute the number of points per class and return a dictionary (dataset_type specifies the keys) with the results
"""
stable_region_indices, marginal_stable_region_indices, marginal... | 5,347,751 |
def merge_rdn(merged_image_file, mask_file, sensors):
""" Merge radiance images.
Arguments:
merged_image_file: str
Merged radiance image filename.
mask_file: str
Background mask filename.
sensors: dict
Sensor dictionaries.
"""
if os.path.exist... | 5,347,752 |
def set_world_properties(world_uid, world_name=None, owner=None, config=None):
""" Set the properties of the given world """
return runtime.set_world_properties(world_uid, world_name, owner, config) | 5,347,753 |
def sort(values, key=None):
"""Perform an in-place sort on 'values', which must be a mutable sequence."""
if len(values) <= 1:
return
if key is None:
_quicksortBetween(values, 0, len(values) - 1, 1, lambda x, y: x < y)
else:
_quicksortBetween(values, 0, len(values) - 1, 1, lambd... | 5,347,754 |
def _resize_and_pad(img, desired_size):
"""
Resize an image to the desired width and height
:param img:
:param desired_size:
:return:
"""
old_size = img.shape[:2] # old_size is in (height, width) format
ratio = float(desired_size) / max(old_size)
new_size = tuple([int(x * ratio) fo... | 5,347,755 |
def _terminal_size(fallback: Tuple[int, int]) -> Tuple[int, int]:
"""
Try to get the size of the terminal window.
If it fails, the passed fallback will be returned.
"""
for i in (0, 1):
try:
window_width = os.get_terminal_size(i)
return cast(Tuple[int, int], tuple(win... | 5,347,756 |
def dropout(x, name=None):
"""
Compute a new tensor with `dropoutRate` perecent set to zero. The values
that are set to zero are randomly chosen. This is commonly used to prevent
overfitting during the training process.
The output tensor has the same shape as `x`, but with `dropoutRate` of the
... | 5,347,757 |
def mol2graph(crystal_batch: CrystalDataset, args: Namespace) -> BatchMolGraph:
"""
Converts a list of SMILES strings to a BatchMolGraph containing the batch of molecular graphs.
:param crystal_batch: a list of CrystalDataset
:param args: Arguments.
:return: A BatchMolGraph containing the com... | 5,347,758 |
def _compile(s: str):
"""compiles string into AST.
:param s: string to be compiled into AST.
:type s: str
"""
return compile(
source = s,
filename = '<unknown>',
mode = 'eval',
flags = ast.PyCF_ONLY_AST,
) | 5,347,759 |
def result_logger(result_dict, epoch_num, result_path='./results', model_name='model', make_dir=True):
"""
saves train results as .csv file
"""
log_path = result_path + '/logs'
file_name = model_name + '_results.csv'
directory_setter(log_path, make_dir)
save_path = os.path.join(log_path, fil... | 5,347,760 |
def rename_storms(
top_input_dir_name, first_date_unix_sec, last_date_unix_sec,
first_id_number, max_dropout_time_seconds, top_output_dir_name):
"""Renames storms. This ensures that all storm IDs are unique.
:param top_input_dir_name: Name of top-level directory with input files
(proce... | 5,347,761 |
def test_mark_dirty_fat32():
"""Test that _mark_dirty is able to mark partition as dirty."""
pf = PyFat()
pf.fat_type = pf.FAT_TYPE_FAT32
fat_orig = [0xFFFFFF8, 0xFFFFFFF]
pf.fat = list(fat_orig)
pf.fat_header = {"BS_Reserved1": 0x0}
with mock.patch('pyfatfs.PyFat.PyFat.flush_fat') as ff:
... | 5,347,762 |
def temp_get_users_with_permission_form(self):
"""Used to test that swapping the Form method works"""
# Search string: ABC
return () | 5,347,763 |
def create_resource_types(raml_data, root):
"""
Parse resourceTypes into ``ResourceTypeNode`` objects.
:param dict raml_data: Raw RAML data
:param RootNode root: Root Node
:returns: list of :py:class:`.raml.ResourceTypeNode` objects
"""
# TODO: move this outside somewhere - config?
acce... | 5,347,764 |
def plot_roc(y_test, y_score, title=None,n_classes=3,lw=2):
"""
plot roc for classification y_score of y_test
Parameters
----------
y_test: true class for test set
y_score: classification score
title: to save as eps
Default: None (only show but not save it)
n... | 5,347,765 |
def verify_inclusion(position, R, geometries_nodes, allNodes, ax):
"""
Quick function, with drawing, to verify if a particle is inside or not.
"""
h = np.linspace(0, 1, 100)
ax.plot(position[0] + 0.5*R*np.cos(2*np.pi*h),
position[1] + 0.5*R*np.sin(2*np.pi*h),
color='cyan', li... | 5,347,766 |
def permute_images(images, permutation_index):
"""
Permute pixels in all images.
:param images: numpy array of images
:param permutation_index: index of the permutation (#permutations = #tasks - 1)
:return: numpy array of permuted images (of the same size)
"""
# seed = np.random.randint(low... | 5,347,767 |
def generate_random_urdf_box(save_path, how_many):
"""
generate 10 boxes - to change the limits of dimensions modify $rand_box_shape$
source: http://wiki.ros.org/urdf/Tutorials/Adding%20Physical%20and%20Collision%20Properties%20to%20a%20URDF%20Model
"""
scale = 0.03
cube_height = 0.03
grippe... | 5,347,768 |
def atanh(x) -> float:
"""
Return the inverse hyperbolic tangent of ``x``.
"""
... | 5,347,769 |
def new_user(request, id):
"""
Page for creating users after registering a person.
person must be either volunteer, NGO employee or Government
"""
msg = ''
password = ''
try:
person_id = int(id)
# Get Name
user = RegPerson.objects.get(pk=person_id)
personfna... | 5,347,770 |
def transformAndSaveResultsAsTiff(filename, segmentation, predictions, transform):
""" Saves results as tiff:
segmentation : name of the segmentation
filename: full filename with the extention
image_file : file of the size for the classifiacation
"""
csvfilename, npz_filename, image_file_green, ... | 5,347,771 |
def multi_conv(func=None, options=None):
"""A function decorator for generating multi-convolution operations.
Multi-convolutions allow for a set of data-independent convolutions to be
executed in parallel. Executing convolutions in parallel can lead to an
increase in the data throughput.
The ``multi_conv`` f... | 5,347,772 |
def use_fixture(obj, name, force):
"""Switch to fixture with given name."""
if not force:
click.confirm(
f'Are you sure you want to change the database to fixture "{name}"?',
abort=True,
)
api = lib.get_api(**obj)
poll, NoTaskResultYet = api.dbctl_action("use_fixt... | 5,347,773 |
def hi_joseangel():
""" Hi Jose Angel Function """
return "hi joseangel!" | 5,347,774 |
def test_as_meg_type_evoked():
"""Test interpolation of data on to virtual channels."""
# validation tests
raw = read_raw_fif(raw_fname)
events = mne.find_events(raw)
picks = pick_types(raw.info, meg=True, eeg=True, stim=True,
ecg=True, eog=True, include=['STI 014'],
... | 5,347,775 |
def main():
"""Main function call to test the shortest_path function."""
test(shortest_path) | 5,347,776 |
def received_date_date(soup):
"""
Find the received date received_date_date in human readable form
"""
received_date = get_history_date(soup, date_type = "received")
date_string = None
try:
date_string = time.strftime("%B %d, %Y", received_date)
except(TypeError):
# Date did not convert
pass
return date_s... | 5,347,777 |
def is_on(hass, entity_id):
""" Returns if the group state is in its ON-state. """
state = hass.states.get(entity_id)
if state:
group_type = _get_group_type(state.state)
# If we found a group_type, compare to ON-state
return group_type and state.state == _GROUP_TYPES[group_type][0]... | 5,347,778 |
def pytest_report_header(config, startdir):
"""return a string to be displayed as header info for terminal reporting."""
capabilities = config.getoption('capabilities')
if capabilities:
return 'capabilities: {0}'.format(capabilities) | 5,347,779 |
def chessboard_distance(x_a, y_a, x_b, y_b):
"""
Compute the rectilinear distance between
point (x_a,y_a) and (x_b, y_b)
"""
return max(abs(x_b-x_a),abs(y_b-y_a)) | 5,347,780 |
def bayesnet():
"""
References:
https://class.coursera.org/pgm-003/lecture/17
http://www.cs.ubc.ca/~murphyk/Bayes/bnintro.html
http://www3.cs.stonybrook.edu/~sael/teaching/cse537/Slides/chapter14d_BP.pdf
http://www.cse.unsw.edu.au/~cs9417ml/Bayes/Pages/PearlPropagation.html
... | 5,347,781 |
def safe_makedirs(directory, mode=0o777):
"""Create a directory and all its parent directories, unless it already
exists.
"""
if not os.path.isdir(directory):
os.makedirs(directory, mode) | 5,347,782 |
def command(task_id, tail, wip, limit):
"""
Use this command to show a task or all the tasks.
$ trackmywork show
id;time;project;category;links;started_at;finished_at
1;Starting a new task;2h;trackmywork;personal;;2018-08-11 14:41:39.584405;
2;Starting a second task;2h;trackmywork;personal;;201... | 5,347,783 |
def sigma_R(sim, Pk=None, z=None, non_lin=False):
""" return amplitude of density fluctuations
if given Pk -- C++ class Extrap_Pk or Extrap_Pk_Nl -- computes its sigma_R.
if given redshift, computes linear or non-linear (emulator) amplitude of density fluctuations """
sigma = fs.Data_Vec_2()
if Pk:... | 5,347,784 |
def test_displays_all_error_messages():
"""By default, ParseFixer stops on errors and outputs a message
listing all encountered errors."""
expected_error_msg = dedent(
"""\
Stopped parsing after 2 errors in table 'farm_cols1' with messages:
Duplicate column 'flt' at position 4 in tab... | 5,347,785 |
def session_ended_request_handler(handler_input):
"""Handler for Session End."""
# type: (HandlerInput) -> Response
logger.info("Entering AMAZON.SessionEndedRequest")
save_data(handler_input)
return handler_input.response_builder.response | 5,347,786 |
def _getTestSuite(testFiles):
"""
Loads unit tests recursively from beneath the current directory.
Inputs: testFiles - If non-empty, a list of unit tests to selectively run.
Outputs: A unittest.TestSuite object containing the unit tests to run.
"""
loader = unittest.TestLoader()
if testF... | 5,347,787 |
def stratifiedsmooth2stratifiedwavy_c(rho_gas, rho_liq, vel_gas, d_m, beta, mu_liq, mu_gas):
"""
function for construction of boundary transition from stratified-smooth to stratified-wavy structure
resulting from the "wind" effect
:param rho_gas: gas density
:param rho_liq: liquid density
:para... | 5,347,788 |
def box(
data_frame=None,
x=None,
y=None,
color=None,
facet_row=None,
facet_row_weights=None,
facet_col=None,
facet_col_weights=None,
facet_col_wrap=0,
facet_row_spacing=None,
facet_col_spacing=None,
hover_name=None,
hover_data=None,
custom_data=None,
animatio... | 5,347,789 |
def main():
"""Run script."""
tic = perf_counter()
# fetch buzz data, create DataFrame, and clean it
current_df = create_df()
add_team_position_column(current_df)
clean_player_column(current_df)
add_pct_column(current_df)
add_timestamp_column(current_df)
# dump DataFrame to MySQL
... | 5,347,790 |
def _infer_main_columns(df, index_level='Column Name', numeric_dtypes=_numeric_dtypes):
"""
All numeric columns up-until the first non-numeric column are considered main columns.
:param df: The pd.DataFrame
:param index_level: Name of the index level of the column names. Default 'Column Name'
:param... | 5,347,791 |
def index():
"""
显示首页
:return:
"""
return render_template('index.html') | 5,347,792 |
def float2int_rz(x):
"""
See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_float2int_rz.html
:param in: Argument.
:type in: float32
:rtype: int32
""" | 5,347,793 |
def two_phase(model, config):
"""Two-phase simulation workflow."""
wea_path, datetime_stamps = get_wea(config)
smx = gen_smx(wea_path, config.smx_basis, config.mtxdir)
pdsmx = prep_2phase_pt(model, config)
vdsmx = prep_2phase_vu(model, config)
if not config.no_multiply:
calc_2phase_pt(mo... | 5,347,794 |
def str_with_tab(indent: int, text: str, uppercase: bool = True) -> str:
"""Create a string with ``indent`` spaces followed by ``text``."""
if uppercase:
text = text.upper()
return " " * indent + text | 5,347,795 |
def delete(card, files=None):
"""Delete individual notefiles and their contents.
Args:
card (Notecard): The current Notecard object.
files (array): A list of Notefiles to delete.
Returns:
string: The result of the Notecard request.
"""
req = {"req": "file.delete"}
if fi... | 5,347,796 |
def p_vars_1(p):
"""
vars : empty
"""
p[0] = [] | 5,347,797 |
def test_timed_info():
"""Test timed_info decorator"""
@timed_info
def target():
return "hello world"
result = target()
assert result == "hello world" | 5,347,798 |
def get_doc_word_token_set(doc: Doc, use_lemma=False) -> Set[Token]:
"""Return the set of tokens in a document (no repetition)."""
return set([token.lemma_ if use_lemma else token.text for token in get_word_tokens(doc)]) | 5,347,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.