content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def versioning(version: str) -> str:
"""
version to specification
Author: Huan <zixia@zixia.net> (https://github.com/huan)
X.Y.Z -> X.Y.devZ
"""
sem_ver = semver.parse(version)
major = sem_ver['major']
minor = sem_ver['minor']
patch = str(sem_ver['patch'])
if minor % 2:
... | 17,100 |
def freshdesk_sync_contacts(contacts=None, companies=None, agents=None):
"""Iterate through all DepartmentUser objects, and ensure that each user's
information is synced correctly to a Freshdesk contact.
May optionally be passed in dicts of contacts & companies.
"""
try:
if not contacts:
... | 17,101 |
def device_create_from_symmetric_key(transportType, deviceId, hostname, symmetricKey): # noqa: E501
"""Create a device client from a symmetric key
# noqa: E501
:param transportType: Transport to use
:type transportType: str
:param deviceId:
:type deviceId: str
:param hostname: name of t... | 17,102 |
def create_with_index(data, columns):
"""
Create a new indexed pd.DataFrame
"""
to_df = {columns[0]: [x for x in range(1, len(data) + 1)], columns[1]: data}
data_frame = pd.DataFrame(to_df)
data_frame.set_index("Index", inplace=True)
return data_frame | 17,103 |
def pyfancy_critical(pyfancy_variable):
"""Critical level."""
pyfancy_function(
logger_function().critical,
pyfancy().red_bg().bold(),
pyfancy_variable) | 17,104 |
def random_aes_key(blocksize=16):
"""Set 2 - Challenge 11"""
return afb(np.random.bytes(blocksize)) | 17,105 |
def check_decoded_times(start_time, timewindow=30):
"""Check the decoded IRIG-B times within a window of size timewindow
surrounding the event time and make sure the times are all correct (i.e.
they are either the correct UTC or GPS time; either one is considered
correct). Save the results of the check ... | 17,106 |
def show_ner(text: str, ner_model: str):
"""
Just a shortcut to annotate the text with the given NER model
"""
nlp = stanza.Pipeline(lang='en', package='craft',
dir=STANZA_DOWNLOAD_DIR,
processors={'ner': ner_model})
doc = nlp(text)
print(f'\n... | 17,107 |
def create_and_load(directory: str,
name: str,
new_name: str = None) -> nn.Module:
"""Instantiate an unkown function (uf) required
by the high-order functions with a trained neural network
Args:
directory: directory to the saved weights of an NN
name... | 17,108 |
def select_region_climatedata(gcm_name, rcp, main_glac_rgi):
"""
Get the regional temperature and precipitation for a given dataset.
Extracts all nearest neighbor temperature and precipitation data for a given set of glaciers. The mean temperature
and precipitation of the group of glaciers is... | 17,109 |
def get_patch_boundaries(mask_slice, eps=2):
"""
Computes coordinates of SINGLE patch on the slice. Behaves incorrectly in the case of multiple tumors on the slice.
:mask_slice: 2D ndarray, contains mask with <0, 1, 2> values of pixels
:eps: int, number of additional pixels we extract ar... | 17,110 |
def get_sqrt_ggn_extension(
subsampling: Union[None, List[int]], mc_samples: int
) -> Union[SqrtGGNExact, SqrtGGNMC]:
"""Instantiate ``SqrtGGN{Exact, MC} extension.
Args:
subsampling: Indices of active samples.
mc_samples: Number of MC-samples to approximate the loss Hessian. ``0``
... | 17,111 |
def gray_to_rgb(image):
"""convert cv2 image from GRAYSCALE to RGB
:param image: the image to be converted
:type image: cv2 image
:return: converted image
:rtype: cv2 image
"""
return cv2.cvtColor(image, cv2.COLOR_GRAY2RGB) | 17,112 |
def test_eq(character: Character, other: Any, expected_equality: bool) -> None:
"""Test illud.character.Character.__eq__."""
equality: bool = character == other
assert equality == expected_equality | 17,113 |
def run_evaluation(model, dataset_name, dataset,
mesh, batch_size=32, img_res=224,
num_workers=32, shuffle=False, log_freq=50):
"""Run evaluation on the datasets and metrics we report in the paper. """
renderer = PartRenderer()
# Create SMPL model
smpl =... | 17,114 |
def win_to_cygwin(winpath):
"""run `cygpath winpath` to get cygwin path"""
x = detail.command.run(['cygpath', winpath])
assert(len(x) == 1)
return x[0] | 17,115 |
def test_register_options():
"""Verify we call add_options on the plugin only if it exists."""
# Set up our mocks and Plugin object
entry_point = mock.Mock(spec=['load'])
plugin_obj = mock.Mock(spec_set=['name', 'version', 'add_options',
'parse_options'])
option_... | 17,116 |
def extract_array_from_gpu( part_idx_start, array, selected ):
"""
Extract a selection of particles from the GPU and
store them in a 1D array (N_part,)
Selection goes from starting index (part_idx_start)
to (part_idx_start + N_part-1), where N_part is derived
from the shape of the array `selecte... | 17,117 |
def main(argv=None):
"""
*Optional but needed it you want to run the model from the command line*
Perform command line execution of the model. This example uses the getopt
module to parse the command line options.
The user can set the caseName, the runDir, the timestep and the configfile.
... | 17,118 |
def nucleotide_composition_to_letter(composition):
"""
Converts dictionary of {nucleotide letter: proportion} pairs
to IUPAC degenerate DNA letter.
Usage:
c = {'A': 1}
print(nucleotide_composition_to_letter(c)) --> 'A'
c = dict(zip('ACGT', [1, 1, 1, 1]))
print(nucleotide_composition_to... | 17,119 |
def forcast(doc):
"""
:param: doc object
:returns: tuple with grade level, age level
"""
word_tokens = doc.word_tokens
monosyllables = 0
for i in word_tokens:
if i.isalpha() == False and len(i) < 2:
word_tokens.remove(i)
for i in word_tokens[10:159]:
if sylla... | 17,120 |
def organization_following_request_get(
organization_id: UUID = typer.Argument(..., help="UUID of the organization"),
following_id: UUID = typer.Argument(..., help="UUID of the following request")
):
"""
Returns a request received by an organization to follow another.
"""
client = Client(pro... | 17,121 |
def convert_coordinates_to_country(deg_x: float, deg_y: float) -> str:
""" returns country name """
return geocoder.osm([deg_x, deg_y], method="reverse").country | 17,122 |
def fixture_items(test_list):
"""Returns an instance of ItemCollection for testing"""
return test_list.get_items(query=QUERY) | 17,123 |
def match_files(base_dir, pattern):
"""
Return the files matching the given pattern.
:param base_dir: directory to search in
:param pattern: file pattern to use
:returns generator: the generator which iterates the matching file names
"""
for path, _, files in os.walk(base_dir):
for ... | 17,124 |
def numbers_lists_entry_widget(
list_param: list,
name: str,
expect_amount: int = -1,
expect_int: bool = False,
help=None,
) -> list:
"""
create a list text input field and checks if expected amount and type matches if set.
:param list_param: a list variable handled by this wiget
:pa... | 17,125 |
def annotate_image(image: Image.Image, room_classification: dict) -> None:
"""Annotate a given image. This is done in-place. Nothing is returned.
Args
----
image: Pillow image
room_classification:
"""
logging.debug(f"annotating image ...")
draw = ImageDraw.Draw(image)
font = ImageF... | 17,126 |
def get_daily_discussion_post(subreddit_instance: praw.models.Subreddit):
"""Try to get the daily discussions post for a subreddit.
Args:
subreddit_instance
Returns:
The submission object for the discussion post, or None if it couldn't be found.
Works by searching the stickied posts of ... | 17,127 |
def menu_rekening_opzeggen(): # IO ()
"""
Menu-item twee. Vraagt de nodige invoer om rekening_verwijderen() aan te kunnen roepen.
:return: ()
"""
rekeningnr = input_rekeningnr("Welk rekeningnummer wil je opzeggen? ")
rekening_verwijderen(rekeningnr) | 17,128 |
def metric_by_training_size(X, y, classifier_list, training_set, metric, as_percentage=True):
"""
This is a refactoriation of code to repeat metrics for best fitted models by training set percentage size.
i.e.: Find accuracy rating for multiple training-test splits for svm, random forests, and naive bayes a... | 17,129 |
def apply_back_defence(
board: Board, opponent: Optional[Player] = None
) -> Optional[Action]:
"""
Move to intercept.
"""
player = board.controlled_player
ball = board.ball
if not opponent:
opponent = ball.player
if opponent.vector.x < 0:
# trying to predict opponent's... | 17,130 |
def your_sanity_checks():
"""
Use this space add any additional sanity checks by running:
python q2_neural.py
This function will not be called by the autograder, nor will
your additional tests be graded.
"""
print "Running your sanity checks..." | 17,131 |
def remove_namespace(tag, ns):
"""Remove namespace from xml tag."""
for n in ns.values():
tag = tag.replace('{' + n + '}', '')
return tag | 17,132 |
def test_close_trustline_last_edge_insufficient_capacity(
complex_community_with_trustlines_and_fees,
):
"""A owes money to B and A wants to reduce that amount with the help of C"""
complex_community_with_trustlines_and_fees.update_balance(
A, B, 50000
) # amount B owes A
complex_community_... | 17,133 |
def false_prediction_pairs(y_pred, y_true):
"""
Prints pairs of predicted and true classes that differ.
Returns
-------
false_pairs
The pairs of classes that differ.
counts
Number of occurences of the pairs.
"""
cond = y_pred != y_true
false_preds = np.stack([y_true[... | 17,134 |
def draw_boxes_and_labels_to_image_multi_classes(image, classes, coords, scores=None, classes_name=None, classes_colors=None, font_color=[0, 0, 255]):
"""
Draw bboxes and class labels on image. Return or save the image with bboxes
Parameters
-----------
image : numpy.array
The RGB image [hei... | 17,135 |
def route_open_file_dialog(fqname):
"""Return html of file structure for that parameter"""
# these arguments are only set when called with the `navigate_to` function on an already open
# file dialog
current_folder = request.args.get('current_folder')
folder = request.args.get('folder')
config ... | 17,136 |
def simulate():
"""
Runs a simulation given a context, a simulator, a trace, and a depth
Method PUT
"""
context = request.get_json()['context']
simulator = request.get_json()['simulator']
trace = request.get_json()['trace']
depth = request.get_json()['depth']
if context is None or si... | 17,137 |
def soft_expected_backup_rl(
next_q: Array,
next_pol: Array,
next_log_pol: Array,
rew: Array,
done: Array,
discount: float,
er_coef: float,
) -> Array:
"""Do soft expected bellman-backup :math:`r + \gamma P \langle \pi, q - \tau * \log{\pi}\rangle`.
Args:
next_q (Array): ? x... | 17,138 |
def readcal(calfile):
"""
This reads all of the information from a master calibration index and returns
it in a dictionary where each calibration type has a structured arrays that
can be accessed by the calibration name (e.g. 'dark').
"""
if os.path.exists(calfile) == False:
raise Value... | 17,139 |
def global_attributes_dict():
# type: () -> Dict[str, str]
"""Set global attributes required by conventions.
Currently CF-1.6 and ACDD-1.3.
Returns
-------
global_atts: dict
Still needs title, summary, source, creator_institution,
product_version, references, cdm_data_type, ins... | 17,140 |
def test_write_cif_PIYZAZ():
"""
Tests writing cif formatted molecule file
File comparison tests are OS dependent, they should only work in UNIX but not Windows.
"""
piyzaz = Molecule(atoms=piyzaz_atoms, coordinates=piyzaz_coors)
test_file = os.path.join(os.path.abspath(os.path.dirname(__file__)... | 17,141 |
def add_txt(axes):
"""Add text to the plot.
Parameters
----------
axes :
"""
axes.text(0.5, 1.0, "FOURIER ", transform=axes.transAxes,
ha="right", va="bottom", color="w",
family="sans-serif", fontweight="light", fontsize=16)
axes.text(0.5, 1.0, "UNCHAINED", tra... | 17,142 |
def test_write_yml():
"""读写"""
data = {"name": "wxnacy"}
_path = f'/tmp/wpy_{random.randint(9000, 10000)}.yml'
path.write_yml(_path, data)
res = path.read_dict(_path)
assert data, res | 17,143 |
def generate_bias(series: pd.Series, effect_size: float = 1, power: float = 1) -> pd.Series:
"""
Calculate bias for sensitive attribute
Parameters
----------
series : pd.Series
sensitive attribute for which the bias is calculated.
effect_size : float, optional
Size of the bias f... | 17,144 |
def compress_coils(kspace,
num_output_coils=None,
tol=None,
coil_axis=-1,
matrix=None,
method='svd',
**kwargs):
"""Coil compression gateway.
This function estimates a coil compression matrix and uses i... | 17,145 |
def get_thellier_gui_meas_mapping(input_df, output=2):
"""
Get the appropriate mapping for translating measurements in Thellier GUI.
This requires special handling for treat_step_num/measurement/measurement_number.
Parameters
----------
input_df : pandas DataFrame
MagIC records
outp... | 17,146 |
def test_make_df_2(pg_conn):
"""Test of main Postgres binary data to Pandas dataframe pipeline.
This tests boolean data.
"""
cursor = pg_conn.cursor()
# Copy binary data to a tempfile
path = tempfile.mkstemp()[1]
query = 'COPY test2 TO STDOUT BINARY;'
with open(path, 'wb') as f:
... | 17,147 |
def new_unsigned_vaccination_credential(
passenger_first_name: str,
passenger_last_name: str,
passenger_id_number: str,
passenger_date_of_birth: str,
vaccination_disease: str,
vaccination_vaccine: str,
vaccination_product: str,
vaccination_auth_holder: str,
vaccination_dose_number: s... | 17,148 |
def calc_pk_integrated_intensities(p,x,pktype,num_pks):
"""
Calculates the area under the curve (integrated intensities) for fit peaks
Required Arguments:
p -- (m x u + v) peak parameters for number of peaks, m is the number of
parameters per peak ("gaussian" and "lorentzian" - 3, "pvoigt" - 4, "... | 17,149 |
def cant_serialize(media_type: str) -> NoReturn: # type: ignore
"""Reject the current example if we don't know how to send this data to the application."""
event_text = f"Can't serialize data to `{media_type}`."
note(f"{event_text} {SERIALIZERS_SUGGESTION_MESSAGE}")
event(event_text)
reject() | 17,150 |
def read_fid_ntraces(filename, shape=None, torder='flat', as_2d=False,
read_blockhead=False):
"""
Read a Agilent/Varian binary (fid) file possibility having multiple
traces per block.
Parameters
----------
filename : str
Filename of Agilent/Varian binary file (fid) ... | 17,151 |
async def async_get_erc20_decimals(
token: spec.ERC20Reference,
block: typing.Optional[spec.BlockNumberReference] = None,
**rpc_kwargs: typing.Any
) -> int:
"""get decimals of an erc20"""
return await erc20_generic.async_erc20_eth_call(
function_name='decimals', token=token, block=block, **r... | 17,152 |
def test_toc_all_references_should_exist_pep420_disabled(make_app, apidoc):
"""All references in toc should exist. This test doesn't say if
directories with empty __init__.py and and nothing else should be
skipped, just ensures consistency between what's referenced in the toc
and what is create... | 17,153 |
def get_game_log(game_id: int):
"""
Method used to get list of important events of macau game with given game id.
:param game_id: integer value of existing game
:return: list with string with all important events in game
"""
if game_id >= len(games_container):
return JSONResponse(content... | 17,154 |
def get_exploration_components_from_dir(dir_path):
"""Gets the (yaml, assets) from the contents of an exploration data dir.
Args:
dir_path: str. a full path to the exploration root directory.
Returns:
*. A 2-tuple, the first element of which is a yaml string, and the
second element... | 17,155 |
def iterate_pattern_mapping(pattern_mapping: Union[List[Dict[str, Any]], Dict[str, Any]]) -> Generator[Mapping, None, None]:
""" Iterate mapping entry.
:param pattern_mapping: The pattern mapping table.
:return: Each mapping entry. {pattern:, exclude:, algorithm:, output:, next:}
"""
if isinstance(... | 17,156 |
def time_this_function(func):
"""
Time the function.
use as a decorator.
Examples
---------
::
@time_this_function
def func(x):
return x
a= func(1)
Parameters
----------
func: Callable
function
Returns
-------
result
... | 17,157 |
def test_true_azimuth(coord_system, bldg_north, zone_rel_north, expected):
"""py.test for true_azimuth"""
fhandle = StringIO(idftxt)
idf = IDF(fhandle)
geom_rules = idf.idfobjects["GlobalGeometryRules"][0]
building = idf.idfobjects["Building"][0]
zone = idf.idfobjects["Zone"][0]
surface = id... | 17,158 |
def power_plot(data, sfreq, toffset, log_scale, zscale, title):
"""Plot the computed power of the iq data."""
print("power")
t_axis = np.arange(0, len(data)) / sfreq + toffset
if log_scale:
lrxpwr = 10 * np.log10(data + 1e-12)
else:
lrxpwr = data
zscale_low, zscale_high = zsca... | 17,159 |
def load_dataset(dataset):
"""
Loads a dataset and returns train, val and test partitions.
"""
dataset_to_class = {
'mnist': torchvision.datasets.MNIST,
'cifar10': torchvision.datasets.CIFAR10,
'fa-mnist': torchvision.datasets.FashionMNIST
}
assert dataset in dataset_to_class.keys()
transform = transforms.... | 17,160 |
def batch_sql_query(sql_statement, key_name, key_list, dry_run=False):
"""Run a query on the specifies list of primary keys."""
for key in key_list:
if isinstance(key, dict):
sql = "{sql_statement} where ".format(sql_statement=sql_statement)
andcount = 0
for k... | 17,161 |
def compareTo(s1, s2):
"""Compares two strings to check if they are the same length and whether one is longer
than the other"""
move_slice1 = 0
move_slice2 = 1
if s1[move_slice1:move_slice2] == '' and s2[move_slice1:move_slice2] == '':
return 0 # return 0 if same length
elif s1[move_... | 17,162 |
def score_network(network, node_to_score, output_file):
"""
Scores a network
"""
# Get all nodes
all_nodes = node_to_score.keys()
# Here, the network is scored and stored in a file
with open(output_file, 'w') as f:
for u, v in network.edges():
score_u = node_to_score[u]... | 17,163 |
def is_unique(x):
# A set cannot contain any duplicate, so we just check that the length of the list is the same as the length of the corresponding set
"""Check that the given list x has no duplicate
Returns:
boolean: tells if there are only unique values or not
Args:
x (list): elemen... | 17,164 |
def str2format(fmt, ignore_types=None):
"""Convert a string to a list of formats."""
ignore_types = ignore_types if ignore_types else ()
token_to_format = {
"s": "",
"S": "",
"d": "g",
"f": "f",
"e": "e",
}
base_fmt = "{{:{}}}"
out = []
for i, token ... | 17,165 |
def add_zones_to_elements(net, elements=["line", "trafo", "ext_grid", "switch"]):
"""
Adds zones to elements, inferring them from the zones of buses they are
connected to.
"""
for element in elements:
if element == "sgen":
net["sgen"]["zone"] = net["bus"]["zone"].loc[net["... | 17,166 |
def _read_concordance(filename: Path, Sample_IDs: pd.Index) -> pd.DataFrame:
"""Create a flag of known replicates that show low concordance.
Given a set of samples that are known to be from the same Subject. Flag
samples that show low concordance with one or more replicates.
Returns:
pd.Series... | 17,167 |
def load_image(name):
""" Get and cache an enaml Image for the given icon name.
"""
path = icon_path(name)
global _IMAGE_CACHE
if path not in _IMAGE_CACHE:
with open(path, 'rb') as f:
data = f.read()
_IMAGE_CACHE[path] = Image(data=data)
return _IMAGE_CACHE[path] | 17,168 |
def add_shipment_comment(
tracking_id: str,
body: CreateComment = Body(...),
client: VBR_Api = Depends(vbr_admin_client),
):
"""Add a Comment to a Shipment.
Requires: **VBR_WRITE_PUBLIC**"""
tracking_id = sanitize_identifier_string(tracking_id)
shipment = client.get_shipment_by_tracking_id(... | 17,169 |
def train_faster_rcnn_alternating(base_model_file_name, debug_output=False):
"""
4-Step Alternating Training scheme from the Faster R-CNN paper:
# Create initial network, only rpn, without detection network
# --> train only the rpn (and conv3_1 and up for VGG16)
# buffer region proposals from r... | 17,170 |
def _mp2_energy(output_str):
""" Reads the MP2 energy from the output file string.
Returns the energy in Hartrees.
:param output_str: string of the program's output file
:type output_str: str
:rtype: float
"""
ene = ar.energy.read(
output_str,
app.one_of_the... | 17,171 |
def fastlcs(a,b,Dmax=None):
"""
return the length of the longest common substring or 0 if the maximum number of difference Dmax cannot be respected
Implementation: see the excellent paper "An O(ND) Difference Algorithm and Its Variations" by EUGENE W. MYERS, 1986
NOTE:
let D be the minim... | 17,172 |
def FeaturesExtractor( # pylint: disable=invalid-name
eval_config: config_pb2.EvalConfig,
tensor_representations: Optional[Mapping[
Text, schema_pb2.TensorRepresentation]] = None) -> extractor.Extractor:
"""Creates an extractor for extracting features.
The extractor acts as follows depending on th... | 17,173 |
def clean_reorgs(horizon=settings.MEX_SYNC_HORIZON):
"""
Clean chain reorganizations up to `horizon` number of blocks in the past.
First we compare the latest `horizon` block hashes from the database with
those form the authoritative node. If we find a difference we will delete
all the blocks start... | 17,174 |
def assert__(engine, obj, condition, message=u'Assertion failed'):
""":yaql:assert
Evaluates condition against object. If it evaluates to true returns the
object, otherwise throws an exception with provided message.
:signature: obj.assert(condition, message => "Assertion failed")
:arg obj: object ... | 17,175 |
def create_review(request, item_id,
template_name="reviewclone/create_review.html"):
"""
Current user can create a new review.
Find the item with `item_id` then make sure the current user
does not already have a review. If a review is found
`review_exist` will be True. If the cur... | 17,176 |
def removeDir(path):
""" Remove dir on a given path, even if it is not empty. """
try:
shutil.rmtree(path)
except OSError as exc:
# Silently catch the exception if the directory does not exist
if exc.errno != 2:
raise | 17,177 |
def get_backend_bucket_output(backend_bucket: Optional[pulumi.Input[str]] = None,
project: Optional[pulumi.Input[Optional[str]]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetBackendBucketResult]:
"""
Returns the specified Ba... | 17,178 |
def build_level_codes(incoming_column_name: str, levels: Iterable) -> List[str]:
"""
Pick level names for a set of levels.
:param incoming_column_name:
:param levels:
:return:
"""
levels = [str(lev) for lev in levels]
levels = [incoming_column_name + "_lev_" + clean_string(lev) for lev ... | 17,179 |
def get_all(isamAppliance, check_mode=False, force=False):
"""
Get all rsyslog objects
"""
return isamAppliance.invoke_get("Get all rsyslog objects",
"/core/rsp_rsyslog_objs") | 17,180 |
def genomic_dup1_37_loc():
"""Create test fixture GRCh37 duplication subject"""
return {
"_id": "ga4gh:VSL.CXcLL6RUPkro3dLXN0miGEzlzPYiqw2q",
"sequence_id": "ga4gh:SQ.VNBualIltAyi2AI_uXcKU7M9XUOuA7MS",
"interval": {
"type": "SequenceInterval",
"start": {"value": 4... | 17,181 |
def parse(f, _bytes):
"""
Parse function will take a parser combinator and parse some set of bytes
"""
if type(_bytes) == Parser:
return f(_bytes)
else:
s = Parser(_bytes, 0)
return f(s) | 17,182 |
def save(filestring, path):
"""Saves a filestring to file.
:param str filestring: the string to save.
:param str path: the place to save it."""
try:
with builtins.open(path, "w") as f: f.write(filestring)
except:
with builtins.open(path, "wb") as f: f.write(filestring) | 17,183 |
def spiral_tm(wg_width=0.5, length=2):
""" sample of component cutback """
c = spiral_inner_io_euler(wg_width=wg_width, length=length, dx=10, dy=10, N=5)
cc = add_gratings_and_loop_back(
component=c,
grating_coupler=pp.c.grating_coupler_elliptical_tm,
bend_factory=pp.c.bend_circular,... | 17,184 |
def test_show_router_interface(parsed_show_router_int):
"""
Test extracting router interfaces from show command
"""
data = "tests/fixtures/show_output/show_router_interface.txt"
sros_parser = SrosParser(data)
result = sros_parser.show_router_interface()
assert result == parsed_show_router_i... | 17,185 |
def test_cleanup_policy(faker):
"""Ensure the command creates a new policy and that is shows on the list"""
x_name = faker.pystr()
# CLI accepts days, Nexus stores seconds
downloaded = faker.random_int(1, 365)
x_downloaded = str(downloaded * 86400)
updated = faker.random_int(1, 365)
x_update... | 17,186 |
def get_url_until_success(url):
"""Continuously tries to open a url until it succeeds or times out."""
time_spent = 0
while (time_spent < RECEIVE_TIMEOUT):
try:
helps = urllib2.urlopen(url)
break
except:
time.sleep(RETRY_INTERVAL)
time_spent += RETRY_INTERVAL
if (time_spent >= R... | 17,187 |
def _chunk(fst: pynini.Fst) -> List[Tuple[str, str]]:
"""Chunks a string transducer into tuples.
This function is given a string transducer of the form:
il1 il2 il3 il4 il5 il6
ol1 eps eps ol2 eps ol3
And returns the list:
[(il1 il2 il3, ol1), (il4 il5, ol2), (il6, ol3)]
It ... | 17,188 |
def auth_token_required(func):
"""Your auth here"""
return func | 17,189 |
def run_data_assimilation(wrf_model, fm10, wrf_model_prev = None):
"""
Run the fuel moisture and DA for all time steps in the model wrf_model.
If a previous run is available, the fuel moisture values (and covariance if available)
are transferred.
:param wrf_model: the current WRF data file to proce... | 17,190 |
def base_convert_money(amount, currency_from, currency_to):
"""
Convert 'amount' from 'currency_from' to 'currency_to'
"""
source = get_rate_source()
# Get rate for currency_from.
if source.base_currency != currency_from:
rate_from = get_rate(currency_from)
else:
# If curren... | 17,191 |
def init_dask_workers(worker, config, obj_dict=None):
"""
Initalize for all dask workers
:param worker: Dask worker
:type worker: object
:param config: Configuration which contains source and sink details
:type config: dict
:param obj_dict: Objects that are required to be present on every da... | 17,192 |
async def contestant() -> dict:
"""Create a mock contestant object."""
return {
"id": "290e70d5-0933-4af0-bb53-1d705ba7eb95",
"first_name": "Cont E.",
"last_name": "Stant",
"birth_date": date(1970, 1, 1).isoformat(),
"gender": "M",
"ageclass": "G 12 år",
"... | 17,193 |
def GetApitoolsTransport(timeout='unset',
enable_resource_quota=True,
response_encoding=None,
ca_certs=None,
allow_account_impersonation=True,
use_google_auth=None,
respo... | 17,194 |
def user_requested_anomaly7():
""" Checks if the user requested an anomaly, and returns True/False accordingly. """
digit = 0
res = False
if is_nonzero_file7(summon_filename):
lines = []
with open(get_full_path(summon_filename)) as f:
lines = f.readlines()
if len(line... | 17,195 |
def test_data_process_content():
"""Test the _data_process_content function."""
# test case 1
dataio = fmu.dataio.ExportData(
name="Valysar",
config=CFG2,
content="depth",
timedata=[["20210101", "first"], [20210902, "second"]],
tagname="WhatEver",
)
obj = xtge... | 17,196 |
def test_path_count_priority_cache(tmpdir, allocate_GB):
"""
Test PathCountPriorityCache by runnin the same DWWC computation three times.
"""
hetmat = get_graph('bupropion-subgraph', hetmat=True, directory=tmpdir)
cache = hetmech.hetmat.caching.PathCountPriorityCache(hetmat, allocate_GB)
hetmat.... | 17,197 |
def mat_to_r(_line, _mat_object : MatlabObject, _r_object : RObject = RObject()):
"""Move variables from Matlab to R
Parameters
----------
_line : str, Iterable[str]
If str, one of the following:
1. '#! m[at[lab]] -> <vars>'
2. '<vars>'
where <vars> is a comma separated list of Matlab variable names
I... | 17,198 |
def write_powerball_numbers():
"""Writes a CSV file of "Powerball" numbers and their draw distribution.
Args:
None
Returns:
A CSV file where the first column contains each "Powerball" number
and the second column contains the corresponding draw distribution
for that number.... | 17,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.