content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def expected_shd(posterior, ground_truth):
"""Compute the Expected Structural Hamming Distance.
This function computes the Expected SHD between a posterior approximation
given as a collection of samples from the posterior, and the ground-truth
graph used in the original data generation process.
Pa... | 5,500 |
def package_list_read(pkgpath):
"""Read package list"""
try:
with open(PACKAGE_LIST_FILE, 'r') as pkglistfile:
return json.loads(pkglistfile.read())
except Exception:
return [] | 5,501 |
def hpat_pandas_series_le(self, other, level=None, fill_value=None, axis=0):
"""
Pandas Series method :meth:`pandas.Series.le` implementation.
.. only:: developer
Test: python -m hpat.runtests hpat.tests.test_series.TestSeries.test_series_op8
Parameters
----------
self: :class:`pandas.S... | 5,502 |
def add_obs_info(telem, obs_stats):
"""
Add observation-specific information to a telemetry table (ok flag, and outlier flag).
This is done as part of get_agasc_id_stats. It is a convenience for writing reports.
:param telem: list of tables
One or more telemetry tables (potentially many observ... | 5,503 |
def plot_greedy_kde_interval_2d(pts, levels, xmin=None, xmax=None, ymin=None, ymax=None, Nx=100, Ny=100, cmap=None, colors=None, *args, **kwargs):
"""Plots the given probability interval contours, using a greedy
selection algorithm. Additional arguments passed to
:func:`pp.contour`.
The algorithm uses... | 5,504 |
def map_view(request):
"""
Place to show off the new map view
"""
# Define view options
view_options = MVView(
projection='EPSG:4326',
center=[-100, 40],
zoom=3.5,
maxZoom=18,
minZoom=2
)
# Define drawing options
drawing_options = MVDraw(
... | 5,505 |
def test_auto_linebreaks_no_ignore_lf(get_lcd):
"""
Do not ignore manual \n after auto linebreak.
"""
lcd = get_lcd(16, 2, True)
lcd.write_string('a' * 16) # Fill up line
lcd.write_string('\nb')
assert lcd._content[0] == [98, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97]
a... | 5,506 |
def decompose_jamo(compound):
"""Return a tuple of jamo character constituents of a compound.
Note: Non-compound characters are echoed back.
WARNING: Archaic jamo compounds will raise NotImplementedError.
"""
if len(compound) != 1:
raise TypeError("decompose_jamo() expects a single characte... | 5,507 |
def test_wrong_input():
"""Test all kinds of wrong inputs."""
with pytest.raises(ValueError):
HiddenLayerHandle(method="potato")(n_in=10, n_out=10, n_sample=100) | 5,508 |
def cp_in_drive(
source_id: str,
dest_title: Optional[str] = None,
parent_dir_id: Optional[str] = None,
) -> DiyGDriveFile:
"""Copy a specified file in Google Drive and return the created file."""
drive = create_diy_gdrive()
if dest_title is None:
dest_title = build_dest_title(drive, sou... | 5,509 |
def label_tuning(
text_embeddings,
text_labels,
label_embeddings,
n_steps: int,
reg_coefficient: float,
learning_rate: float,
dropout: float,
) -> np.ndarray:
"""
With N as number of examples, K as number of classes, k as embedding dimension.
Args:
'text_embeddings': flo... | 5,510 |
def create_nan_filter(tensor):
"""Creates a layer which replace NaN's with zero's."""
return tf.where(tf.is_nan(tensor), tf.zeros_like(tensor), tensor) | 5,511 |
def requestor_is_superuser(requestor):
"""Return True if requestor is superuser."""
return getattr(requestor, "is_superuser", False) | 5,512 |
def run_inital_basgra(basali, weed_dm_frac, harv_targ, harv_trig, freq):
"""
run an intial test
:param basali:
:param weed_dm_frac:
:return:
"""
params, matrix_weather, days_harvest, doy_irr = get_input_data(basali, weed_dm_frac, harv_targ=harv_targ,
... | 5,513 |
def process(business: Business, # pylint: disable=too-many-branches
filing: Dict,
filing_rec: Filing,
filing_meta: FilingMeta): # pylint: disable=too-many-branches
"""Process the incoming historic conversion filing."""
# Extract the filing information for incorporation
... | 5,514 |
def pid(text):
"""Print text if global debug flag set to true"""
if global_debug:
print(text) | 5,515 |
def est_const_bsl(bsl,starttime=None,endtime=None,intercept=False,val_tw=None):
"""Performs a linear regression (assuming the intercept at the origin).
The corresponding formula is tt-S*1/v-c = 0 in which tt is the travel
time of the acoustic signal in seconds and 1/v is the reciprocal of the
harmonic ... | 5,516 |
def GetExtractedFiles(Directory):
"""A generator that outputs all files in a diretory"""
for Thing in os.listdir(Directory):
PathThing = os.path.join(Directory, Thing)
if os.path.isdir(PathThing):
for File in GetExtractedFiles(PathThing):
yield File
els... | 5,517 |
def print_all(key = None):
"""
Prints out the complete list of physical_constants to the screen or
one single value
Parameters
----------
key : Python string or unicode
Key in dictionary `physical_constants`
Returns
-------
None
See Also
--------
_constants : C... | 5,518 |
def SeasonUPdate(temp):
""" Update appliance characteristics given the change in season
Parameters
----------
temp (obj): appliance set object for an individual season
Returns
----------
app_expected_load (float): expected load power in Watts
app_expected_dur (float): expected ... | 5,519 |
def pad_and_reshape(instr_spec, frame_length, F):
"""
:param instr_spec:
:param frame_length:
:param F:
:returns:
"""
spec_shape = tf.shape(instr_spec)
extension_row = tf.zeros((spec_shape[0], spec_shape[1], 1, spec_shape[-1]))
n_extra_row = (frame_length) // 2 + 1 - F
extension ... | 5,520 |
def GetExclusiveStorageForNodes(cfg, node_uuids):
"""Return the exclusive storage flag for all the given nodes.
@type cfg: L{config.ConfigWriter}
@param cfg: cluster configuration
@type node_uuids: list or tuple
@param node_uuids: node UUIDs for which to read the flag
@rtype: dict
@return: mapping from n... | 5,521 |
def get_read_data(file, dic, keys):
""" Assigns reads to labels"""
r = csv.reader(open(file))
lines = list(r)
vecs_forwards = []
labels_forwards = []
vecs_reverse = []
labels_reverse = []
for key in keys:
for i in dic[key]:
for j in lines:
if i in j[0]... | 5,522 |
def removeDuplicates(listToRemoveFrom: list[str]):
"""Given list, returns list without duplicates"""
listToReturn: list[str] = []
for item in listToRemoveFrom:
if item not in listToReturn:
listToReturn.append(item)
return listToReturn | 5,523 |
def check_hms_angle(value):
"""
Validating function for angle sexagesimal representation in hours.
Used in the rich_validator
"""
if isinstance(value, list):
raise validate.ValidateError("expected value angle, found list")
match = hms_angle_re.match(value)
if not match:
raise... | 5,524 |
def adjust_learning_rate(optimizer, epoch, default_lr=0.1):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
lr = default_lr * (0.1 ** (epoch // 30))
for param_group in optimizer.param_groups:
param_group['lr'] = lr | 5,525 |
def test_matcher_without_allure(
request: SubRequest,
pytester: Pytester,
):
"""Test matcher without allure"""
*_, not_implemented = test_cases()
percent = (len(scenarios) - len(not_implemented)) * 100 // len(scenarios)
with allure_unloaded(request):
pytester_result = run_tests(
... | 5,526 |
def test_merge_configs_extend_two():
"""Ensure extension on first level is fine"""
a = {'a': 1, 'b': 2}
b = {'c': 3}
m = resolve_config.merge_configs(a, b)
assert m == {'a': 1, 'b': 2, 'c': 3} | 5,527 |
def get_logger(module_name):
"""Generates a logger for each module of the project.
By default, the logger logs debug-level information into a
newscrapy.log file and info-level information in console.
Parameters
----------
module_name: str
The name of the module for which the logger sho... | 5,528 |
def stats():
"""Retrives the count of each object type.
Returns:
JSON object with the number of objects by type."""
return jsonify({
"amenities": storage.count("Amenity"),
"cities": storage.count("City"),
"places": storage.count("Place"),
"reviews": storage.count("Re... | 5,529 |
def test_task_persist(_task):
""" show that the task object is the same throughout """
_task.on_success = False # start False
def on_success(task, result):
task.on_success = True # change to True in success function
task.callback(0, result)
_task.call(
task_callback,
... | 5,530 |
def addflux2pix(px,py,pixels,fmod):
"""Usage: pixels=addflux2pix(px,py,pixels,fmod)
Drizel Flux onto Pixels using a square PSF of pixel size unity
px,py are the pixel position (integers)
fmod is the flux calculated for (px,py) pixel
and it has the same length as px and py
pixels is the imag... | 5,531 |
def get_dea_landsat_vrt_dict(feat_list):
"""
this func is designed to take all releveant landsat bands
on the dea public database for each scene in stac query.
it results in a list of vrts for each band seperately and maps
them to a dict where band name is the key, list is the value pair.
"""
... | 5,532 |
def test_validate_skip_inputs_fq_files_not_found(tmp_file):
"""
Test that non-existent :py:const:`riboviz.params.FQ_FILES` files
in the presence of both :py:const:`riboviz.params.VALIDATE_ONLY`
and :py:const:`riboviz.params.SKIP_INPUTS` returns a zero exit
code.
:param tmp_file: Path to tempora... | 5,533 |
def test_spammers_error(mailchimp, mailchimp_member, err_response):
"""Integration test to validate an error is thrown when mailchimp returns error during subscription"""
mailchimp.http_mock.post('https://us05.api.mailchimp.com/3.0/lists/test-list-id', json=err_response)
with pytest.raises(MailchimpSubscri... | 5,534 |
def load_json() -> tuple[list["Team"], list["User"]]:
"""Load the Json file."""
logging.debug("Starting to load data file.")
with open(".example.json") as file:
data = json.load(file)
if any(field not in data for field in REQUIRED_DATA_FIELDS):
raise ValueError("Required field is missin... | 5,535 |
def is_zh_l_bracket(uni_ch):
"""判断一个 unicode 是否是中文左括号。"""
if uni_ch == u'\uff08':
return True
else:
return False | 5,536 |
def test_archive__ArchiveForm__3(search_data, browser, role):
"""It cannot be accessed by non-admin users."""
browser.login(role)
browser.keyword_search('church')
# There is no archive option which can be applied:
assert (search_result_handlers_without_archive_for_editor
== browser.getCo... | 5,537 |
def petlink32_to_dynamic_projection_mMR(filename,n_packets,n_radial_bins,n_angles,n_sinograms,time_bins,n_axial,n_azimuthal,angles_axial,angles_azimuthal,size_u,size_v,n_u,n_v,span,n_segments,segments_sizes,michelogram_segments,michelogram_planes, status_callback):
"""Make dynamic compressed projection from list-mo... | 5,538 |
def is_core_recipe(component: Dict) -> bool:
"""
Returns True if a recipe component contains a "Core Recipe"
preparation.
"""
preparations = component.get('recipeItem', {}).get('preparations') or []
return any(prep.get('id') == PreparationEnum.CORE_RECIPE.value for prep in preparations) | 5,539 |
def login_submit_step(context):
"""
The cognito signin form is rendered in HTML twice for difference screen sizes.
The small screen version appears first in the HTML but is hidden by CSS.
Without the .visible-md class this resolves the hidden form element and
is unable to interact with the form.
... | 5,540 |
def build_estimator(output_dir, first_layer_size, num_layers, dropout,
learning_rate, save_checkpoints_steps):
"""Builds and returns a DNN Estimator, defined by input parameters.
Args:
output_dir: string, directory to save Estimator.
first_layer_size: int, size of first hidden layer of ... | 5,541 |
def importConfig():
"""設定ファイルの読み込み
Returns:
tuple:
str: interface,
str: alexa_remote_control.sh path
list: device list
"""
with open("config.json", "r", encoding="utf-8") as f:
config = json.load(f)
interface = config["interface"]
if not int... | 5,542 |
def create_dataset(project_id):
"""Creates a dataset for the given Google Cloud project."""
from google.cloud import datalabeling_v1beta1 as datalabeling
client = datalabeling.DataLabelingServiceClient()
# [END datalabeling_create_dataset_beta]
# If provided, use a provided test endpoint - this will... | 5,543 |
def create_local_command(opts: Options, jobs: List[Dict[str, Any]], jobs_metadata: List[Options]) -> str:
"""Create a terminal command to run the jobs locally."""
cmd = ""
for meta, job in zip(jobs_metadata, jobs):
input_file = meta.input.absolute().as_posix()
workdir = meta.workdir.absolute... | 5,544 |
def test_write_tags(tmpdir):
"""Test writing tags from a FLAC to mp3 file."""
# Prepare.
flac = tmpdir.mkdir('flac').join('song.flac').ensure(file=True)
mp3 = tmpdir.mkdir('mp3').join('song.mp3').ensure(file=True)
with open(os.path.join(os.path.dirname(__file__), '1khz_sine.flac'), 'rb') as f:
... | 5,545 |
def time_for_log() -> str:
"""Function that print the current time for bot prints"""
return time.strftime("%d/%m %H:%M:%S - ") | 5,546 |
def reset_session(self, request):
"""
Resets the session present in the current request,
to reset the session is to unset it from the request.
This method is useful for situation where a new session
context is required or one is meant to be created always.
:type request: Request
:... | 5,547 |
def _is_int(n) -> bool:
"""
is_int 是判断给定数字 n 是否为整数,
在判断中 n 小于epsilon的小数部分将被忽略,
是则返回 True,否则 False
:param n: 待判断的数字
:return: True if n is A_ub integer, False else
"""
return (n - math.floor(n) < _epsilon) or (math.ceil(n) - n < _epsilon) | 5,548 |
def _cpp_het_stat(A, t_stop, rates, t_start=0. * pq.ms):
"""
Generate a Compound Poisson Process (CPP) with amplitude distribution
A and heterogeneous firing rates r=r[0], r[1], ..., r[-1].
Parameters
----------
A : np.ndarray
CPP's amplitude distribution. A[j] represents the probabilit... | 5,549 |
def return_bad_parameter_config() -> CloudSettings:
"""Return a wrongly configured cloud config class."""
CloudSettingsTest = CloudSettings( # noqa: N806
settings_order=[
"init_settings",
"aws_parameter_setting",
"file_secret_settings",
"env_settings",
... | 5,550 |
def update(isamAppliance, instance_id, id, filename=None, contents=None, check_mode=False, force=False):
"""
Update a file in the administration pages root
:param isamAppliance:
:param instance_id:
:param id:
:param name:
:param contents:
:param check_mode:
:param force:
:return:... | 5,551 |
def view_deflate_encoded_content():
"""Returns Deflate-encoded data.
---
tags:
- Response formats
produces:
- application/json
responses:
200:
description: Defalte-encoded data.
"""
return jsonify(get_dict("origin", "headers", method=request.method, deflated=True)) | 5,552 |
def predict_from_word_vectors_matrix(tokens, matrix, nlp, POS="NOUN", top_number=constants.DEFAULT_TOP_ASSOCIATIONS):
"""
Make a prediction based on the word vectors
:param tokens:
:param matrix:
:param nlp:
:param POS:
:param top_number:
:return:
"""
vector_results = collect_wor... | 5,553 |
def get_luis_keys():
"""Retrieve Keys for LUIS app"""
load_dotenv()
key = os.getenv("LUIS_KEY")
region = os.getenv("LUIS_REGION")
app_id = os.getenv("LUIS_APP_ID")
return key, region, app_id | 5,554 |
def xls_to_dict(path_or_file):
"""
Return a Python dictionary with a key for each worksheet
name. For each sheet there is a list of dictionaries, each
dictionary corresponds to a single row in the worksheet. A
dictionary has keys taken from the column headers and values
equal to the cell value f... | 5,555 |
def blendImg(img_a, img_b, α=0.8, β=1., γ=0.):
"""
The result image is computed as follows:
img_a * α + img_b * β + γ
"""
return cv2.addWeighted(img_a, α, img_b, β, γ) | 5,556 |
def setup(app):
"""Sets up the extension"""
app.add_autodocumenter(documenters.FunctionDocumenter)
app.add_config_value(
"autoclass_content", "class", True, ENUM("both", "class", "init")
)
app.add_config_value(
"autodoc_member_order",
"alphabetical",
True,
E... | 5,557 |
def test_register_invalid_transfer(raiden_network, settle_timeout):
""" Regression test for registration of invalid transfer.
The bug occurred if a transfer with an invalid allowance but a valid secret
was registered, when the local end registered the transfer it would
"unlock" the partners' token, but... | 5,558 |
def genoimc_dup4_loc():
"""Create genoimc dup4 sequence location"""
return {
"_id": "ga4gh:VSL.us51izImAQQWr-Hu6Q7HQm-vYvmb-jJo",
"sequence_id": "ga4gh:SQ.-A1QmD_MatoqxvgVxBLZTONHz9-c7nQo",
"interval": {
"type": "SequenceInterval",
"start": {
"valu... | 5,559 |
def compare_versions(a, b):
"""Return 0 if a == b, 1 if a > b, else -1."""
a, b = version_to_ints(a), version_to_ints(b)
for i in range(min(len(a), len(b))):
if a[i] > b[i]:
return 1
elif a[i] < b[i]:
return -1
return 0 | 5,560 |
def check_ast_schema_is_valid(ast: DocumentNode) -> None:
"""Check the schema satisfies structural requirements for rename and merge.
In particular, check that the schema contains no mutations, no subscriptions, no
InputObjectTypeDefinitions, no TypeExtensionDefinitions, all type names are valid and not
... | 5,561 |
def get_machine_action_data(machine_action_response):
"""Get machine raw response and returns the machine action info in context and human readable format.
Notes:
Machine action is a collection of actions you can apply on the machine, for more info
https://docs.microsoft.com/en-us/windows/sec... | 5,562 |
def test_validate_cabling_invalid_ip_file():
"""Test that the `canu validate network cabling` command errors on invalid IPs from a file."""
invalid_ip = "999.999.999.999"
with runner.isolated_filesystem():
with open("test.txt", "w") as f:
f.write(invalid_ip)
result = runner.inv... | 5,563 |
def do_zone_validation(domain):
"""Preform validation on domain. This function calls the following
functions::
check_for_soa_partition
check_for_master_delegation
validate_zone_soa
.. note::
The type of the domain that is passed is determined
dynamically
:param... | 5,564 |
def BulkRemove(fname,masterfile=None,edlfile=None):
"""
Given a file with one IP per line, remove the given IPs from the EDL if they are in there
"""
global AutoSave
success = True
removes = list()
if os.path.exists(fname):
with open(fname,"rt") as ip_list:
for ip in ip_list:
removes.append(ip.strip(... | 5,565 |
def log(message, level_in=0, tag=PLUGIN_NAME):
"""
Writes to QGIS inbuilt logger accessible through panel.
:param message: logging message to write, error or URL.
:type message: str
:param level_in: integer representation of logging level.
:type level_in: int
@param tag: if relevant give t... | 5,566 |
def convolutionalize(modules, input_size):
"""
Recast `modules` into fully convolutional form.
The conversion transfers weights and infers kernel sizes from the
`input_size` and modules' action on it.
n.b. This only handles the conversion of linear/fully-connected modules,
although other modul... | 5,567 |
def is_unique2(s):
"""
Use a list and the int of the character will tell if that character has
already appeared once
"""
d = []
for t in s:
if d[int(t)]:
return False
d[int(t)] = True
return True | 5,568 |
def generate_wav(audio, file_name, sample_rate=41000):
"""
Generate .wav file from recorded audio
:param audio: Numpy array of audio samples
:param file_name: File name
:param sample_rate: Audio sample rate. (Default = 41000)
:return: None
"""
wavio.write(file_name, audio, sample_rate, s... | 5,569 |
def uncomplete_tree_parallel(x:ATree, mode="full"):
""" Input is tuple (nl, fl, split)
Output is a randomly uncompleted tree,
every node annotated whether it's terminated and what actions are good at that node
"""
fl = x
fl.parent = None
add_descendants_ancestors(fl)
y = AT... | 5,570 |
def stations_by_river(stations):
"""Give a dictionary to hold the rivers name as keys and their corresponding stations' name as values"""
rivers_name = []
for i in stations:
if i.river not in rivers_name:
rivers_name.append(i.river)
elif i.river in rivers_name:
contin... | 5,571 |
def clean():
"""Delete Generated Documentation"""
with lcd("docs"):
pip(requirements="requirements.txt")
local("make clean") | 5,572 |
def QA_SU_save_huobi(frequency):
"""
Save huobi kline "smart"
"""
if (frequency not in ["1d", "1day", "day"]):
return QA_SU_save_huobi_min(frequency)
else:
return QA_SU_save_huobi_day(frequency) | 5,573 |
def new_users():
"""
I have the highland! Create some users.
""" | 5,574 |
def get_cachefile(filename=None):
"""Resolve cachefile path
"""
if filename is None:
for f in FILENAMES:
if os.path.exists(f):
return f
return IDFILE
else:
return filename | 5,575 |
def inverse(a):
"""
[description]
calculating the inverse of the number of characters,
we do this to be able to find our departure when we arrive.
this part will be used to decrypt the message received.
:param a: it is an Int
:return: x -> it is an Int
"""
x = 0
while a * x % 9... | 5,576 |
def currency_column_to_numeric(
df: pd.DataFrame,
column_name: str,
cleaning_style: Optional[str] = None,
cast_non_numeric: Optional[dict] = None,
fill_all_non_numeric: Optional[Union[float, int]] = None,
remove_non_numeric: bool = False,
) -> pd.DataFrame:
"""Convert currency column to nume... | 5,577 |
async def subreddit_type_submissions(sub="wallstreetbets", kind="new"):
"""
"""
comments = []
articles = []
red = await reddit_instance()
subreddit = await red.subreddit(sub)
if kind == "hot":
submissions = subreddit.hot()
elif kind == "top":
submissions = subreddit.top()... | 5,578 |
def get_args():
"""Get argument"""
try:
opts, args = getopt.getopt(
sys.argv[1:],
"i:s:t:o:rvh",
["ibam=",
"snp=",
"tag=",
"output=",
"rstat", "verbose", "help"])
except getopt.GetoptError as err:
print(s... | 5,579 |
def _get_bundle_manifest(
uuid: str,
replica: Replica,
version: typing.Optional[str],
*,
bucket: typing.Optional[str] = None) -> typing.Optional[dict]:
"""
Return the contents of the bundle manifest file from cloud storage, subject to the rules of tombstoning. If version... | 5,580 |
def handler400(request, exception):
"""
This is a Django handler function for 400 Bad Request error
:param request: The Django Request object
:param exception: The exception caught
:return: The 400 error page
"""
context = get_base_context(request)
context.update({
'message': {
... | 5,581 |
def object_trajectory_proposal(vid, fstart, fend, gt=False, verbose=False):
"""
Set gt=True for providing groundtruth bounding box trajectories and
predicting classme feature only
"""
vsig = get_segment_signature(vid, fstart, fend)
name = 'traj_cls_gt' if gt else 'traj_cls'
path = get_featur... | 5,582 |
def _gather_topk_beams(nested, score_or_log_prob, batch_size, beam_size):
"""Gather top beams from nested structure."""
_, topk_indexes = tf.nn.top_k(score_or_log_prob, k=beam_size)
return _gather_beams(nested, topk_indexes, batch_size, beam_size) | 5,583 |
def _traceinv_exact(K, B, C, matrix, gram, exponent):
"""
Finds traceinv directly for the purpose of comparison.
"""
# Exact solution of traceinv for band matrix
if B is not None:
if scipy.sparse.isspmatrix(K):
K_ = K.toarray()
B_ = B.toarray()
if C is ... | 5,584 |
def create_feature_vector_of_mean_mfcc_for_song(song_file_path: str) -> ndarray:
"""
Takes in a file path to a song segment and returns a numpy array containing the mean mfcc values
:param song_file_path: str
:return: ndarray
"""
song_segment, sample_rate = librosa.load(song_file_path)
mfccs... | 5,585 |
def stations_highest_rel_level(stations, N):
"""Returns a list containing the names of the N stations
with the highest water level relative to the typical range"""
names = [] # create list for names
levels = [] # create list for levels
for i in range(len(stations)): # iterate through stat... | 5,586 |
def read_image(file_name, format=None):
"""
Read an image into the given format.
Will apply rotation and flipping if the image has such exif information.
Args:
file_name (str): image file path
format (str): one of the supported image modes in PIL, or "BGR"
Returns:
image (n... | 5,587 |
def reduce_opacity_filter(image, opacity_level):
"""Filter divides each pixel by the specified amount
of opacity_level
"""
data = []
image_data = get_image_data(image)
# creating new opacity level pixels
for i in range(len(image_data)):
current_tuple = list(image_data[i])
... | 5,588 |
def add_global_nodes_edges(g_nx : nx.Graph, feat_data: np.ndarray, adj_list: np.ndarray,
g_feat_data: np.ndarray, g_adj_list: np.ndarray):
"""
:param g_nx:
:param feat_data:
:param adj_list:
:param g_feat_data:
:param g_adj_list:
:return:
"""
feat_da... | 5,589 |
def _load_readme(file_name: str = "README.md") -> str:
"""
Load readme from a text file.
Args:
file_name (str, optional): File name that contains the readme. Defaults to "README.md".
Returns:
str: Readme text.
"""
with open(os.path.join(_PATH_ROOT, file_name), "r", encoding="ut... | 5,590 |
def get_data_collector_instance(args, config):
"""Get the instance of the data
:param args: arguments of the script
:type args: Namespace
:raises NotImplementedError: no data collector implemented for given data source
:return: instance of the specific data collector
:rtype: subclass of BaseDat... | 5,591 |
def timeIntegration(params):
"""Sets up the parameters for time integration
:param params: Parameter dictionary of the model
:type params: dict
:return: Integrated activity variables of the model
:rtype: (numpy.ndarray,)
"""
dt = params["dt"] # Time step for the Euler intergration (ms)
... | 5,592 |
def test_set_stage_invalid_buttons(memory):
"""Test setting the stage with invalid buttons."""
stage = 0
display = 1
expected_exception = 'buttons must be of type list'
with pytest.raises(Exception, message=expected_exception):
memory.set_stage(stage, display, '1, 2, 3, 4')
expected_ex... | 5,593 |
def is_role_user(session, user=None, group=None):
# type: (Session, User, Group) -> bool
"""
Takes in a User or a Group and returns a boolean indicating whether
that User/Group is a component of a service account.
Args:
session: the database session
user: a User object to check
... | 5,594 |
def argCOM(y):
"""argCOM(y) returns the location of COM of y."""
idx = np.round(np.sum(y/np.sum(y)*np.arange(len(y))))
return int(idx) | 5,595 |
def fringe(z, z1, z2, rad, a1):
"""
Approximation to the longitudinal profile of a multipole from a permanent magnet assembly.
see Wan et al. 2018 for definition and Enge functions paper (Enge 1964)
"""
zz1 = (z - z1) / (2 * rad / pc.pi)
zz2 = (z - z2) / (2 * rad / pc.pi)
fout = ( (1 / ... | 5,596 |
def random_param_shift(vals, sigmas):
"""Add a random (normal) shift to a parameter set, for testing"""
assert len(vals) == len(sigmas)
shifts = [random.gauss(0, sd) for sd in sigmas]
newvals = [(x + y) for x, y in zip(vals, shifts)]
return newvals | 5,597 |
def compute_encrypted_request_hash(caller):
"""
This function will compute encrypted request Hash
:return: encrypted request hash
"""
first_string = get_parameter(caller.params_obj, "requesterNonce") or ""
worker_order_id = get_parameter(caller.params_obj, "workOrderId") or ""
worker_id = ge... | 5,598 |
def test_num_samples(res_surf):
""" Verify dimension value."""
assert res_surf.num_samples == 47 | 5,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.