content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def find_closest_raster(return_period,aoi_col='AoI_RP{}y_unique',depth_col='RP{}_max_flood_depth'):
"""
Find the closest AoI and Flood raster column name for given return period
Arguments:
*return_period* (float): Return period of the flood for which to find the nearest inundation raster
*a... | 68,300 |
def svn_diff_fns_invoke_datasource_get_next_token(*args):
"""svn_diff_fns_invoke_datasource_get_next_token(svn_diff_fns_t _obj, void diff_baton, svn_diff_datasource_e datasource) -> svn_error_t"""
return _diff.svn_diff_fns_invoke_datasource_get_next_token(*args) | 68,301 |
def plot_lstsq(rec, event_station_pairs, ax=None, base=np.e, **kwargs):
"""Plot solution of weighted least squares inversion"""
eventids, stations = zip(*event_station_pairs)
eventids = list(OrderedDict.fromkeys(eventids))
stations = list(OrderedDict.fromkeys(stations))
err, g0, b, W, R, info = rec... | 68,302 |
def _is_bn_diff_doctypes(dyad):
"""Check if a dyad is between two different doctypes.
Args:
dyad (tuple): two-item tuple where each item is a dict which represents a document
Returns:
ind (bool): True if the dyad is between two different doctypes
"""
if dyad[0]["doctype"] != dyad[... | 68,303 |
def selectcontains(table, field, value, complement=False):
"""Select rows where the given field contains the given value."""
return selectop(table, field, value, operator.contains,
complement=complement) | 68,304 |
def with_path_to(q, value, info, union=False, name='with_path_to'):
"""This will traverse any (any meaning any paths specified in the path
generation heuristic which prunes some redundant/wandering paths)
from the source entity to the given target type where it will
apply a given query.
This filter... | 68,305 |
def get_links(entry: Dict, html_data: Text) -> List[urllib.parse.ParseResult]:
"""Extract any links from the html"""
links = []
soup = BeautifulSoup(html_data, "html.parser")
if soup:
links = [a['href'] for a in soup.findAll('a', href=True)]
else:
logging.warning("soup is none : %s"... | 68,306 |
def write_file(filename, data):
"""
Writes to a file by outputting, line by line, the elements of a list.
arguments: filename, list of strings.
"""
with open(filename,'w') as f:
print(*data,sep='\n',file=f) | 68,307 |
def conjgrad (A, b, x = None, iterations = 10**6, epsilon = 10**(-10)):
"""
Méthode du gradient conjugué.
-----------------------------
Entrée:
A matrice symétrique définie positive.
b vecteur colonne.
(optional) x vecteur initial de la suite.
... | 68,308 |
def mge_to_tflite(
mge_fpath,
output="out.tflite",
*,
graph_name="graph",
mtk=False,
disable_nhwc=False,
outspec=None,
):
"""
Convert megengine model to TFLite,
and save the TFLite model to file `output`.
:param mge_fpath: the file path of megengine model.
:type fpath: s... | 68,309 |
def get_and_check_counter(counter, cloudservice_name, management,
storageacct_name, warning, critical, verbosity):
"""retrieve performance counter and evaluate with respect to warning and
critical range and return appropriate error message
management - storagemanagement object
... | 68,310 |
def _transform_build_config(config, config_files, whitelabel):
"""Transforms Config instance into target platform JSON schema.
Args:
config: Config namedtuple
config_files: Map to look up the generated config files.
whitelabel: Whether the config is for a whitelabel design
Returns:
Unique config... | 68,311 |
def is_valid(token):
"""Checks if the token is valid.
Args:
token (str): Token
Returns:
Boolean: True or false
"""
if len(token) < 64:
return False
now = datetime.now().timestamp()
time = token[22:][:20]
decode_timstamp = binascii.unhexlify(time).decode(CHARSETS... | 68,312 |
def shared_dataset(filename):
"""Returns the training-, validation- and test-datasets as shared variables"""
train_set, valid_set, test_set = load_dataset(filename)
train_x, train_y = shared_variables(train_set, 'Training')
valid_x, valid_y = shared_variables(valid_set, 'Validation')
test_x, test_y... | 68,313 |
def _stats_print(good_noise, good_gains, good_fit, test_chans):
"""Generate a simple set of statistics for the test
and print them to screen.
"""
print("\nFilter statistics:")
good_chans = [1] * len(test_chans)
Nact = len(test_chans) # Number of active channels
if good_noise is not None:
... | 68,314 |
def text():
"""make text files"""
return build('text', 'The text files are in {}.') | 68,315 |
def upload2ipfs(file_path: str) -> str:
"""Upload to ipfs using local port.
IPFS node must be running locally. Run:
$ ipfs daemon
Args:
nft_path (str): path to metadata file
"""
with open(file_path, "rb") as f:
nft_binary = f.read()
ipfs_endpoint = "http://127.0.0.1:5001/"
... | 68,316 |
def rotateImage(imgdata, org_corners):
"""
"""
rotation = calculateRotation(org_corners.ul, org_corners.ur)
rot_img = skimage.transform.rotate(imgdata, rotation, resize = True, preserve_range = True)
return rot_img | 68,317 |
def mean_absolute_scaled_error(y_true: ArrayLike, y_pred: ArrayLike) -> float:
"""Compute the mean absolute scaled error (MASE).
MASE is computed by comparing mean absolute error of the predictions to
the mean absolute error obtained from a lag-1 forecast.
Args:
y_true: the actual values.
... | 68,318 |
def GetCloudBasePath():
"""Returns the folder within the Makani bucket where all databases live."""
return 'gs://gcp-public-data-makani-deps/deps/turbsim_databases' | 68,319 |
def open_repo(*args, **kwargs):
"""Yields a git.Repo and ensures closing."""
repo = git.Repo(*args, **kwargs)
try:
yield repo
finally:
repo.close() | 68,320 |
def test_main_w_version(mocker, capsys):
"""Test calling the CLI with the --version option"""
mocker.patch.object(sys, 'argv', ['temple', '--version'])
temple.cli.main()
out, _ = capsys.readouterr()
assert out == 'temple %s\n' % temple.__version__ | 68,321 |
def create_entity(station: WeatherStationTuple) -> dict:
""" Conversion from input data to desired properties and types """
entity = Entity()
entity.provider = 'bom'
entity.country = 'Australia'
entity.country_code = 'AU'
entity.state = station.state
entity.site = station.site
... | 68,322 |
def line(char='-', length=48):
"""Generates a string of characters with a certain length"""
return ''.join([char for _ in range(length)]) | 68,323 |
def ca_receive(priority, pgn, source, timestamp, data):
"""Feed incoming message to this CA.
(OVERLOADED function)
:param int priority:
Priority of the message
:param int pgn:
Parameter Group Number of the message
:param intsa:
Source Address of the message
:param int tim... | 68,324 |
def dict_update(d, u):
"""Recursive update dictionary"""
for k, v in u.items():
if isinstance(v, collections.Mapping):
d[k] = dict_update(d.get(k, {}), v)
else:
d[k] = v
return d | 68,325 |
def _handle_tracking(request, response):
"""Handles the share tracking logic so that users get their number of shares increased
when someone downloads Firefox mobile via their user page."""
if not _has_parent_cookie(request):
parent_username = _add_share_from_cookies(request)
# Set a 'par... | 68,326 |
def prompt_yn(msg, default=None):
"""
Prompts the user for a y/n response.
default param should be either 'y' or 'n'
Returns True if 'Y' and False if 'N'
"""
if default is True:
default = 'y'
elif default is False:
default = 'n'
if default == 'y' or default is True:
... | 68,327 |
def noise_for_example(x, extent=1000, intensity=0.1, rng=None, **kwargs):
"""
Add noise to x. Just for demonstration.
Arguments:
extent -- number of points to add noise at
intensity -- scale parameter of half-normal distribution; samples
from this distribution will be added at each nois... | 68,328 |
def get_spectra(st, event, inventory, synthetic_picks,
calc_displacement=False,
S_win_len=.1, P_or_S='P'):
""" Calculate the fft at each channel in the stream that has an arrival
in event.arrivals
:param st: uquake.core.stream.Stream
:type st: uquake.core.stream... | 68,329 |
async def upload_file(request: Request, file: List[UploadFile] = File(...)):
"""
Uploads temporary file which is loadied in to the cdQA model as the data
"""
query = await request.form()
user = request.headers["authorization"]
#csv_folder = f'data/uploaded/{user}/csv'
upload_folder = ... | 68,330 |
def datasets_loader(conf, train=True, dev=True, test=True):
"""
simple wrapper for unified interface of datasets loaders
"""
fmt = conf.pop("fmt")
if fmt == "kaldi_ra":
return kaldi_ra_datasets_loader(conf, train, dev, test)
else:
raise ValueError("dataset format %s not supported... | 68,331 |
def calc_all_scores(pair_file, score_file):
""" Calculate the entire score file """
pair_scores = score_file.name + '-' + pair_file.name
pair_scores = SCOREDIR / pair_scores
have_scores = set()
if OVERWRITE and pair_scores.is_file():
pair_scores.unlink()
if pair_scores.is_file():
... | 68,332 |
def remove_existing_datasets(viable_datasets, connection):
"""Remove the viable datasets that are already existing datasets."""
for dataset_type in viable_datasets:
for container, datasets in viable_datasets[dataset_type].items():
actually_viable_datasets = []
for viable_dataset... | 68,333 |
def group_by_size(input_tensors, bytes_per_pack):
"""Groups `input_tensors` into chunks of `bytes_per_pack`.
The method preserves the original order of `input_tensors`. The grouping is
best effort, each pack could have more or less bytes than `bytes_per_pack`.
It only groups values with known shape.
Args:
... | 68,334 |
def np_emd_loss(y_true, y_pred, reduction_axis=None, num_bins=327, **kwargs):
"""Earth Mover Distance between two waveforms
Parameters
----------
y_true : np.ndarray
A tensorflow tensor defining the true waveform
shape: [batch_size, num_bins]
y_pred : np.ndarray
A tensorflow... | 68,335 |
def adapters(text):
"""
Parse lines of text into a list of adapters (represented by their joltage),
supplemented by the outlet (0) and your device (maximum + 3).
"""
adapters = list(sorted(map(int, text.splitlines())))
adapters = [0] + adapters + [max(adapters) + 3]
return adapters | 68,336 |
def test_reorder_to_cellsize():
"""
Test reordering to different cellsize
"""
lons = np.array([-177, -177, -176, -176])
lats = np.array([51, 57, 51, 57])
gpis = np.array([1, 2, 3, 4])
cells = np.array([14, 14, 14, 14])
orig_grid = grids.CellGrid(lons, lats, cells, gpis=gpis)
reordere... | 68,337 |
def read_local_config(options, filename):
""" Read the given configuration filename and save values in 'options'
This function recognizes only one section:
'[main]'
Within this section, this function recognizes only:
'sheetname' - name of spreadsheet file in Drive
... | 68,338 |
def generate_dem(chunk: ms.Chunk, redo: bool = False):
"""
Generate a DEM using PDAL.
Generating a DEM in PDAL is better than in Metashape since the grid size can be specified and interpolation is off.
param: chunk: The input chunk.
param: redo: Whether to redo the analysis even if it is partially... | 68,339 |
def assign_bonds_to_groups(tors, group):
"""
|
**Description:** Make a group for each torsion bond
and keep track of how many members
Finally it returns the biggest group.
**Input:**
- Tors: atoms with torsions
- Group: Atoms grouped by proximity
**Output:**
- output: li... | 68,340 |
def _build_generator_map():
"""Build a map of sdtype to data generator.
Output:
dict:
A mapping of sdtype (str) to a list of data
generators (rdt.tests.datasets.BaseDatasetGenerator).
"""
generators = defaultdict(list)
for generator in BaseDatasetGenerator.get_subcl... | 68,341 |
def read_file(path, sep):
"""
ファイルの読み込みを行う。一度に、複数ファイルの読み込みも可能。
相対パスと絶対パス、どちらでも可能。
Input
------
path : 読み込みたいファイルへのパス
sep : 読み込みたいファイルの区切り文字の指定
Output
------
df_array : 読み込んだdfのリスト
path_array : globで取得した、ファイルパスのリスト
Raises
------
存在しないディレクトリやパスが指定された時。
入力に... | 68,342 |
def get_ignore_unknown_patterns():
"""
Fetch the value of the setting that tells us what unknown overrides we
should ignore in reports. The regular expressions from the settings file
(if any) are compiled in the returned list.
When the setting is a boolean, the result is either an empty list or a l... | 68,343 |
def main(xyz_file) -> Any:
"""
Execute main code for function by reading an xyz file and returning persistence diagram
Arg: xyz_file is the name of an xyz structure (which is stored in 'xyz_structures')
Return: persistence diagram from Delaunay triangulation, current file name
"""
# Point to x... | 68,344 |
def test_dal_method_middleware():
"""
Verify that when calling a method on a service off the DAL,
the method middlewares run, in the correct order and run
before the method itself is called.
We deliberately do not use the DalMethodResolverMiddleware here,
because we are testing middleware call... | 68,345 |
def purge_deployment(namespace, label_selector):
"""Delete all resources matching a label selector"""
delete_resources(namespace, '--selector', label_selector) | 68,346 |
def chain_functions(fun_first: tp.Callable[..., tp.Union[tp.Tuple[tp.Tuple, tp.Dict],
tp.Dict, tp.Tuple]]) -> tp.Callable:
"""
A decorator to chain function calls.
This function is expected to return:
* a 2-tuple [tp.Tuple, tp.Dict] - args and k... | 68,347 |
def find_variables(
expr: Union[types.Constraint, List[types.Constraint], Tuple[types.Constraint]]
) -> Set[core.Symbol]:
"""Find variables in constraints."""
if not isinstance(expr, (list, tuple)):
expr = []
variables = set()
for e in expr:
variables |= e.free_symbols
return variables | 68,348 |
def codespacerange(toUnicode):
""" """
re_code = re.compile(rb'beginbfrange.*?<(\w*)>.*?<(\w*)>.*?<(\w*)>.*?endbfrange', re.S)
for match in re.finditer(re_code, toUnicode):
print(f"{match.group(1)} {match.group(2)} {match.group(3)}") | 68,349 |
def _add_cell_methods(merge_file):
"""Add the cell_methods attribute to select variables."""
cmd = "%s/ncatted" %(_NCO_DIR)
cmd = _add_cell_methods_1(cmd)
cmd = _add_cell_methods_2(cmd)
cmd += " %s" %(merge_file)
_run_cmd(cmd, "[ERR] Problem with ncatted!") | 68,350 |
def highlight_symbol_in_DECOMP():
"""
Select a symbol in the IDA DISASM view,
highlight the corresponding symbol in DECOMP view.
"""
# print("GhIDA:: [DEBUG] highlight_symbol_in_DECOMP called")
symbol = get_highlighted_identifier()
if not symbol:
return
converted_symbol = from_i... | 68,351 |
def _number_of_neighbors(i, j, height, width, state):
"""
Counts the number of LIVE neighbors of the cell in position (i, j).
:param i: Row of the cell.
:param j: Column of the cell.
:param height: Height of the input state.
:param width: Width of the input state.
:param state: A game state... | 68,352 |
def assert_rank(tensor, expected_rank, name=None):
"""Raises an exception if the tensor rank is not of the expected rank.
Args:
tensor: A tf.Tensor to check the rank of.
expected_rank: Python integer or list of integers, expected rank.
name: Optional name of the tensor for the error message.
... | 68,353 |
def _format_cpu_memory(container_group):
"""Format CPU and memory. """
containers = container_group.get('containers')
if containers is not None and containers:
total_cpu = 0
total_memory = 0
for container in containers:
resources = container.get('resources')
i... | 68,354 |
def create_category(name):
"""
Create a new category
:param name:
:return object:
"""
category = Category(name=name)
session.add(category)
session.commit()
return category | 68,355 |
def load_user(user, db_session):
"""
Load user from the database
"""
res = (
db_session.query(User)
.filter_by(username=user) # pylint: disable=no-member
.first()
)
if not res: # add user to DB
db_user = User(username=user)
# make first user admin
... | 68,356 |
def logpost_negb(state,params):
"""
Compute log-posterior density values; this function assumes
the likelihood is a product of negative-binomial distributions
Parameters
----------
state: python list or numpy array
model parameters
params: dictionary
detailed settings for... | 68,357 |
def parse_user_config():
"""Loads a user's configuration"""
parse_simple_config(USER_CONFIG_PATH, USER_CONFIG) | 68,358 |
def GetBinhostCache(options):
"""Get and optionally clear the binhost cache."""
cache_dir = os.path.join(path_util.FindCacheDir(),
'cros_install_debug_syms-v' + CACHE_VERSION)
if options.clearcache:
osutils.RmDir(cache_dir, ignore_missing=True)
binhost_cache = None
if options.c... | 68,359 |
def matcher(callable_or_names, names=None):
"""
Implicitly registers it with function's __name__, "be_a_dog":
@matcher
def be_a_dog(x):
return type(x) == dog
Explicitly registers it with names "be_a_dog" and "be_canine"
@matcher("be_a_dog, be_canine")
def whatever(x):
retu... | 68,360 |
def main():
"""Make a jazz noise here"""
args = get_args()
letter = args.letter
for line in args.file:
if line[0].upper() == letter.upper():
print(line, end='')
sys.exit(0)
print(f'I do not know "{letter}".') | 68,361 |
def helicsFilterAddDeliveryEndpoint(filter: HelicsFilter, delivery_endpoint: str):
"""
Clone filter functions.
Functions that manipulate cloning filters in some way.
Add a delivery endpoint to a cloning filter.
All cloned messages are sent to the delivery address(es).
**Parameters**
- **`f... | 68,362 |
def update_tree(
tree: EmptyTree, oid: str, current_user: User = Depends(get_current_active_user)
):
"""
Update tree DB entry
"""
print(tree)
try:
selected_tree = TreeDB.objects.get(id=oid)
selected_tree.species = tree.species if tree.species else selected_tree.species
s... | 68,363 |
def get_queue_jobs(queue_name):
"""Get the jobs by status of a Queue.
Args:
queue_name (str): The RQ Queue name
Returns:
dict: Number of jobs by job status
Raises:
redis.exceptions.RedisError: On Redis connection errors
"""
queue = Queue(queue_name)
return {
... | 68,364 |
def update_lengths(lengths, eoses, idx):
"""Update the length of a generated tensor based on the first EOS found.
This is useful for a decoding situation where tokens after an EOS
can be something other than EOS. This also makes sure that a second
generated EOS doesn't effect the lengths.
:param l... | 68,365 |
def delete_widget_config(id_):
"""Deletes a widget
:param id: ID of the widget to delete
:type id: str
:rtype: tuple
"""
widget_config = WidgetConfig.query.get(id_)
if not widget_config:
return "Not Found", 404
else:
session.delete(widget_config)
session.commit(... | 68,366 |
def detail_view(request):
"""
Directs user to the detail template
"""
try:
symbol = request.matchdict['symbol']
except KeyError:
return HTTPNotFound()
try:
query = request.dbsession(Account)
stock_detail = query.filter(Account.username == request.authenticated_us... | 68,367 |
def is_right_censored(lc, frange):
""" Returns true if the light curve is cutoff on the right. """
return len(lc['t0'])-1 in frange | 68,368 |
def test_multiple_awards_update_date(submissions, award_data2):
"""Update 5 award records, excluding 5 based on update_date"""
award_id, yesterday = award_data2
today = datetime.now(timezone.utc)
assert Award.objects.count() == 10, "Missing Award objects"
assert Award.objects.filter(update_date__lt... | 68,369 |
def neural_net_learning_rate_input():
"""
Return a Tensor for the learning rate
"""
return tf.placeholder(tf.float64, name="learning_rate") | 68,370 |
def decode_csr(b64der):
"""
Decode JOSE Base-64 DER-encoded CSR.
:param str b64der: The encoded CSR.
:rtype: `cryptography.x509.CertificateSigningRequest`
:return: The decoded CSR.
"""
try:
return x509.load_der_x509_csr(
jose.decode_b64jose(b64der), default_backend())
... | 68,371 |
def retrieve_span(task, task_id):
"""Helper to retrieve an active `Span` stored in a `Task`
instance
"""
weak_dict = getattr(task, CTX_KEY, None)
if weak_dict is None:
return
else:
return weak_dict.get(task_id) | 68,372 |
def check_data(func):
"""Decorator function for checking possible exceptions during extraction.
Args:
func (obj): function used in try-except block
Except:
(str) : in case of exception assigns '-' for the missing data.
"""
def inner(line):
try:
return func(line)... | 68,373 |
def fscale(ns, si=1, one_sided=False):
"""
numpy.fft.fftfreq returns Nyquist as a negative frequency so we propose this instead
:param ns: number of samples
:param si: sampling interval in seconds
:param one_sided: if True, returns only positive frequencies
:return: fscale: numpy vector contain... | 68,374 |
def test_calculate_aep_curve():
""" Test Calculate AEP curve"""
aep = plt_calculator.calculate_aep_curve(TEST_PLT, 5)
assert isinstance(aep, EPCurve)
assert aep.get_ep_type() == EPType.AEP
assert aep.loss_at_a_given_return_period(5) == 3000
assert aep.loss_at_a_given_return_period(2.5) == 900
... | 68,375 |
def get_features_from_files(
data_dir,
features_ext='.proc.c3d-avg.npy',
test_split=[],
classes=None,
max_elements=13320):
"""
Creates and executes mPyPl pipe to load feature vectors from serialized files and returns a preprocessed
data stream that can be further used with respect to... | 68,376 |
def crypto_hash(*args):
"""
Return a SHA-256 hash of the given arguments
"""
stringified_args = sorted(map(lambda x: json.dumps(x), args))
joined_data = "".join(stringified_args)
return hashlib.sha256(joined_data.encode("utf-8")).hexdigest() | 68,377 |
def vectorized(csm, e, h, r0, rm, kj):
""" Uses Numpys fast array operations, distributed via the mkl-package.
Those oparations are already optimized and use all available physical cores.
"""
nFreqs = csm.shape[0]
nGridPoints = r0.shape[0]
beamformOutput = np.zeros((nFreqs, nGridPoints), np.comp... | 68,378 |
def is_empty_line(line: str) -> bool:
"""Checks whether a line is empty."""
return line.strip("\n").strip("\t").strip() == "" | 68,379 |
def to_host_list(value):
"""Space separated list of FQDNs."""
return value.split() | 68,380 |
def drop_prediction_column(data_path, group_name, column_name, yes=True):
"""
Deletes prediction columns in a h5py file if the columns exist.
Including 'mean' and 'std' columns.
"""
n_del = 0
with h5py.File(data_path, "r+") as f:
if group_name not in f.keys():
return n_del
... | 68,381 |
def create_indep_noise_weight_matrix(Nbm, Knoise, gamma, g, w):
"""create a weight matrix for Nbm * Knoise sources projecting to Nbm
targets with a fixed indegree of Knoise. no shared inputs are
allowed, hence each target receives uncorrelated input of the
sources are uncorrelated.
"""
Nnoise ... | 68,382 |
def tensordot(x, y, axis=2):
""" Compute tensor dot product along specified axes.
axes : int or (2,) array_like
integer_like If an int N, sum over the last N axes of a and the first N axes
of b in order. The sizes of the corresponding axes must match.
(2,) array_like Or, a list of axes to be summed ove... | 68,383 |
def _is_tarfile(filename):
"""Returns true if 'filename' is TAR file."""
return (filename.endswith(".tar") or filename.endswith(".tar.gz") or
filename.endswith(".tgz")) | 68,384 |
def deleteAnonMsgs(key, dbn='anon', env=None):
"""
Deletes messages at key uid
Parameters:
key is anon uid
dbn is name str of named sub database, Default is 'anon'
env is main LMDB database environment
If env is not provided then use global gDbEnv
"""
global gDbE... | 68,385 |
async def test_congregate_not_sure():
"""
Selecting not sure should give a description, then ask the question again
"""
u = User(
addr="27820001001", state=StateData(name="state_congregate"), session_id="1"
)
app = Application(u)
msg = Message(
content="not sure",
to_... | 68,386 |
def transfer(
self, new_owner, teams=github.GithubObject.NotSet
):
"""
:calls: POST /repos/:owner/:repo/transfer
:param new_owner: string
:param teams: list of team member ids
"""
assert isinstance(new_owner, str), new_owner
assert teams is github.GithubObject.NotSet or isInstance(
... | 68,387 |
def configured_model():
"""
Fixture for configured model - this was how aliasing was achieved for the first schema,
but since nearly every object will need aliasing methods, the models now inherit from
AbstractModel - this fixture is for testing that AbstractModel behaves the same as a
configured mo... | 68,388 |
def get_rho(w):
"""
:param w: 対象の値
最小位から数えて最初の1ビットの位置(1-indexed)
"""
return libc.ffs(w) | 68,389 |
def check_mergeinfo_recursively(root_path, subpaths_mergeinfo):
"""Check that the mergeinfo properties on and under ROOT_PATH are those in
SUBPATHS_MERGEINFO, a {path: mergeinfo-prop-val} dictionary."""
expected = verify.UnorderedOutput(
[path + ' - ' + subpaths_mergeinfo[path] + '\n'
for path in subp... | 68,390 |
def test_run_transform(inputs, transform_to_type, tmp_path: Path):
"""
Test run_transform.
"""
cli.run_transform(inputs, transform_to_type, str(tmp_path))
for x in tmp_path.iterdir():
if len(inputs) == 1:
test_gdf = gpd.read_file(Path(x))
original_gdf = gpd.read_file(... | 68,391 |
def data_collection(env: gym.Env,
num_episodes: int = 10,
epsilon: float = 0.2,
use_gt_states: bool = False,
use_tqdm: bool = False):
""" Collect demonstration dataset """
train_inputs = []
train_actions = []
train_states = ... | 68,392 |
def get_running_loop() -> Optional[asyncio.AbstractEventLoop]:
"""Check if an event loop is already running."""
with contextlib.suppress(RuntimeError):
if hasattr(asyncio, "get_running_loop"):
return cast(
asyncio.AbstractEventLoop,
asyncio.get_running_l... | 68,393 |
def distance_diff_catl(ra, dist, gap):
"""
Computes the necessary distance between catalogues
Parameters
-----------
ra: float
1st distance
dist: float
2nd distance
Returns
-----------
dist_diff: float
amount of distance necessary between mocks
"""
... | 68,394 |
def test_fibonacci_generator_0_to_1():
"""This function test fibonacci for 1 value
"""
generated = fibonacci.fibonacci(1)
expected = [0, 1]
for i in expected:
assert next(generated) == i | 68,395 |
def calculate_degree(network):
"""Calculates the degree of the nodes from the from and to ids. It
is not wise to call this method after removing nodes or edges
without first resetting the ids
Args:
network (class): A network composed of nodes (points in space) and edges (lines)
Returns:
... | 68,396 |
def parse_token(filehandle, token):
"""Iterates through filehandle until token found. If value found after
token, returns it."""
for line in filehandle:
line = line.strip()
if line.startswith(token):
if len(line) > len(token):
return line.rsplit('\t', 1)[1]
... | 68,397 |
def send_transaction(orderers, tran_req, tx_context):
"""Send a transaction to the chain's orderer service (one or more
orderer endpoints) for consensus and committing to the ledger.
This call is asynchronous and the successful transaction commit is
notified via a BLOCK or CHAINCODE event. This method ... | 68,398 |
def init_db_command():
"""Clear the existing data and create new tables. """
init_db()
click.echo('Initialized the database') | 68,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.