content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_getDisabledChannel_where_all_channels_are_used():
"""Get the first disabled channel."""
anode = Node('foo', 'bar')
channel1 = Channel(index=1, role=1)
channel1.settings.modem_config = 3
channel1.settings.psk = b'\x01'
channel2 = Channel(index=2, role=2)
channel3 = Channel(index=3,... | 5,343,200 |
def complexDivision(a, b):
"""
复数除法
:param a: 负数a
:param b: 负数b
:return: 返回除法结果
"""
res = np.zeros(a.shape, a.dtype)
divisor = 1. / (b[:, :, 0] ** 2 + b[:, :, 1] ** 2)
res[:, :, 0] = (a[:, :, 0] * b[:, :, 0] + a[:, :, 1] * b[:, :, 1]) * divisor
res[:, :, 1] = (a[:, :,... | 5,343,201 |
def test_int_n():
"""Test method"""
message = "n must be integer"
with raises(AssertionError):
_ = BlobFactory(n=5.0)
assert False, message | 5,343,202 |
def validate_activation_time(time):
"""
This function check that activation time not earlier than current moment
:param time: activation time
:raise ValueError
:return: None
"""
if get_date(time) < dt.now():
raise ValueError('calistra: activation time cannot be earlier '
... | 5,343,203 |
def issue(license_file, license_description, issuer_certificate, issuer_key,
license_file_password, **args):
"""issue [license file] [license description]
Issues a new license and shows information about it. You must specify the
issuer certificate and key as --issuer-certificate/key on the command... | 5,343,204 |
def dynamics_RK4(OdeFun, tspan, x, u, v):
"""
# RK4 integrator for a time-invariant dynamical system under a control, u,
and disturbance, v.
# See https://lpsa.swarthmore.edu/NumInt/NumIntFourth.html
This impl adopted from unstable-zeros's learning CBFs example for two airplanes
https://githu... | 5,343,205 |
def random_decay(num_actions=None, decay_type='polynomial_decay', start_decay_at=0,
stop_decay_at=1e9, decay_rate=0., staircase=False, decay_steps=10000,
min_exploration_rate=0):
"""Builds a random decaying exploration.
Decay a random value based on number of states and the de... | 5,343,206 |
def not_found_handler(not_found):
"""Basic not found request handler."""
return render_template('except.html',
http_excep=not_found,
message='Not resource found at this URL.',
http_code=404,
http_error="N... | 5,343,207 |
def remove_minor_regions(labeled_img, biggest_reg_lab):
"""
Set all the minor regions to background and the biggest to 1.
Returns:
A numpy array with the new segmentation.
"""
f = np.vectorize(lambda x: 1 if x == biggest_reg_lab else 0)
return f(labeled_img) | 5,343,208 |
def test_raise_10():
"""
Feature: graph raise by JIT Fallback.
Description: Test raise(string % var).
Expectation: No exception.
"""
class RaiseNet(nn.Cell):
def construct(self, x):
raise ValueError(f"The input can not be %s." % x)
with pytest.raises(ValueError) as raise... | 5,343,209 |
def get_right(html):
"""
获取公共解析部分(右边页面,用户详细资料部分)
"""
soup = BeautifulSoup(html, "html.parser")
scripts = soup.find_all('script')
pattern = re.compile(r'FM.view\((.*)\)')
cont = ''
# 这里先确定右边的标识,企业用户可能会有两个r_id
rids = []
for script in scripts:
m = pattern.search(script.strin... | 5,343,210 |
def test():
"""
Verify that the renderer can trim long file names correctly
"""
# get the renderer
from journal.Alert import Alert as alert
# the color spaces
from journal.ANSI import ANSI
# and a channel
from journal.Warning import Warning as warning
# make a channel
channe... | 5,343,211 |
def marginal_ln_likelihood_worker(task):
"""
Compute the marginal log-likelihood, i.e. the likelihood integrated over
the linear parameters. This is meant to be ``map``ped using a processing
pool` within the functions below and is not supposed to be in the
public API.
Parameters
----------
... | 5,343,212 |
def coverage(session: Session) -> None:
"""Upload coverage data."""
_install_with_constraints(session, "coverage[toml]", "codecov")
session.run("coverage", "xml", "--fail-under=0")
session.run("codecov", *session.posargs) | 5,343,213 |
def chunks(l, n):
""" Yield n successive chunks from l.
"""
newn = int(1.0 * len(l) / n + 0.5)
for i in xrange(0, n-1):
yield l[i*newn:i*newn+newn]
yield l[n*newn-newn:] | 5,343,214 |
def test_write_csv():
"""Test write_csv."""
with tempfile.TemporaryDirectory() as tmp_dir:
csv_path = Path(tmp_dir) / 'tmp.json'
utils_data.write_csv(csv_path, [['header 1', 'headder 2'], ['row 1', 'a'], ['row 2', 'b']])
result = csv_path.read_text()
assert result == 'header 1,head... | 5,343,215 |
def from_matvec(matrix, vector=None):
""" Combine a matrix and vector into an homogeneous affine
Combine a rotation / scaling / shearing matrix and translation vector into
a transform in homogeneous coordinates.
Parameters
----------
matrix : array-like
An NxM array representing the th... | 5,343,216 |
def create_parser():
"""
Creates the argparse parser with all the arguments.
"""
parser = argparse.ArgumentParser(
description='Management CLI for Enodebd',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# Add subcommands
subparsers = parser.add_subparsers(title='subcom... | 5,343,217 |
def read_file(fp, limit=DEFAULT_FILE_READ_SIZE):
"""
Return output of fp.read() limited to `limit` bytes of output from the end of file.
"""
fp.seek(0, 2) # Go to EOF
total = fp.tell()
if total > limit:
fp.seek(total - limit)
else:
fp.seek(0)
return fp.read() | 5,343,218 |
def sample_quaternions(shape=None):
"""
Effective Sampling and Distance Metrics for 3D Rigid Body Path Planning, James J. Kuffner (2004)
https://ri.cmu.edu/pub_files/pub4/kuffner_james_2004_1/kuffner_james_2004_1.pdf
"""
s = np.random.random(shape)
sigma1 = np.sqrt(1 - s)
sigma2 = np.sqrt(s)... | 5,343,219 |
def _select_free_device(existing):
"""
Given a list of allocated devices, return an available device name.
According to
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/device_naming.html
all AWS Linux instances have ``/dev/sd[a-z]`` available. However:
- ``sda`` is reserved for the root de... | 5,343,220 |
def create_target_delivery_request(get_offers_opts):
"""Converts dict representation of get_offers options to TargetDeliveryRequest object"""
return TargetDeliveryRequest(request=create_delivery_request(get_offers_opts.get("request")),
target_cookie=get_offers_opts.get("targetCo... | 5,343,221 |
def wintype_to_cdata(wintype):
"""
Returns the underlying CFFI cdata object or ffi.NULL if wintype is None.
Used internally in API wrappers to "convert" pywincffi's Python types to
the required CFFI cdata objects when calling CFFI functions. Example:
>>> from pywincffi.core import dist
>>> from... | 5,343,222 |
def GenerateOutput(target_list, target_dicts, data, params):
"""
Generates all the output files for the specified targets.
"""
options = params['options']
if options.generator_output:
def output_path(filename):
return filename.replace(params['cwd'], options.generator_output)
else:
d... | 5,343,223 |
def check_keypoint(kp, rows, cols):
"""Check if keypoint coordinates are in range [0, 1)"""
for name, value, size in zip(['x', 'y'], kp[:2], [cols, rows]):
if not 0 <= value < size:
raise ValueError(
'Expected {name} for keypoint {kp} '
'to be in the range [0.... | 5,343,224 |
def __add_contrast_tokens(mr_list, utt, slot_alignment, alt_mode=False):
"""Augments an MR with an auxiliary token indicating a pair of slots that should be contrasted in the
corresponding generated utterance.
"""
contrast_connectors = ['but', 'however', 'yet']
scalar_slots = get_scalar_slots()
... | 5,343,225 |
def driver(request_id):
"""Parquet doesn't need any special setup in the driver."""
pass | 5,343,226 |
def test_get_probable_delete_index_id_failure():
"""
Test if probable delete index id is not specified
then it should throw KeyError.
"""
with pytest.raises(KeyError):
config = CORTXS3Config()
del config._config['indexid']['probable_delete_index_id']
assert config.get_probabl... | 5,343,227 |
def get_imports(module):
"""
Return an generator with all the imports to a particular py file as string
"""
source = inspect.getsource(module)
path = inspect.getsourcefile(module)
root = ast.parse(source, path)
for node in ast.iter_child_nodes(root):
if isinstance(node, ast.Import):... | 5,343,228 |
def rating_feedback_view(incident: Incident, channel_id: str):
"""Builds all blocks required to rate and provide feedback about an incident."""
modal_template = {
"type": "modal",
"title": {"type": "plain_text", "text": "Incident Feedback"},
"blocks": [
{
"typ... | 5,343,229 |
def _GetTargetOS():
"""Returns the target os specified in args.gn file.
Returns an empty string is target_os is not specified.
"""
build_args = _GetBuildArgs()
return build_args['target_os'] if 'target_os' in build_args else '' | 5,343,230 |
def generalise_sent_pos(s):
"""
generalise sentence pattern by POS tags only
:param s:
:return:
"""
rets = []
for token in s['sent']:
e = token.idx + len(token.text)
is_matched = False
for ann in s['anns']:
if token.idx >= ann['s'] and e <= ann['e']:
... | 5,343,231 |
def add_batting_metrics(df):
"""
Adds the following columns to a given DataFrame:
PA
1B
OBP
BA
SLG
OPS
ISO
PA/HR
K
BB
BABIP
wOBA
wRAA
wRC
Args:
df (DataFrame): the DataFrame t... | 5,343,232 |
def line_break(text, line_len=79, indent=1):
"""
Split some text into an array of lines.
Enter: text: the text to split.
line_len: the maximum length of a line.
indent: how much to indent all but the first line.
Exit: lines: an array of lines.
"""
lines = [text.rstrip()]
... | 5,343,233 |
async def test_delete_cluster(
mock_client, mock_cluster_status, mock_cluster_identifier, cluster_state, expected_result
):
"""Test delete cluster async hook function by mocking return value of delete_cluster"""
mock_client.return_value.__aenter__.return_value.delete_cluster.return_value = expected_result
... | 5,343,234 |
def init_workflow(bids_path, output_path, participant_label, workdir=None):
"""Create the preprocessing workflow."""
from nipype.pipeline import engine as pe
from nibabies.workflows.anatomical.preproc import init_anat_average_wf
from nibabies.workflows.anatomical.registration import init_coregistration_... | 5,343,235 |
def visualize_spectrum(y):
"""Effect that maps the Mel filterbank frequencies onto the LED strip"""
global _prev_spectrum
y = np.copy(interpolate(y, config.N_PIXELS // 2))
common_mode.update(y)
diff = y - _prev_spectrum
_prev_spectrum = np.copy(y)
# Color channel mappings
r = r_filt.upda... | 5,343,236 |
def testDuplicateContours(glyph):
"""
Contours shouldn't be duplicated on each other.
"""
contours = {}
for index, contour in enumerate(glyph):
contour = contour.copy()
contour.autoStartSegment()
pen = DigestPointPen()
contour.drawPoints(pen)
digest = pen.getD... | 5,343,237 |
def setupGroups(root, VariableGroups):
"""
Set variable groups.
Args:
-----
VariableGroups (dict) : each entry must have the form
'<Rogue device or Variable>' :
{'groups' : [<list of groups>],
'pollInterval... | 5,343,238 |
def expand_strength(row):
"""Extracts information from Strength column and cleans remaining strengths.
Gets Additional Info and Final Volume Quantity columns from Strength.
Reformats any malformed strengths and removes commas from within numbers.
"""
strengths = row['Strength']
# search for ad... | 5,343,239 |
def dem_autoload(geometries, demType, vrt=None, buffer=None, username=None, password=None,
product='dem', nodata=None, hide_nodata=False):
"""
obtain all relevant DEM tiles for selected geometries
Parameters
----------
geometries: list[spatialist.vector.Vector]
a list of :c... | 5,343,240 |
def randomString(stringLength=6):
"""Generate a random string of fixed length """
letters = string.ascii_uppercase
return ''.join(random.choice(letters) for i in range(stringLength)) | 5,343,241 |
def create_new_record(account,userName,password):
"""
Function that creates new records for a given user account
"""
new_record = Records(account,userName,password)
return new_record | 5,343,242 |
def is_bow(vec):
"""
Checks if a vector is in the sparse Gensim BoW format
"""
return matutils.isbow(vec) | 5,343,243 |
def timeout(seconds, loop=None):
"""
Returns a channel that closes itself after `seconds`.
:param seconds: time before the channel is closed
:param loop: you can optionally specify the loop on which the returned channel is intended to be used.
:return: the timeout channel
"""
c = Chan(loop=... | 5,343,244 |
def analyse_df(df, options):
"""
Analyses a dataframe, creating a metadata object
based on the passed options. Metadata objects can be
used to apply dataset preparations across multiple platforms.
"""
_validate_options(options)
metadata = _create_metadata(options)
for proc i... | 5,343,245 |
def populate_db(session, num_participants=100, num_tips=50):
"""
Populate DB with fake data
"""
#Make the participants
participants = []
for i in xrange(num_participants):
p = fake_participant()
session.add(p)
participants.append(p)
#Make the "Elsewhere's"
for p ... | 5,343,246 |
def base_route():
"""
Base route to any page. Currently, aboutme.
"""
return redirect(url_for("pages.links")) | 5,343,247 |
def blend_normal(source, source_mask, target):
"""Blend source on top of target image using weighted alpha blending.
Args:
source (np.ndarray): Array of shape (H, W, C) which contains the source
image (dtype np.uint8).
source_mask (np.ndarray): Array of shape (H, W) which contains the
source fo... | 5,343,248 |
def load_dataset(name):
"""
Load a dataset.
"""
try:
func = loaders[name]
except KeyError:
print(f"Dataset '{name}' is not in available list: {list_datasets()}")
else:
return func() | 5,343,249 |
def display_data(params):
"""
display data with the parsed arguments
"""
# evaluation data
test_ds = datautils.get_dataflow(params.testfiles, params.batch_size, is_training=False)
itr = test_ds.as_numpy_iterator()
raw_record = next(itr)
data_sample = datautils.transform_raw_record(raw_... | 5,343,250 |
def func1():
"""
# FaaS Interactive Tutorial – Using Python & Dataloop SDK
## Concept
Dataloop Function-as-a-Service (FaaS) is a compute service that automatically runs your code based on time patterns or in response to trigger events.
You can use Dataloop FaaS to extend other Dataloop services w... | 5,343,251 |
def split_symbols_implicit_precedence(tokens, local_dict, global_dict): # pragma: no cover
"""Replace the sympy builtin split_symbols with a version respecting implicit multiplcation.
By replacing this we can better cope with expressions like 1/xyz being
equivalent to 1/(x*y*z) rather than (y*z)/x a... | 5,343,252 |
def altsumma(f, k, p):
"""Return the sum of f(i) from i=k, k+1, ... till p(i) holds true or 0.
This is an implementation of the Summation formula from Kahan,
see Theorem 8 in Goldberg, David 'What Every Computer Scientist
Should Know About Floating-Point Arithmetic', ACM Computer Survey,
Vol. 23, No... | 5,343,253 |
def action_logging(f: T) -> T:
"""
Decorates function to execute function at the same time submitting action_logging
but in CLI context. It will call action logger callbacks twice,
one for pre-execution and the other one for post-execution.
Action logger will be called with below keyword parameters... | 5,343,254 |
def decode_public_id(str_id):
"""
make numeric ID from 4-letter ID
Args:
str_id (str): ID consisting of a number and 3 alphabets
Return:
num_id (int): numeric ID
"""
def alpha2num(c):
return encoder.find(c)
def num2num(c):
return 5 if c ==... | 5,343,255 |
def get_sentence_idcs_in_split(datasplit: DataFrame, split_id: int):
"""Given a dataset split is (1 for train, 2 for test, 3 for dev), returns the set of corresponding sentence
indices in sentences_df."""
return set(datasplit[datasplit["splitset_label"] == split_id]["sentence_index"]) | 5,343,256 |
def valid_scope_list():
"""List all the oscilloscope types."""
s = "\nValid types are:\n"
s += ", ".join(DS1000C_scopes) + "\n"
s += ", ".join(DS1000E_scopes) + "\n"
s += ", ".join(DS1000Z_scopes) + "\n"
s += ", ".join(DS4000_scopes) + "\n"
s += ", ".join(DS6000_scopes) + "\n"
return s | 5,343,257 |
def process_input_file(remote_file):
"""Process the input file.
If its a GCS file we download it to a temporary local file. We do this
because Keras text preprocessing doesn't work with GCS.
If its a zip file we unpack it.
Args:
remote_file: The input
Returns:
csv_file: The local csv file to pro... | 5,343,258 |
def load():
"""Returns an instance of the plugin"""
return SyslogOutOutputPlugin | 5,343,259 |
def test_regenerate_uuids_catalog() -> None:
"""Test regeneration of uuids with updated refs in catalog."""
orig_cat = catalog.Catalog.oscal_read(catalog_path)
new_cat, uuid_lut, n_refs_updated = validator_helper.regenerate_uuids(orig_cat)
assert len(uuid_lut.items()) == 2
assert n_refs_updated == 2 | 5,343,260 |
def word_sorter(x):
"""
Function to sort the word frequency pairs after frequency
Lowest frequency collocates first - highest frerquency collocates last
"""
# getting length of list of word/frequency pairs
lst = len(x)
# sort by frequency
for i in range(0, lst):
for j i... | 5,343,261 |
def le_assinatura():
"""[A funcao le os valores dos tracos linguisticos do modelo e devolve uma assinatura a ser comparada com os textos fornecidos]
Returns:
[list] -- [description]
"""
print("Bem-vindo ao detector automático de COH-PIAH.")
print("Informe a assinatura típica de um aluno in... | 5,343,262 |
def incMagLock():
"""
rotate the text display
"""
pass | 5,343,263 |
def category_task_delete(request, structure_slug, category_slug,
task_id, structure):
"""
Deletes task from a category
:type structure_slug: String
:type category_slug: String
:type task_id: String
:type structure: OrganizationalStructure (from @is_manager)
:param ... | 5,343,264 |
def lnposterior_selection(lnprobability, sig_fact=3., quantile=75, quantile_walker=50, verbose=1):
"""Return selected walker based on the acceptance fraction.
:param np.array lnprobability: Values of the lnprobability taken by each walker at each iteration
:param float sig_fact: acceptance fraction below q... | 5,343,265 |
def space_check(board, position):
"""Returns boolean value whether the cell is free or not."""
return board[position] not in PLAYERS_MARKS | 5,343,266 |
def find_repo_root_by_path(path):
"""Given a path to an item in a git repository, find the root of the repository."""
repo = git.Repo(path, search_parent_directories=True)
repo_path = repo.git.rev_parse("--show-toplevel")
logging.debug("Repository: {}".format(repo_path))
return repo_path | 5,343,267 |
def validate_params(serializer_cls):
"""利用Serializer对请求参数进行校验"""
def decorator(func):
@functools.wraps(func)
def wrapper(request: Request):
data = request.query_params if request.method == "GET" else request.data
serializer = serializer_cls(data=data)
seriali... | 5,343,268 |
def get_pairs_observations(kdata: kapture.Kapture,
kdata_query: Optional[kapture.Kapture],
keypoints_type: str,
max_number_of_threads: Optional[int],
iou: bool,
topk: int):
"""
... | 5,343,269 |
def col2im_conv(col, input, layer, h_out, w_out):
"""Convert image to columns
Args:
col: shape = (k*k, c, h_out*w_out)
input: a dictionary contains input data and shape information
layer: one cnn layer, defined in testLeNet.py
h_out: output height
w_out: output width
Returns:
im: shape =... | 5,343,270 |
def parse_arguments(argv):
""" Parse command line arguments """
parser = create_parser()
args = parser.parse_args(argv)
if args.n is None and not args.tch:
parser.error('-n is required')
if args.m is None and args.grnm:
parser.error('-m is required')
if args.d is None and args.g... | 5,343,271 |
def parse_args() -> argparse.Namespace:
"""
Creates the parser for train arguments
Returns:
The parser
"""
parse = argparse.ArgumentParser()
parse.add_argument('--local_rank', dest='local_rank', type=int, default=0)
parse.add_argument('--port', dest='port', type=int, default=44554)... | 5,343,272 |
def fix_missing_period(line):
"""Adds a period to a line that is missing a period"""
if line == "":
return line
if line[-1] in END_TOKENS:
return line
return line + " ." | 5,343,273 |
async def main() -> int:
"""main async portion of command-line runner. returns status code 0-255"""
try:
await tome.database.connect()
return await migrations.main(
whither=args.whither, conn=tome.database.connection(), dry_run=args.dry_run
)
except KeyboardInterrupt:
... | 5,343,274 |
def getTaskStatus( task_id ) :
"""Get tuple of Instance status and corresponding status string.
'task_id' is the DB record ID."""
_inst = Instance.objects.get( id = task_id )
return ( _inst.status , STATUS2TEXT[_inst.status] ) | 5,343,275 |
def fit_affine_matrix(p1, p2):
""" Fit affine matrix such that p2 * H = p1
Hint:
You can use np.linalg.lstsq function to solve the problem.
Args:
p1: an array of shape (M, P)
p2: an array of shape (M, P)
Return:
H: a matrix of shape (P, P) that transform p2 to p1.
... | 5,343,276 |
def cnn_lstm_nd(pfac,
max_features=NUM_WORDS,
maxlen=SEQUENCE_LENGTH,
lstm_cell_size=CNNLSTM_CELL_SIZE,
embedding_size=EMBEDDING_SIZE):
"""CNN-LSTM model, modified from Keras example."""
# From github.com/keras-team/keras/blob/master/examples/imdb_cnn_... | 5,343,277 |
def updateUserPassword(userName, newPassword):
""" update the user password """
cursor = conn('open')
if cursor:
try:
cursor.execute("UPDATE user SET u_Pass= %s where u_name= %s ",
(generate_password_hash(newPassword), userName))
conn("commit")
conn('close')
except Exception as e:
return Fa... | 5,343,278 |
def mit_b1(**kwargs):
"""
Constructs a mit_b1 model.
Arguments:
"""
model = MixVisionTransformer(embed_dims=64, num_layers=[2, 2, 2, 2], num_heads=[1, 2, 5, 8], **kwargs)
return model | 5,343,279 |
def test_beams_to_bintable():
""" Check that NPOL is set """
beamlist = [Beam(1*u.arcsec)]*2
beamhdu = beams_to_bintable(beamlist)
assert beamhdu.header['NPOL'] == 0 | 5,343,280 |
def draw_img(frame, x, y, img):
"""Draw an image onto a frame
Args:
frame: Frame to modify
x: Centered x coordinate on frame
y: Centered y coordinate on frame
img: Image to draw
Returns:
ndarray: Modified frame
"""
hw = img.shape[1] // 2
hh = img.shape[... | 5,343,281 |
def GenerateConfig(_):
"""Returns empty string."""
return '' | 5,343,282 |
def calc_procrustes(points1, points2, return_tform=False):
""" Align the predicted entity in some optimality sense with the ground truth.
Does NOT align scale
https://github.com/shreyashampali/ho3d/blob/master/eval.py """
t1 = points1.mean(0) # Find centroid
t2 = points2.mean(0)
points1_t = ... | 5,343,283 |
def _check_name_func(name_func):
"""
Make sure ``name_func`` is ``None`` or a callable that
takes ``func_name``, ``kwargs`` arguments.
"""
if name_func is None:
return
if not callable(name_func):
raise ParametrizationError("name_func must be a callable or `None`")
try:
... | 5,343,284 |
def sync_trusted_origins(neo4j_session, okta_org_id, okta_update_tag, okta_api_key):
"""
Sync trusted origins
:param neo4j_session: session with the Neo4j server
:param okta_org_id: okta organization id
:param okta_update_tag: The timestamp value to set our new Neo4j resources with
:param okta_a... | 5,343,285 |
def read_image_pillow(input_filename: Path) -> torch.Tensor:
"""
Read an image file with pillow and return a torch.Tensor.
:param input_filename: Source image file path.
:return: torch.Tensor of shape (C, H, W).
"""
pil_image = Image.open(input_filename)
torch_tensor = TF.to_tensor(pil_imag... | 5,343,286 |
def compute_solar_angle(balloon_state: balloon.BalloonState) -> float:
"""Computes the solar angle relative to the balloon's position.
Args:
balloon_state: current state of the balloon.
Returns:
Solar angle at the balloon's position.
"""
el_degree, _, _ = solar.solar_calculator(
balloon_state.... | 5,343,287 |
def print_dictionary(employee_as_dict):
"""Print a dictionary representation of the employee."""
print(json.dumps(employee_as_dict, indent=2)) | 5,343,288 |
def parse_links(source_file: str, root_url: Optional[str]=None) -> Tuple[List[Link], str]:
"""parse a list of URLs with their metadata from an
RSS feed, bookmarks export, or text file
"""
check_url_parsing_invariants()
timer = TimedProgress(TIMEOUT * 4)
with open(source_file, 'r', encoding... | 5,343,289 |
def executemany(c: CursorType, sql: str, args: Iterable[Iterable[Any]]) -> OtherResult:
"""
Call c.executemany, with the given sqlstatement and argumens, and return c.
The mysql-type-plugin for mysql will special type this function such
that the number and types of args matches the what is expected for... | 5,343,290 |
def test_get_warship_directory(config, wowsdir):
"""Test the get_warship_directory method."""
assert get_warship_directory(config) == wowsdir | 5,343,291 |
def do_add_student_bad(first_name, last_name, card_info):
"""Insert a student into the DB. VULNERABLE TO SQL INJECTION"""
# Note that we are building our own query via an f-string: this is what makes
# us vulnerable to SQL injection
query = (
"INSERT INTO students (card_info, first_name, last_n... | 5,343,292 |
def get_default_directory():
"""Return the default directory in a string
.. note:: Not tested on unix!
Returns:
(str): Default directory:
Windows: %AppData%/deharm
Unix: '~' expanded
"""
if kivy.utils.platform == 'win':
# In case this is running in Windows ... | 5,343,293 |
def validate_host():
"""Ensure that the script is being run on a supported platform."""
supported_opsys = ["darwin", "linux"]
supported_machine = ["amd64"]
opsys, machine = get_platform()
if opsys not in supported_opsys:
click.secho(
f"this application is currently not known to... | 5,343,294 |
def test_version():
"""第一个单元测试,校验是不是一个字符串格式"""
from hogwarts_apitest import __version__
assert isinstance(__version__, str)
# import requests
#
# class BaseApi(object):
#
# method = "GET"
# url = ""
# parmas = {}
# headers = {}
# data = {}
# json = {}
#
# # 共性的 set_parmas 和 ... | 5,343,295 |
def EAD_asset(x,RPs,curves,positions):
"""
Calculates the expected annual damage for one road segment (i.e. a row of the DataFrame containing the results)
based on the damage per return period and the flood protection level.
WARNING: THIS FUNCTION PROBABLY REALLY SLOWS DOWN THE OVERALL POST-PR... | 5,343,296 |
def procrustes_alignment(data, reference=None, n_iter=10, tol=1e-5,
return_reference=False, verbose=False):
"""Iterative alignment using generalized procrustes analysis.
Parameters
----------
data : list of ndarrays, shape = (n_samples, n_feat)
List of datasets to alig... | 5,343,297 |
def test_directory_origin_configuration_ignore_control_characters_xml(sdc_builder, sdc_executor,
ignore_control_characters, shell_executor,
file_writer):
"""Directory origin ... | 5,343,298 |
def get_paramsets(args, nuisance_paramset):
"""Make the paramsets for generating the Asmimov MC sample and also running
the MCMC.
"""
asimov_paramset = []
llh_paramset = []
gf_nuisance = [x for x in nuisance_paramset.from_tag(ParamTag.NUISANCE)]
llh_paramset.extend(
[x for x in nui... | 5,343,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.