content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def maybe_copy(arr):
"""Decide if we should make a copy of an array in order to release memory.
NumPy arrays may be views into other array objects, by which a small array can
maintain a persistent pointer to a large block of memory that prevents it from
being garbage collected. This can quickly lead to memory ... | 59,500 |
def bmeow_to_bio(tags: List[str]) -> List[str]:
"""Convert BMEOW tags to the BIO format.
Args:
tags: The BMEOW tags we are converting
Raises:
ValueError: If there were errors in the BMEOW formatting of the input.
Returns:
Tags that produce the same spans in the BIO format.
... | 59,501 |
def clear_grid(grid):
"""
Resets the grid for each new instance of Randomise.
"""
for house in grid.houses.values():
house.set_init()
for battery in grid.batteries.values():
battery.set_init() | 59,502 |
def test_save_large_object(tmp_path: Path):
"""Check that the object are properly store."""
name, path_str = save_numpy_data(tmp_path)
prop_data = {"collection_name": CONTAINER,
"large_objects": {name: path_str}}
swift = SwiftAction()
swift.upload(prop_data)
output = next(swift... | 59,503 |
def signature(word: str) -> str:
"""Return a word sorted
>>> signature("test")
'estt'
>>> signature("this is a test")
' aehiisssttt'
>>> signature("finaltest")
'aefilnstt'
"""
return "".join(sorted(word)) | 59,504 |
def decision_tree(tree, inputs, method="predict", value_transform=None):
"""
Creates a SKAST expression corresponding to a given SKLearn Tree object.
Kwargs:
inputs: a list of AST nodes to be used as inputs to the model.
method: 'predict' (for classifier and regressor models),
... | 59,505 |
def weight_check():
"""
make sure the weighted values add up to 100% of home cost
"""
if sum(HOMES_ATTRIBUTES_WEIGHTED_VALUES.values()) < 0.9999999999:
print("Miscalculation of weights")
exit(1) | 59,506 |
def plot_spark_error(xdat,ydat, error, filename='plot.eps', save=True, show=False, color='#47d147'):
"""Generic plotting function for (multiple) xy datasets.
Based on matplotlib spark_line function defined here:
https://markhneedham.com/blog/2017/09/23/python-3-create-sparklines-using-matplotlib/
Args:
... | 59,507 |
def get_object(bucket: str, key: str) -> bytes:
"""Gets the object at key in the passed bucket
Wraps the Acquire get_object function
Args:
bucket: Bucket containing data
key: Key for data in bucket
Returns:
bytes: Object from store
"""
return ObjectStore.get_object(buck... | 59,508 |
def get_radius(box, element, dr, n=1, ratio=0.5):
"""Get the radius of a bubble.
Radius is determined to be r with closest value of n_element / n_atoms
to ratio, i.e. within radius, n_element / n_atoms should be as close to
ratio as possible.
n specifies number of radiuses to return, i.e. n radiuses... | 59,509 |
def _get_extra_price_id(items, key_name, hourly, location):
"""Returns a price id attached to item with the given key_name."""
for item in items:
if not utils.lookup(item, 'keyName') == key_name:
continue
for price in item['prices']:
if not _matches_billing(price, hourl... | 59,510 |
def test_validate_generator():
"""Test that generator replacement for validation in config doesn't
actually replace the returned value."""
@my_registry.schedules("test_schedule.v2")
def test_schedule():
while True:
yield 10
cfg = {"@schedules": "test_schedule.v2"}
result = ... | 59,511 |
def plot_det_label(image, anno, labels):
""" 目标检测类型生成标注图
Args:
image: 图片路径
anno: 图片标注
labels: 图片所属数据集的类别信息
"""
catid2color = {}
img = cv2.imread(image)
img, scale_value = resize_img(img)
tree = ET.parse(anno)
objs = tree.findall('object')
color_map = get_colo... | 59,512 |
def getHeaders(lst, filterOne, filterTwo):
"""
Find indexes of desired values.
Gets a list and finds index for values which exist either in filter one or filter two.
Parameters:
lst (list): Main list which includes the values.
filterOne (list): A list containing values to find indexes of in the main list... | 59,513 |
def get_binary_clf_scores(y_true, y_pred, y_score=None,
sample_weight=None, level=1):
"""
Scores a binary classifiers.
Parameters
----------
y_true: array-like, (n_samples, )
The ground truth labels.
y_pred: array-like, (n_samples, )
The predicted labe... | 59,514 |
def historylog_with_tab(historylog, mocker, monkeypatch):
"""Return a fixture for a history log with one tab.
The base history log is a plugin widget. Within the plugin widget,
the method add_history creates a tab containing a code editor
for each history file. This fixture creates a history log with... | 59,515 |
def mail_staffs(subject, message, fail_silently=False, connection=None, html_message=None):
"""Overwrite of Django mail_staffs()"""
msg = EmailMultiAlternatives(
subject,
message,
DEFAULT_FROM_EMAIL,
ast.literal_eval(config.STAFFS_EMAIL),
connection=connection,
re... | 59,516 |
def get_audio_uris(uri):
"""
Fetches HTML of a File page and returns an array of URIs to the audio files on that page
:param uri: URI to a File page full of audio players
:return: A list of dictionaries with the date, index, and URI of audio files
"""
page_response = web_get(ur... | 59,517 |
async def main():
"""
Async Main Entry
"""
#
# Make sure we have set WECHATY_PUPPET_SERVICE_TOKEN in the environment variables.
# Learn more about services (and TOKEN) from https://wechaty.js.org/docs/puppet-services/
#
# It is highly recommanded to use token like [paimon] and [wxwork].
... | 59,518 |
def test_Peaks2MapsKernel(testdata_cbma, tmp_path_factory):
"""Test Peaks2MapsKernel."""
tmpdir = tmp_path_factory.mktemp("test_Peaks2MapsKernel")
model_dir = extract.download_peaks2maps_model()
testdata_cbma.update_path(tmpdir)
kern = kernel.Peaks2MapsKernel(model_dir=model_dir)
# MA map gene... | 59,519 |
def overlap_compress(X, n_components, window_size):
"""
Overlap (at 50% of window_size) and compress X.
Parameters
----------
X : ndarray, shape=(n_samples,)
Input signal to compress
n_components : int
number of DCT components to keep
window_size : int
Size of wind... | 59,520 |
def get_total_count(query):
"""Get count of all objects in the query."""
with benchmark("Apply limit: apply_limit > query_count"):
# Note: using func.count() as query.count() is generating additional
# subquery
# query.count() has a bug and it returns incorrect number of objects
count_q = query.stat... | 59,521 |
def lcsubstrings(seq1, seq2, positions=False):
"""Find the longest common substring(s) in the sequences `seq1` and `seq2`.
If positions evaluates to `True` only their positions will be returned,
together with their length, in a tuple:
(length, [(start pos in seq1, start pos in seq2)..])
Otherwise, the subst... | 59,522 |
def n_max_numbers(in_iter, n=2):
"""Get N maximal numbers from iter.
>>> n_max_numbers([])
[]
>>> n_max_numbers([1, 2, 3])
[2, 3]
>>> n_max_numbers([4, 2, 3])
[3, 4]
>>> n_max_numbers([1, 2, -1, 0], 3)
[0, 1, 2]
"""
max_numbers = list()
for number in in_iter:
... | 59,523 |
def main(logger, args):
"""
Main function
Args:
logger: logger object
args: arguments from command line
Returns:
None
"""
# variables
train_data_path = args.train_data_path
output_data_path = args.out_process_path
logger.info('initializing data preprocessing.... | 59,524 |
def test_missing_render_dependency(arca_model, content_repo, git_command):
"""Missing naucse_render dependency gives actionable error message"""
# Remove Pipfile & lock
run([git_command, 'rm', 'Pipfile'], cwd=content_repo)
run([git_command, 'rm', 'Pipfile.lock'], cwd=content_repo)
# Instead, add r... | 59,525 |
def _check_status(task):
"""Check inspection status for node given by a task."""
node = task.node
if node.provision_state != states.INSPECTING:
return
if not isinstance(task.driver.inspect, DiscoverdInspect):
return
LOG.debug('Calling to discoverd to check status of node %s',
... | 59,526 |
def unittest_discover():
"""Explicit test suite creation"""
if sys.hexversion >= 0x3000000:
from pybitmessage import pathmagic
pathmagic.setup()
loader = unittest.defaultTestLoader
# randomize the order of tests in test cases
loader.sortTestMethodsUsing = lambda a, b: random.randint(... | 59,527 |
def Scatter(xs, ys=None, **options):
"""Makes a scatter plot.
xs: x values
ys: y values
options: options passed to plt.scatter
"""
options = _Underride(options, color='blue', alpha=0.2,
s=30, edgecolors='none')
if ys is None and isinstance(xs, pd.Series):
y... | 59,528 |
def weather_data(
latitude: float, longitude: float, date_: date, weather_stations: pd.DataFrame
):
"""
Get weather data for given location and date using the closest weather station
Args:
latitude (float): Latitude
longitude (float): Longitude
date_ (date): Date
weather... | 59,529 |
def separate_words(text, min_word_return_size):
"""
Utility function to return a list of all words that are have a length greater than a specified number of characters.
@param text The text that must be split in to words.
@param min_word_return_size The minimum no of characters a word must have to be in... | 59,530 |
async def test_get_user(http_service: Any, token: MockFixture) -> None:
"""Should return OK and an user as json."""
url = f"{http_service}/users"
headers = {
hdrs.AUTHORIZATION: f"Bearer {token}",
}
async with ClientSession() as session:
async with session.get(url, headers=headers)... | 59,531 |
def LogControl(control: Control, depth: int = 0, showAllName: bool = True) -> None:
"""
Print and log control's properties.
control: `Control` or its subclass.
depth: int, current depth.
showAllName: bool, if False, print the first 30 characters of control.Name.
"""
def getKeyName(theDict, t... | 59,532 |
def test_exp_slow():
"""
Tests the slow version of exponentiation
"""
# Count the number of call frames
print('Testing exp_slow')
exp.count_frames = 0
introcs.assert_floats_equal(1.0, exp.exp_slow(2, 0))
introcs.assert_floats_equal(2.0, exp.exp_slow(2, 1))
introcs.assert_floa... | 59,533 |
def adjust_learning_rate(optimizer, epoch):
"""Sets the learning rate to the initial LR decayed by 10 every args.lr_drop epochs"""
lr = args.lr * (0.1 ** (epoch // args.lr_drop))
print('lr= '+str(lr), flush=True)
for param_group in optimizer.param_groups:
param_group['lr'] = lr | 59,534 |
def getSelectedObjectChannels(oSel=None, userDefine=False, animatable=False):
"""Get the selected object channels.
Arguments:
oSel (None, optional): The pynode with channels to get
userDefine (bool, optional): If True, will return only the user
defined channels. Other channels will... | 59,535 |
def admin_urlify(column, help_text=None): # pragma: no cover
"""
Can be used to add a link to a model referenced in another admin.
Example:
fields = [admin_urlify("user")]
"""
def inner(*args):
if len(args) > 1:
obj = args[1]
else:
obj = args[0]
_obj = getattr(obj, column)
if _obj is None:
ret... | 59,536 |
def getMS(start, stop):
"""
Get time difference in milliseconds
"""
diff = stop - start
return getMSDiff(diff) | 59,537 |
def compiles():
"""uniform.py produces correct answer."""
check50.run("python uniform.py {}".format(seed)).stdout(str(sol)+'\n').exit() | 59,538 |
def allowedExperiments(reagents, maxConcentration, minConcentration=None):
""" Find the allowed ConvexHull given the reagent definitions and max/min concentration.
Note that, relative to the Mathematica code, the location of max and min concentration in the function arguments are swapped. This allows for the ... | 59,539 |
def basicauth_dump_request_endpoint(request):
"""
Dump a HttpRequest to files in a directory.
"""
uname, passwd, user = _basicauth(request)
print(uname, passwd, user)
if user is None:
# Either they did not provide an authorization header or
# something in the authorization attem... | 59,540 |
def load_metadata(paths, quiet=False):
"""
--> makes hashtable -> filepath : fcs file class instance
meta_keys == all_keys w any new keys extended
replaced -> meta_keys = ['FILEPATH'] with 'SRC_FILE'
Arg:
paths: iterable of fcs filepaths
Returns:
fcs_objs:
m... | 59,541 |
def test_laplacian_kernel(sample_dim, num_samples, gamma):
"""Tests specific for Laplacian kernel."""
laplacian = LaplacianKernel(gamma=gamma, skip_input_checks=False)
_test_for_all_kernels(laplacian, sample_dim)
_test_func_is_valid_kernel(laplacian, sample_dim, num_samples) | 59,542 |
def combine_args_kwargs(
func: Callable[..., Any], *args: Any, **kwargs: Any
) -> Tuple[Any, ...]:
"""
Combine args and kwargs into args.
This is needed because we allow users to pass custom kwargs to adapters,
but when creating the virtual table we serialize only args.
"""
signature = insp... | 59,543 |
def get_tensor_backend(tensor):
"""
Determine the tensor backend for a given tensor.
Args:
tensor: A tensor type of any of the supported backends.
Return:
The backend class which providing the interface to the tensor library
corresponding to ``tensor``.
Raises:
:py... | 59,544 |
def generate_primes_up_to(max_prime):
"""Generates an array of prime numbers up to @max_prime"""
primes = [2, 3]
i = 4
while i < max_prime:
prime = True
for divisor in xrange(2, int(math.sqrt(i)) + 1):
if i % divisor == 0:
prime = False
break
if prime is True:
primes.append(i)
i += 1
retu... | 59,545 |
def _print_list_modules(mode: str, include_parent: bool = False):
"""Prints certain properties of cirq modules on separate lines.
Module root folder and top level package paths are supported. The search dir is the current
directory.
Args:
mode: 'folder' lists the root folder for each module, '... | 59,546 |
def _plot2D(self, funcname, *args, **kwargs):
""" generic plotting function for 2-D plots
"""
if len(self.dims) != 2:
raise NotImplementedError(funcname+" can only be called on two-dimensional dimarrays.")
import matplotlib.pyplot as plt
#ax = plt.gca()
if 'ax' in kwargs:
... | 59,547 |
def _get_from_members_items_or_properties(obj, key):
"""TODO_Sphinx."""
try:
if hasattr(obj, key):
return obj.id
if hasattr(obj, 'properties') and key in obj.properties:
return obj.properties[key]
except (KeyError, TypeError, AttributeError): pass
try:
... | 59,548 |
def get_package_list_arch(repo, arch):
"""Return all packages in a repository with given architecture."""
filters = _filters_from_args(request.args)
filters['repo'] = repo
filters['arch'] = arch
pkgs = pkgdb.find(**filters)
_json = list(map(_json_from_pkg, pkgs))
return json.dumps(_json) | 59,549 |
def h(k, n, td, tb, tau):
"""Term in Eq. 35 in Zhang+95."""
# Typo in Zhang+95 corrected. k * tb, not k * td
if k * tb < n * td:
return 0
return (k - n*(td + tau) / tb +
tau / tb * Gn((k * tb - n * td)/tau, n)) | 59,550 |
def settings():
"""Expose app settings in tests."""
print('Loading test settings...')
previous = os.environ.get('SETTINGS_MODULE', None)
os.environ['SETTINGS_MODULE'] = 'settings.testing'
yield load_settings()
if previous:
print('Unsetting test settings...')
os.environ['SETTING... | 59,551 |
def definers (ioc, name) :
"""Return the classes defining `name` in `mro` of `ioc`"""
try :
mro = ioc.__mro__
except AttributeError :
mro = ioc.__class__.__mro__
def _gen (mro, name) :
for c in mro :
v = c.__dict__.get (name)
if v is not None :
... | 59,552 |
def interact(experiment: str) -> None:
"""Interactive mode command where we can have a conversation with a trained model
that impersonates a Vegan that likes cooking and radical activities such as sky-diving.
"""
model = EmotionTransformer.from_experiment(experiment)
while 1:
print("Please w... | 59,553 |
def dict_to_yaml_snippet (dictionary, indent = ' ', level = 2, newline = '\n'):
"""Convert a dataframe Dictionary to a formated yaml snippet
Parameters
----------
dictionary : dict
dictionary with keys INDEX, ORDER, and the values of INDEX and ORDER
indent : str, optional
level : int ,... | 59,554 |
def write_implicational(path, implicational, implicational_prior):
"""Writes implicational associations to a file."""
with open(path, "w") as stream:
# Write out for max value
#
# Feature1
# Value1
# Feature2
# Value2
# Probabilty of Value2 given Feature1, Value1 and Feature2
# Total... | 59,555 |
def test_get_waiter_args_servicename_empty():
"""Empty serviceName raises."""
context = Context({
'k1': 'v1',
'awsWaitIn': {
'serviceName': '',
'waiterName': 'method_name',
'arbKey': 'arb_value'
}})
with pytest.raises(KeyInContextHasNoValueError) ... | 59,556 |
def test_atomic_g_year_min_exclusive_2_nistxml_sv_iv_atomic_g_year_min_exclusive_3_1(mode, save_output, output_format):
"""
Type atomic/gYear is restricted by facet minExclusive with value 2025.
"""
assert_bindings(
schema="nistData/atomic/gYear/Schema+Instance/NISTSchema-SV-IV-atomic-gYear-minE... | 59,557 |
def datetime_display_renderer(widget, data, value=None):
"""Note: This renderer function optionally accepts value as parameter,
which is used in favor of data.value if defined. Thus it can be used as
utility function inside custom blueprints with the need of datetime
display rendering.
"""
value... | 59,558 |
def get_bbc_dataset():
"""Extract a return the train and test data for the bbc corpus."""
dataset = pd.read_csv('bbc_dataset.csv', index_col=0)
dataset_train = dataset[dataset.set == 'train']
dataset_test = dataset[dataset.set == 'test']
X_train = dataset_train[['Utterance']]
y_train = dataset_... | 59,559 |
def get_course_url(course_id, course_json, platform):
"""
Get the url for a course if any
Args:
course_id (str): The course_id of the course
course_json (dict): The raw json for the course
platform (str): The platform (mitx or ocw)
Returns:
str: The url for the course i... | 59,560 |
def load_model(helper: PredictHelper, config: PredictionConfig, path_to_model_weights: str) -> Any:
""" Loads model with desired weights. """
return ConstantVelocityHeading(config.seconds, helper) | 59,561 |
def create_supervised_trainer(
model: torch.nn.Module,
optimizer: torch.optim.Optimizer,
loss_fn: Union[Callable, torch.nn.Module],
device: Optional[Union[str, torch.device]] = None,
non_blocking: bool = False,
prepare_batch: Callable = _prepare_batch,
output_transform: Callable[[Any, Any, A... | 59,562 |
def bootstrap(packages):
"""Validates the presence of $IMPALA_HOME and $IMPALA_TOOLCHAIN in the environment. By
checking $IMPALA_HOME is present, we assume that IMPALA_{LIB}_VERSION will be present as
well. Will create the directory specified by $IMPALA_TOOLCHAIN if it does not yet
exist. Each of the packages s... | 59,563 |
def add_dest(df_conc, dest_labware, dest_start=1):
"""Setting destination locations for samples & primers.
Adding to df_conc:
[dest_labware, dest_location]
"""
dest_start= int(dest_start)
#try:
# dest_labware = dest_labware_index[dest_type]
#except KeyError:
# raise KeyError(... | 59,564 |
def load_ratings_data(path_data='ratings.csv'):
"""
Returns a list of triples (a, i, r)
"""
data = []
with open(path_data) as f_data:
for line in f_data:
(uid, iid, rating, timestamp) = line.strip().split(",")
data.append([int(uid), int(iid), float(rating)])
prin... | 59,565 |
def image_has_any_human_annotations(image):
"""
Return True if the image has at least one human-made Annotation.
Return False otherwise.
"""
human_annotations = Annotation.objects.filter(image=image).exclude(user=get_robot_user()).exclude(user=get_alleviate_user())
return human_annotations.count... | 59,566 |
def build_fix_from_line(line: Dict) -> GpsFix:
"""
Builds a GpsFix parsing the specified line
:param line: The line to parse
:return: A GpsFix object
"""
date = datetime.strptime(line["timestamp"], '%Y-%m-%d %H:%M:%S')
latitude = float(line["latitude"])
longitude = float(line["longitude"... | 59,567 |
def top(Q):
"""Inspects the top of the queue"""
if Q:
return Q[0]
raise ValueError('PLF ERROR: empty queue') | 59,568 |
def get_valid_handles_domain_only():
"""
Define valid domain handles
"""
return ["cli", "web", "gui", "pub"] | 59,569 |
def gen_3d_fs_plot(mesh,rvec,ham_r,ndegen,mu,avec,BZ_faces,surface_opt=0):
"""
This function plot 3D Fermi Surface
argument:
mesh: k-grid mesh size
rvec,ham_r,ndegen: model hamiltonian
mu: chemical potential
surface_opt: switch of surface color 1:orbital weights, 2:size of velocities
"""... | 59,570 |
def printInfoTable(status, options):
""" prints the Information table.
"""
if options.isHtml:
if 'isDone' not in status.variables:
print '<form name="Reload">'
print('<input type="checkbox" name="checkboxReload" onclick="StartTime()" checked="checked">'
'Aut... | 59,571 |
def test_left_stop_1(g, v):
"""
Test left stops with adornment.
"""
stop = left_stop(g)
assert stop == v | 59,572 |
def qc_board_and_constraints(board, constraints):
"""
Purpose: When the board first comes in, do a check to see if any of the
fixed values are duplicates
@param board The Sudoku board: A list of lists of variable class instances
@param constraints The unallowed values for each cell, list of tuples... | 59,573 |
def spdot(A, x):
""" Dot product of sparse matrix A and dense matrix x (Ax = b) """
return A.dot(x) | 59,574 |
def main():
"""Outputs URLs one by one as they appear on the Hive Podping stream"""
allowed_accounts = get_allowed_accounts()
hive = beem.Hive()
blockchain = Blockchain(mode="head", blockchain_instance=hive)
# If you want instant confirmation, you need to instantiate
# class:beem.blockchain.Bloc... | 59,575 |
def plot_errors(errors, lambda_=0.99):
"""
Plots a moving average and histogram of np array errors
"""
num_vals = int(errors.shape[0]/50)
error_avg = [np.mean((errors*errors)[i-num_vals:i]) for i in range(num_vals,errors.shape[0]-2)]
fig,ax = plt.subplots(2)
fig.suptitle("RLS with forgetting factor="+str(lam... | 59,576 |
def test_non_quoted_attribute_name_following_value():
"""
Make sure to test an attribute name with a following non-quoted value that is not empty.
"""
# Arrange
input_tag_name = "<meta http:equiv=abc>"
start_index = 16
expected_resultant_index = 20
# Act
actual_resultant_index = Ht... | 59,577 |
def set_figure_positions(lista):
"""Flytta ett antal figurer till angivna positioner
*lista*
[(fig1, (x1, y1)), (fig2, (x2, y2)), ...]
"""
for (i, (x, y)) in lista:
move_fig(Gcf.figs[i], x, y) | 59,578 |
def normalize(environ: OsEnvironLike = None):
"""Normalize the environment variables which set the app ID."""
put(get(environ=environ), environ=environ) | 59,579 |
def ecef2eci(R_ECEF,time):
"""
# Function to compute rotation matrix from ECEF to ECI (simple model)
# Formulas taken from the US Naval Observatory
"""
#
# T is the Julian Date in julian centuries
#
d = time - 2451545.0;
T = d/ 36525;
#
# Compute Greenwich Mean s... | 59,580 |
def get_months(year: str) -> list[str]:
"""Make all Prompts dates for a given year into a unique set.
For some months in 2017, November 2020, and in 2021 and beyond,
there are multiple Hosts per month giving out the prompts.
While the individual dates are stored distinctly,
we need a unique month l... | 59,581 |
def translate_user(user):
""" translates trac user to pivotal user
"""
return user | 59,582 |
def _clean_int(value, default):
"""Convert a value to an int, or the default value if conversion fails."""
try:
return int(value)
except (TypeError, ValueError), _:
return default | 59,583 |
def pitch_stream_to_text(pitch_stream, file_name='corpus.txt', append=True):
"""Converts pitch stream to word file for further analysis
One word consists of 4 instruments
:param pitch_stream: list of pitches | 4 pitch stream list
:param file_name: name of file in which to save the data
:param a... | 59,584 |
def get_target_imagepath(image_path,category_num):
"""
category:
0-userid,
1-isbad,
2-gender: 1 male,0 female,
3-age
"""
basename=os.path.basename(image_path).split(".")[0].split("_")
an=int(basename[category_num])
return an | 59,585 |
def wait_for_first(ds):
""" Returns a deferred that is callbacked/errbacked with whatever deferred in `ds` fires first. """
d = defer.DeferredList(ds, fireOnOneCallback=True, fireOnOneErrback=True, consumeErrors=True)
d.addCallback(operator.itemgetter(0))
d.addErrback(get_maybe_first_error_failure)
... | 59,586 |
def offline_analysis(data_folder: str = None,
parameters: dict = {}, alert_finished: bool = True):
""" Gets calibration data and trains the model in an offline fashion.
pickle dumps the model into a .pkl folder
Args:
data_folder(str): folder of the data
... | 59,587 |
def main():
"""Read file,
get time,
check if in flare list."""
# First read observations
# format: YYYY mm dd start_HHMM peak_HHMM end_HHMM flare_class ARNo
obs = open(flare_file, 'r').readlines()
m_obs = []
x_obs = []
# separate the M and X flares
for line in obs:
... | 59,588 |
def filterSignal(mriSignal, acqTime, timePhysioRegrid, valuesPhysioRegrid, cardiacPeriod, freqDetection='temporal'):
"""
Define function to apply last 2 steps (breathing frequencies filtering and final smoothing) in one single call
:param mriSignal:
:param acqTime:
:param timePhysioRegrid:
:pa... | 59,589 |
def write_string(val: str) -> bytes:
"""Returns the OSC string equivalent of the given python string.
Raises:
- BuildError if the string could not be encoded.
"""
try:
dgram = val.encode('utf-8') # Default, but better be explicit.
except (UnicodeEncodeError, AttributeError) as e:
... | 59,590 |
def split_in_columns(message=message):
"""Split the message by newline (\n) and join it together on '|'
(pipe), return the obtained output"""
pipe = "|"
message_split = message.split("\n")
message_join = pipe.join(message_split)
return message_join | 59,591 |
def cli():
"""NPAnalyst CLI entrypoint"""
click.echo("Welcome to NPAnalyst!") | 59,592 |
def test_roundtrip(tmpdir, ref_data_dir):
"""A simple check that file written can be read back in.
Currently this does not do anything besides ensure there are no failures.
Reading could fail, for example, if the extension spec is not included
in the NWB file by accident.
"""
# Write one of the... | 59,593 |
def test_port_getter(port_getter):
"""Test port getter utility."""
port1 = port_getter()
sock1 = socket.socket(socket.AF_INET)
sock1.bind(('127.0.0.1', port1))
assert port1
port2 = port_getter()
sock2 = socket.socket(socket.AF_INET)
sock2.bind(('127.0.0.1', port2))
assert port2
a... | 59,594 |
def detail(container: str):
"""
Inspect a container on Azure Blob Storage
"""
# Get container info
container_client = service_client.get_container_client(
container=container)
container = container_client.get_container_properties()
# Get the blobs inside this container
blobs =... | 59,595 |
def sync_cp_dump(server, args_array, **kwargs):
"""Function: sync_cp_dump
Description: Locks the database and then copies the database files to a
destination directory.
Arguments:
(input) server -> Database server instance.
(input) args_array -> Array of command line options and... | 59,596 |
def create_image (width, height, color='white'):
"""
Creates an empty image.
:param width: image width
:param height: image height
:param color: background color
:return: the image
"""
image = PIL.Image.new("RGBA", (width, height), color)
return image | 59,597 |
def convert_image_resize1d(attrs, inputs, tinfos, desired_layouts):
"""Convert Layout pass registration for image resize1d op.
Parameters
----------
attrs : tvm.ir.Attrs
Attributes of current resize op
inputs : list of tvm.relay.Expr
The args of the Relay expr to be legalized
ti... | 59,598 |
def analog_uxg_lan_stream_pdw_example(ipAddress):
"""Defines a pdw file for a chirp, and loads the
pdw file into the UXG, and plays it out."""
# Create analog UXG object
uxg = pyarbtools.instruments.AnalogUXG(ipAddress, port=5025, timeout=10, reset=False)
# UXG configuration variables
output =... | 59,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.