content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def wrap(
module: nn.Module,
cls: Callable = FullyShardedDataParallel,
activation_checkpoint: bool = False,
**wrap_overrides: Any
) -> nn.Module:
"""
Annotate that a module should be wrapped. Annotated modules will only be
wrapped if inside of an :func:`enable_wrap` context manager. An impor... | 5,351,500 |
def _is_multiple_state(state_size):
"""Check whether the state_size contains multiple states."""
return (hasattr(state_size, '__len__') and not isinstance(state_size, tensor_shape.TensorShape)) | 5,351,501 |
def deque_to_yaml(representer, node):
"""Convert collections.deque to YAML"""
return representer.represent_sequence("!collections.deque", (list(node), node.maxlen)) | 5,351,502 |
def parse_webpage(url, page_no):
"""
Parses the given webpage using 'BeautifulSoup' and returns html content of
that webpage.
"""
page = urllib2.urlopen(url + page_no)
parsed_page = BeautifulSoup(page, 'html.parser')
return parsed_page | 5,351,503 |
def randomDigits(length=8):
"""
生成随机数字串
randomDigits() ==> 73048139
"""
return ''.join([random.choice(digits) for _ in range(length)]) | 5,351,504 |
def adaptor_set_all(handle, adaptors=None, server_id=1, **kwargs):
"""
Example:
adaptor_set_all(handle,
adaptors=[
{id: 1,
lldp: "enabled",
fip_mode: "enabled",
port_ch... | 5,351,505 |
def some_func(string: str, function: Callable) -> bool:
"""Check if some elements in a string match the function (functional).
Args:
string: <str> string to verify.
function: <callable> function to call.
Returns:
True if some of elements are in the sequence are True.
Examples:... | 5,351,506 |
def UseExceptions(*args):
"""UseExceptions()"""
return _ogr.UseExceptions(*args) | 5,351,507 |
def get_mlm_logits(input_tensor, albert_config, mlm_positions, output_weights):
"""From run_pretraining.py."""
input_tensor = gather_indexes(input_tensor, mlm_positions)
with tf.variable_scope("cls/predictions"):
# We apply one more non-linear transformation before the output layer.
# This matrix is not u... | 5,351,508 |
def test_mesh2d_delete_hanging_edges():
"""Tests `mesh2d_delete_hanging_edges` by deleting 2 hanging edges in a simple Mesh2d
4*
|
3---2---5*
| |
0---1
"""
mk = MeshKernel()
node_x = np.array([0.0, 1.0, 1.0, 0.0, 0.0, 2.0], dtype=np.double)
node_y = np.array([0.0, 0.0, 1.0, 1... | 5,351,509 |
def spm_hrf(TR, t1=6, t2=16, d1=1, d2=1, ratio=6, onset=0, kernel=32):
"""Python implementation of spm_hrf.m from the SPM software.
Parameters
----------
TR : float
Repetition time at which to generate the HRF (in seconds).
t1 : float (default=6)
Delay of response relative to onset ... | 5,351,510 |
def prob_active_neuron(activity_matrix):
"""Get expected co-occurrence under independence assumption.
Parameters
----------
activity_matrix : np.array
num_neurons by num_bins, boolean (1 or 0)
Returns
-------
prob_active : np.array
Fraction of bins each cell participates in... | 5,351,511 |
def translate_x(image: tf.Tensor, pixels: int, replace: int) -> tf.Tensor:
"""Equivalent of PIL Translate in X dimension."""
image = translate(wrap(image), [-pixels, 0])
return unwrap(image, replace) | 5,351,512 |
def reduce_time_space_seasonal_regional( mv, season=seasonsyr, region=None, vid=None,
exclude_axes=[] ):
"""Reduces the variable mv in all time and space dimensions. Any other dimensions will remain.
The averages will be restricted to the the specified season and region... | 5,351,513 |
def get_args():
"""
Function to retrieve and parse the command line arguments,
then to return these arguments as an ArgumentParser object.
Parameters:
None.
Returns:
parser.parse_args(): inputed or default argument objects.
"""
parser = argparse.ArgumentParser()
p... | 5,351,514 |
def apply_modifications(model, custom_objects=None):
"""Applies modifications to the model layers to create a new Graph. For example, simply changing
`model.layers[idx].activation = new activation` does not change the graph. The entire graph needs to be updated
with modified inbound and outbound tensors bec... | 5,351,515 |
def bioinfo():
"""Main entry point of load commands"""
pass | 5,351,516 |
def make_ccd_temperature_timeseries_pickle(sectornum):
"""
convert the engineering data on MAST to a pickled time-series of on-chip
CCD temperature.
outputs:
'/nfs/phtess1/ar1/TESS/FFI/ENGINEERING/sector0001_ccd_temperature_timeseries.pickle'
which contains a dictionary, with keys 'S_C... | 5,351,517 |
def stuur_nieuwe_taak_email(email, aantal_open):
""" Stuur een e-mail ter herinnering dat er een taak te wachten staat.
"""
text_body = ("Hallo %s!\n\n" % email.account.get_first_name()
+ "Er is zojuist een nieuwe taak voor jou aangemaakt op %s\n" % settings.SITE_URL
+ "Op... | 5,351,518 |
def search_variations(image, old_image):
"""
Search, but now for the variation of each tile.
"""
if is_complete(image):
yield image
return
constrains = calc_constrains(image)
position = max(constrains, key=constrains.get)
tile = tiles[old_image[position]]
possible_variati... | 5,351,519 |
def fuel_requirement(mass: int) -> int:
"""Fuel is mass divide by three, round down and subtract 2"""
return math.floor(mass / 3) - 2 | 5,351,520 |
def test_basic_ops(cinq_test_service):
"""
Test will pass if:
1. Auditor can detect non-compliant EC2 instances
2. Auditor respect grace period settings
"""
# Prep
cinq_test_service.start_mocking_services('ec2')
setup_info = setup_test_aws(cinq_test_service)
recipient = setup_info[... | 5,351,521 |
def data_head(fname):
"""
Get the columns-names of the csv
Parameters
----------
fname: str
Filename of the csv-data
Returns
----------
str-list:
header-names of the csv-data
"""
return pd.read_csv(fname, encoding='ISO-8859-1').columns | 5,351,522 |
def print_count(description, count, total_count, indent=''):
"""
Prints the results for a single count, including its percent.
Arguments:
description (string): A description of the count.
count (int): The count to be printed.
total_count (int): Total count used to calculate percenta... | 5,351,523 |
def test_linked_list_push_adds_new_item():
"""Linded List push method should add a new item to the list."""
from linked_list import LinkedList
l = LinkedList()
l.push('val')
assert l.head.value == 'val' | 5,351,524 |
def format(serverDict, sortKeyword='id'):
"""
Returns an array of nicely formatted servers, sorted by whatever the user prefers, or id by default.
"""
sortDict = {'id': lambda server: int(server.name[4:-3]),
'uptime': lambda server: server.uptime}
sortFunction = sortDict[sort... | 5,351,525 |
def moray_script():
"""
JavaScript関数を公開するためのjsモジュールを生成
Returns:
JavaScript関数を公開するためのjsモジュール
"""
return bottle.static_file('moray.js', root=_root_static_module) | 5,351,526 |
def load_compdat(wells, buffer, meta, **kwargs):
"""Load COMPDAT table."""
_ = kwargs
dates = meta['DATES']
columns = ['DATE', 'WELL', 'I', 'J', 'K1', 'K2', 'MODE', 'Sat',
'CF', 'DIAM', 'KH', 'SKIN', 'ND', 'DIR', 'Ro']
df = pd.DataFrame(columns=columns)
for line in buffer:
... | 5,351,527 |
def scale_random(a: float, b: float, loc: Optional[float] = None, scale: Optional[float] = None) -> float:
"""Returns a value from a standard normal truncated to [a, b] with mean loc and standard deviation scale."""
return _default.scale_random(a, b, loc=loc, scale=scale) | 5,351,528 |
def created_link(dotfile: ResolvedDotfile) -> str:
"""An output line for a newly-created link.
"""
return (
co.BOLD
+ co.BRGREEN
+ OK
+ " "
+ ln(dotfile.installed.disp, dotfile.link_dest)
+ co.RESET
) | 5,351,529 |
def instruction2_task(scr):
""" Description of task 1 """
scr.draw_text(text = "Great Work!! "+
"\n\nNow comes your TASK 3: **Consider an image**."+
"\n\nIf you press the spacebar now, an image will "+
"appear at the bottom of the screen. You can use the information from the"+
" image to make an... | 5,351,530 |
def tail(f, lines=10, _buffer=4098):
"""Tail a file and get X lines from the end"""
# place holder for the lines found
lines_found = []
# block counter will be multiplied by buffer
# to get the block size from the end
block_counter = -1
# loop until we find X lines
while len(lines_foun... | 5,351,531 |
def loggedin_and_owner_required(func):
"""
Decorator that applies to functions expecting the "owner" name as
a second argument.
It will check that the visitor is also considered as the owner of
the resource it is accessing.
Note: automatically calls login_required and check_and_set_owner decorators.
"""... | 5,351,532 |
def recursive_subs(e: sp.Basic,
replacements: list[tuple[sp.Symbol, sp.Basic]]) -> sp.Basic:
"""
Substitute the expressions in ``replacements`` recursively.
This might not be necessary in all cases, Sympy's builtin
``subs()`` method should also do this recursively.
.. note::
... | 5,351,533 |
def plot_pp_lab4():
"""
0.000909536
0.000863872
0.000859136
0.000866720
0.000920096
"""
times = {
"Block = 512, 450 000 эл.": [0.001181888],
"Block = 256, 450 000 эл.": [0.001197120],
"Block = 512, 900 000 эл.": [0.002302080],
"Block = 256, 900 000 эл.": ... | 5,351,534 |
def visualize_dataset_nd(X, ys, grid_shape=(2,2), alpha=0.5, xlim=None, ylim=None,
loc='upper left', bbox_to_anchor=(1.04,1), figsize=(16, 8),
unique_ys=None, save_path=None, label_text_lookup=None):
"""
Args:
X: 2d np.array
ys: 1d n.array
"""
i... | 5,351,535 |
def wait(
ctx: click.core.Context,
cluster_id: str,
superuser_username: str,
superuser_password: str,
transport: Transport,
skip_http_checks: bool,
enable_spinner: bool,
) -> None:
"""
Wait for DC/OS to start.
"""
check_cluster_id_exists(
new_cluster_id=cluster_id,
... | 5,351,536 |
def create_lag_i(df,time_col,colnames,lag):
""" the table should be index by i,year
"""
# prepare names
if lag>0:
s = "_l" + str(lag)
else:
s = "_f" + str(-lag)
values = [n + s for n in colnames]
rename = dict(zip(colnames, values))
# create lags
dlag = df.reset_ind... | 5,351,537 |
def crop_image(image_array, point, size):
"""
Cropping the image into the assigned size
image_array: numpy array of image
size: desirable cropped size
return -> cropped image array
"""
img_height, img_width = point # assigned location in crop
# for color image
if len(image_array.s... | 5,351,538 |
def deg_to_rad(deg):
"""Convert degrees to radians."""
return deg * pi / 180.0 | 5,351,539 |
def find_plane_normal(points):
"""
d - number of dimensions
n - number of points
:param points: `d x n` array of points
:return: normal vector of the best-fit plane through the points
"""
mean = np.mean(points, axis=1)
zero_centre = (points.T - mean.T).T
U, s, VT = np.linalg.svd(zer... | 5,351,540 |
def binary_search(data, target, low, high):
"""Return True if target is found in indicated portion of a Python list.
The search only considers the portion from data[low] to data[high] inclusive.
"""
if low > high:
return False # interval is empty; no match
else:
... | 5,351,541 |
def ReadUnifiedTreeandHaloCatalog(fname, desiredfields=[], icombinedfile=1,iverbose=1):
"""
Read Unified Tree and halo catalog from HDF file with base filename fname.
Parameters
----------
Returns
-------
"""
if (icombinedfile):
hdffile=h5py.File(fname,'r')
#load data ... | 5,351,542 |
def save_as_txt(file_path:str, obj:Union[str, list[str]]) -> None:
"""Save an object in a txt-file
if obj
(str) -> line[0] = obj
(list) -> line[i] = obj[i] (item_i)
Args:
file_path (str): saving path
obj (Any): object to save
"""
file_path= glob_utils.file... | 5,351,543 |
def lines_in_pull(pull):
"""Return a line count for the pull request.
To consider both added and deleted, we add them together, but discount the
deleted count, on the theory that adding a line is harder than deleting a
line (*waves hands very broadly*).
"""
ignore = r"(/vendor/)|(conf/locale)|... | 5,351,544 |
def plot_panels(volume, panels, figsize=(16, 9), save_name=None):
"""Plot on the same figure a number of views, as defined by a list of panel
Parameters
----------
volume : cortex.Volume
The data to plot.
panels : list of dict
List of parameters for each panel. An example of panel ... | 5,351,545 |
def get_active_milestones(session, project):
"""Returns the list of all the active milestones for a given project."""
query = (
session.query(model.Issue.milestone)
.filter(model.Issue.project_id == project.id)
.filter(model.Issue.status == "Open")
.filter(model.Issue.milestone.... | 5,351,546 |
def set_camera_parameters(cfg):
"""
Set camera parameters.
All values come from the dict generated from the JSON file.
:param cfg: JSON instance.
:type cam: dict
:return: None
:rtype: None
"""
# set camera resolution [width x height]
camera = PiCamera()
camera.resolutio... | 5,351,547 |
def get_srl_result_for_instance(srl_dict, instance):
"""Get SRL output for an instance."""
sent_id = instance.sent_id
tokens_gold = instance.tokens
srl_output = srl_dict[sent_id]
srl_output["words"] = [word for word in srl_output["words"] if word != "\\"]
tokens_srl = srl_output['words']
if tokens_srl != tokens... | 5,351,548 |
def ensure_tty(file=sys.stdout):
""" Ensure a file object is a tty. It must have an `isatty` method that
returns True.
TypeError is raised if the method doesn't exist, or returns False.
"""
isatty = getattr(file, 'isatty', None)
if isatty is None:
raise TypeError(
'Ca... | 5,351,549 |
def chop_cells(text: str, max_size: int, position: int = 0) -> List[str]:
"""Break text in to equal (cell) length strings."""
_get_character_cell_size = get_character_cell_size
characters = [
(character, _get_character_cell_size(character)) for character in text
][::-1]
total_size = position... | 5,351,550 |
def read_input_field_lonlat(
input_file,
fld_name,
level,
conf_in,
*,
conv_fact=None,
crop=0,
):
"""Read from file and pre-process a field.
Returns the field as a Field2D object.
Arguments:
- input_file: Input netCDF file.
- fld_name: Name of the input field used in t... | 5,351,551 |
def multiply_scenarios(sep, *args):
"""
Create the cross product of two lists of scenarios
"""
result = None
for scenes in args:
if result == None:
result = scenes
else:
total = []
for scena in result:
for scenb in scenes:
... | 5,351,552 |
def export_output():
"""
Returns a function that will return the contents of the first file in a zip file which is
not named '_metadata.csv'
"""
def fn(export: FlexibleDataExport):
out = BytesIO()
export.file_format = FileFormat.ZIP_CSV
export.write_data(out)
with Zi... | 5,351,553 |
def _fill_in_database():
"""Fill in 'foodlik' of datas."""
datas_path = Path().resolve() / "core" / "back" / "requests"
datas_path = datas_path / "datas"
_fill_in_categories(datas_path)
_fill_in_products(datas_path)
_fill_in_products_number(datas_path) | 5,351,554 |
def compute_total_probability_vector(mix_coeff_matrix, kernel_probability_matrix):
"""
Computes the total, weighted probability vector using the mixture coefficient matrix and the kernel probability matrix.
"""
# Start writing code here. The computation for the total probability vector can be
# writ... | 5,351,555 |
def test_extract_seq_with_skip_before_and_after_ctg_clv():
"""
AA
GT┘ <-bridge read
G--AGT-GC <-bridge contig
0 123 456 <-contig coord
ctg_clv^ ^ice
...GACAGTTGC... <-genome
5678901234 <-genome coord
1 |
ref_clv^ ^ire
... | 5,351,556 |
def mnist_noniid(dataset, num_users):
"""
Sample non-I.I.D client data from MNIST dataset
:param dataset:
:param num_users:
:return:
"""
num_shards, num_imgs = 200, 300
idx_shard = [i for i in range(num_shards)]
dict_users = {i: np.array([], dtype='int64') for i in range(num_users)}
... | 5,351,557 |
def test_tls_fingerprint_cascade(mgr, temp_chains, cleanup):
"""Verify that when the first cert-to-name entry doesn't match, the
next one is tried"""
do_cert_test(
mgr,
temp_chains,
client_ca_certs=[SERVER_INTR, SERVER_CA, CLIENT_INTR, CLIENT_CA],
server_trusted_client_cer... | 5,351,558 |
def first_order_model(nt, rates):
"""
Returns the first-order model asymptotic solution for a network nt.
Takes a list of interaction weigths (in the same order as the list of nodes) as the "rates" argument
"""
if type(nt) == list:
nt = az.transform(nt)
M = network_matrix(nt, rates=r... | 5,351,559 |
def save_to_disk(url, save_path):
"""
Saves to disk non-destructively (xb option will not overwrite)
"""
print('Downloading: %s' % url)
r = requests.get(url)
if r.status_code == 404:
print('URL broken, unable to download: %s' % url)
return False
else:
with open(save_p... | 5,351,560 |
def test_decision_tree():
"""
This is a test for decision tree on college dataset
The test simply checks for whether a ML model has been fit successfully
This test will be helpful when we switch to API for dataset
and dynamically select features
"""
model = fkm.fit_decision_tree(True)... | 5,351,561 |
def arguments():
"""Parse arguments.
Returns
-------
argparse.Namespace
Returns Argparse Namespace.
"""
parser = argparse.ArgumentParser(prog='pyslackdesc',
description="pyslackdesc - simple, \
interactive script... | 5,351,562 |
def render_settings_window(s_called, s_int, ntfc_called, ntfc_state, s_state):
"""
Render the settings window
"""
win = Settings(s_called, s_int, ntfc_called, ntfc_state, s_state)
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()
return win.settings_called, win.interva... | 5,351,563 |
def run():
"""
Initialize and runs the app (blocks until the GUI is destroyed)
:return:
"""
dump_configuration()
state = AppState()
controller = AppController(state)
AppController.copy_to_clipboard('hello')
render_main_view(controller=controller) | 5,351,564 |
def server(server_id):
"""
Returns a list of sourcemod servers
"""
data = {}
db_server = ServerModel.select().join(IPModel)
db_server = db_server.where(ServerModel.id == server_id).get()
server_address = (db_server.ip.address, db_server.port)
info = {}
try:
querier = Ser... | 5,351,565 |
def atom_hsoc(case, soc):
"""
Return atomic spin-orbit coupling matrix :math:`\\vec{l}\cdot\\vec{s}` in complex spherical harmonics basis.
Parameters
----------
case : str
String label indicating atomic shell,
- 'p': for :math:`p` -shell.
- 't2g': for :math:`t_{2g}` -... | 5,351,566 |
def wcs_to_celestial_frame(wcs):
"""
For a given WCS, return the coordinate frame that matches the celestial
component of the WCS.
Parameters
----------
wcs : :class:`~astropy.wcs.WCS` instance
The WCS to find the frame for
Returns
-------
frame : :class:`~astropy.coordinat... | 5,351,567 |
def conv2d(x, f=64, k=3, d=1, act=None, pad='SAME', name='conv2d'):
"""
:param x: input
:param f: filters, default 64
:param k: kernel size, default 3
:param d: strides, default 2
:param act: activation function, default None
:param pad: padding (valid or same), default same
:param name:... | 5,351,568 |
def combine_subdomain(filenames, outfilename):
"""Recombine per-processor subdomain files into one single file.
Note: filenames must be an array of files organized to reflect the
subdomain decomposition. filenames[0,0] is bottom left, filenames[0,-1] is
bottom right, filenames[-1,0] is top left, filena... | 5,351,569 |
def _is_uniform_distributed_cf(cf):
""" Check if the provided center frequencies are uniformly distributed.
"""
return np.any(np.diff(np.diff(cf))!=0) | 5,351,570 |
def do_execfile(user_input):
"""only exists in PY2"""
try:
execfile(user_input) # noqa: F821
except Exception:
pass | 5,351,571 |
def description_serializer(description, object_, path, linker):
"""
Serializes the given description.
This function is a generator.
Parameters
----------
description : ``GravedDescription``
The table to serialize
object_ : ``UnitBase``
The respective unit.
path ... | 5,351,572 |
def build_person(first_name, last_name):
"""Return a dictionary of information about a person."""
person = {'first': first_name, 'last': last_name}
return person | 5,351,573 |
def test_temp_bad_units():
"""Simple check of bad units in temperature"""
with pytest.raises(datatypes.UnitsError):
datatypes.temperature(-99, "Q") | 5,351,574 |
def radon(image, theta=None):
"""
Calculates the radon transform of an image given specified
projection angles.
Parameters
----------
image : array_like, dtype=float
Input image.
theta : array_like, dtype=float, optional (default np.arange(180))
Projection angles (in degrees... | 5,351,575 |
def build_idrac_table_schemas(metric_definitions: list):
"""build_table_schemas Build iDRAC Table Schemas
Build table schemas based on the idrac telemetry metric definitions
Args:
metric_definitions (list): idrac telemetry metric definitions
Returns:
dict: iDRAC table schemas
... | 5,351,576 |
def _increasing_randomly_negate_to_arg(
level: int, params: Tuple[float, float]
) -> Tuple[float]:
"""
Convert level to transform magnitude. This assumes transform magnitude increases
(or decreases with 50% chance) linearly with level.
Args:
level (int): Level value.
params (Tuple[f... | 5,351,577 |
def test_column_duplicated(df1):
"""Raise ValueError if column is duplicated in `columns`"""
with pytest.raises(ValueError):
df1.complete(
columns=[
"Year",
"Taxon",
{"Year": lambda x: range(x.min().x.max() + 1)},
]
) | 5,351,578 |
def hashify(params, max_length=8):
"""
Create a short hashed string of the given parameters.
:param params:
A dictionary of key, value pairs for parameters.
:param max_length: [optional]
The maximum length of the hashed string.
"""
param_str = json.dumps(params, separators=... | 5,351,579 |
def main():
"""Complete the crudedata collection with missing dates."""
for cow in mongo.cows():
print("Completing cow {}...".format(cow))
dates = mongo.dates(cow)
missing = get_missing_dates(dates)
if missing:
for lact in reversed(mongo.lacts(cow)):
... | 5,351,580 |
def version(package, encoding='utf-8'):
"""Obtain the packge version from a python file e.g. pkg/__init__.py
See <https://packaging.python.org/en/latest/single_source_version.html>.
"""
path = os.path.join(os.path.dirname(__file__), package, '__init__.py')
with io.open(path, encoding=encoding) as f... | 5,351,581 |
def unique_entries(results):
"""Prune non-unqiue search results."""
seen = set()
clean_results = []
for i in results:
if i['code'] not in seen:
clean_results.append(i)
seen.add(i['code'])
return clean_results | 5,351,582 |
def get_q_confidence() -> int:
"""Get's the user's confidence for the card"""
response = input("How confident do you feel about being able to answer this question (from 1-10)? ")
if response.isnumeric() & 0 < response <= 10:
return int(response)
else:
print("Incorrect score value, please... | 5,351,583 |
def generate_offices_table(offices, by_office, by_polling_center,
election_day, day_after_election_day):
""" Pre-compute key data needed for generating election day
office reports.
"""
offices_by_key = {str(office['code']): office for office in offices}
rows = []
for... | 5,351,584 |
def bang(nick, chan, message, db, conn, notice):
"""when there is a duck on the loose use this command to shoot it."""
global game_status, scripters
if chan in opt_out:
return
network = conn.name
score = ""
out = ""
miss = ["You just shot yourself in the foot, the duck laughed at you... | 5,351,585 |
def is_nan(param: float, param_name: str = None, message=None):
"""
Guards the specified :param param from not being a nan (not a number) by throwing an exception of type
ArgumentException with a specific :param message when the precondition has not been met
:param param: The param to be checked
:pa... | 5,351,586 |
def print_summary(model, line_length=None, positions=None, print_fn=None, expand_depth=0):
"""Prints a summary of a model.
Args:
model: Keras model instance.
line_length: Total length of printed lines
(e.g. set this to adapt the display to different
terminal window sizes)... | 5,351,587 |
async def test_avg_processing_time(aresponses):
"""Test requesting AdGuard Home DNS avarage processing time stats."""
aresponses.add(
"example.com:3000",
"/control/stats",
"GET",
aresponses.Response(
status=200,
headers={"Content-Type": "application/json"}... | 5,351,588 |
def pfunc_role_coverage(args):
"""Another intermediate function for parallelization; as for
pfunc_doctor_banding."""
rota = args[0]
role = args[1]
return rota.get_role_coverage(role) | 5,351,589 |
def parse(s: str) -> Tree:
"""
Parse PENMAN-notation string *s* into its tree structure.
Args:
s: a string containing a single PENMAN-serialized graph
Returns:
The tree structure described by *s*.
Example:
>>> import penman
>>> penman.parse('(b / bark-01 :ARG0 (d / d... | 5,351,590 |
def subtract(v: Vector, w: Vector) -> Vector:
"""Subtracts corresponding elements"""
assert len(v) == len(w), "vectors must be the same length"
return [v_i - w_i for v_i, w_i in zip(v, w)] | 5,351,591 |
def get_QUTFish(image_path, train_ratio=0.8):
"""
get train and test dataset of QUTFish:
https://wiki.qut.edu.au/display/cyphy/Fish+Dataset
step1: download the dataset
step2: set the root to QUT_fish_data/
:param image_path: the QUT_fish_data/
:param the percentage used for training
:re... | 5,351,592 |
def test_unknown_tag_code(event, glsc):
"""if unknown tag code is somehow selected, a meaningful error
message should be returned.
"""
choices = get_event_model_form_choices(event)
# make sure cwt is a valid fin clip choice:
event_dict = create_event_dict(event)
event_dict["fish_tags"] = ... | 5,351,593 |
def getWordScore(word, n):
"""
Returns the score for a word. Assumes the word is a valid word.
The score for a word is the sum of the points for letters in the
word, multiplied by the length of the word, PLUS 50 points if all n
letters are used on the first turn.
Letters are scored as in Scrab... | 5,351,594 |
def test_02():
"""Test"""
args = '--seed 1 --kmer_size 4 --num_words 5 --max_word 8'
out = getoutput('{} {} {}'.format(prg, args, dickinson))
expected = """
1: miled
2: iliar
3: noticin
4: venture
5: nelled
""".strip()
assert out.strip() == expected | 5,351,595 |
def resolve_label(token, symbols, memory):
"""Given a label, resolve it in to an address and save to symbol table."""
symbols.add(token, memory.get_address()) | 5,351,596 |
def AutomateMe(data, sslSocket):
"""
This is where you automate me.
:param data: data that came in [str]
:param sslSocket: Client SSL Socket Object [ssl wrapper socket object]
:return: None
"""
# Caught it!
# Put your automation here. Notice if you have a lot of computation you might
... | 5,351,597 |
def get_commit():
""" Try to return the intended commit / release to deal with. Otherwise
raise an acceptable error.
1) it was specified on the command line
2) use the current branch in the target repo
"""
commit = getattr(env, 'commit', None) or rev_parse('HEAD')
if commit is N... | 5,351,598 |
def main():
""" The main function of our asteroids game. """
# Optional: Ask for difficulty in terminal
try:
diff = int(input("Choose your difficulty! 1: easy, 2: medium, 3: hard. " ))
if type(diff) != int:
raise ValueError
except ValueError:
diff = 1
pri... | 5,351,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.