content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def play_image_stack(array_tiff):
"""
Display tiff image stack as a looping video.
Keyword arguments:
array_tiff -- multidimensional array of tiff images
"""
fig = plt.figure()
images = []
# Loop through each slice of 3D array, animate and store in list
for frame in range... | 5,357,200 |
def _ser_batch_ixs(num_samples, batch_size):
"""A generator which yields a list of tuples (offset, size) in serial order.
:param num_samples: Number of available samples.
:param batch_size: The size of the batch to fill.
"""
current_index = 0
batch, batch_count = [], 0
while True:
... | 5,357,201 |
def cal_sort_key( cal ):
"""
Sort key for the list of calendars: primary calendar first,
then other selected calendars, then unselected calendars.
(" " sorts before "X", and tuples are compared piecewise)
"""
if cal["selected"]:
selected_key = " "
else:
selected_key = "X"
... | 5,357,202 |
def select_zip_info(sample: bytes) -> tuple:
"""Print a list of items contained within the ZIP file, along with
their last modified times, CRC32 checksums, and file sizes. Return
info on the item selected by the user as a tuple.
"""
t = []
w = 0
z = ZipFile(sample)
for i in z.infolist(... | 5,357,203 |
def create_ionosphere_layers(base_name, fp_id, requested_timestamp):
"""
Create a layers profile.
:param None: determined from :obj:`request.args`
:return: array
:rtype: array
"""
function_str = 'ionoshere_backend.py :: create_ionosphere_layers'
trace = 'none'
fail_msg = 'none'
... | 5,357,204 |
def unitary_ifft2(y):
"""
A unitary version of the ifft2.
"""
return np.fft.ifft2(y)*np.sqrt(ni*nj) | 5,357,205 |
def orb_scf_input(sdmc):
""" find the scf inputs used to generate sdmc """
myinputs = None # this is the goal
sdep = 'dependencies' # string representation of the dependencies entry
# step 1: find the p2q simulation id
p2q_id = None
for key in sdmc[sdep].keys():
if sdmc[sdep][key].result_names[0] == 'o... | 5,357,206 |
def is_success(code):
""" Returns the expected response codes for HTTP GET requests
:param code: HTTP response codes
:type code: int
"""
if (200 <= code < 300) or code in [404, 500]:
return True
return False | 5,357,207 |
def create_hdf5(
bigwig_paths, chrom_sizes_path, out_path, chunk_size, batch_size=100
):
"""
Creates an HDF5 file containing all BigWig tracks.
Arguments:
`bigwig_paths`: a list of pairs of paths, as returned by
`fetch_bigwig_paths`
`chrom_sizes_path`: path to canonical chrom... | 5,357,208 |
async def asyncio(
*,
client: AuthenticatedClient,
json_body: SearchEventIn,
) -> Optional[Union[ErrorResponse, SearchEventOut]]:
"""Search Event
Dado um Trecho, uma lista de Grupos que resultam da pesquisa
por esse Trecho e um price token, atualiza os preços dos Grupos e o token.
Contabil... | 5,357,209 |
def get_symmtrafo(newstruct_sub):
"""???
Parameters
----------
newstruct_sub : pymatgen structure
pymatgen structure of the bulk material
Returns
-------
trafo : ???
???
"""
sg = SpacegroupAnalyzer(newstruct_sub)
trr = sg.get_symmetry_dataset()
trafo = []
... | 5,357,210 |
def convert_sentence_into_byte_sequence(words, tags, space_idx=32, other='O'):
""" Convert a list of words and their tags into a sequence of bytes, and
the corresponding tag of each byte.
"""
byte_list = []
tag_list = []
for word_index, (word, tag) in enumerate(zip(words, tags)):
tag_ty... | 5,357,211 |
def corr_cov(data, sample, xdata, xlabel='x', plabels=None, interpolation=None,
fname=None):
"""Correlation and covariance matrices.
Compute the covariance regarding YY and XY as well as the correlation
regarding YY.
:param array_like data: function evaluations (n_samples, n_features).
... | 5,357,212 |
def get_number_rows(ai_settings, ship_height, alien_height):
"""Determina o numero de linhas com alienigenas que cabem na tela."""
available_space_y = (ai_settings.screen_height -
(3 * alien_height) - ship_height)
number_rows = int(available_space_y / (2 * alien_height))
return ... | 5,357,213 |
def generate_trial_betas(bc, bh, bcrange, bhrange, step_multiplier, random_state_debug_value=None):
"""Generate trial beta values for an MC move. Move sizes are scaled by the 'step_multiplier' argument,
and individually by the 'bcrange' or 'bhrange' arguments for the beta_c and beta_h values respectively.
... | 5,357,214 |
def map_ref_sites(routed: xr.Dataset, gauge_reference: xr.Dataset,
gauge_sites=None, route_var='IRFroutedRunoff',
fill_method='r2', min_kge=-0.41):
"""
Assigns segs within routed boolean 'is_gauge' "identifiers" and
what each seg's upstream and downstream reference se... | 5,357,215 |
def get_error(est_track, true_track):
"""
"""
if est_track.ndim > 1:
true_track = true_track.reshape((true_track.shape[0],1))
error = np.recarray(shape=est_track.shape,
dtype=[('position', float),
('orientation', float),
... | 5,357,216 |
def test_conflict():
"""
Tiles that have extras that conflict with indices should produce an error.
"""
def tile_extras_provider(hyb: int, ch: int, z: int) -> Any:
return {
Indices.HYB: hyb,
Indices.CH: ch,
Indices.Z: z,
}
stack = synthetic_stack(... | 5,357,217 |
def get_node_to_srn_mapping(match_config_filename):
"""
Returns the node-to-srn map from match_conf.json
"""
with open(match_config_filename) as config_file:
config_json = json.loads(config_file.read())
if "node_to_srn_mapping" in config_json:
return config_json["node_to_s... | 5,357,218 |
def write_cache(cache: Cache, sources: Iterable[Path], mode: Mode) -> None:
"""Update the cache file."""
cache_file = get_cache_file(mode)
try:
CACHE_DIR.mkdir(parents=True, exist_ok=True)
new_cache = {**cache, **{src.resolve(): get_cache_info(src) for src in sources}}
with tempfile.... | 5,357,219 |
def interpolate(values, color_map=None, dtype=np.uint8):
"""
Given a 1D list of values, return interpolated colors
for the range.
Parameters
---------------
values : (n, ) float
Values to be interpolated over
color_map : None, or str
Key to a colormap contained in:
matplot... | 5,357,220 |
def nest_dictionary(flat_dict, separator):
""" Nests a given flat dictionary.
Nested keys are created by splitting given keys around the `separator`.
"""
nested_dict = {}
for key, val in flat_dict.items():
split_key = key.split(separator)
act_dict = nested_dict
final_key = ... | 5,357,221 |
def test_normal_df(test_dataframe, expected_test_return):
"""
Test.
"""
pd.testing.assert_frame_equal(sample_row(test_dataframe), expected_test_return) | 5,357,222 |
def test_classifier_gait_example():
"""Verify that the gait classifier can be packaged and used."""
perform_capsule_tests(
Path("vcap", "examples", "classifier_gait_example"),
ALL_IMAGE_PATHS) | 5,357,223 |
def write(path_, *write_):
"""Overwrites file with passed data. Data can be a string, number or boolean type. Returns True, None if writing operation was successful, False and reason message otherwise."""
return _writeOrAppend(False, path_, *write_) | 5,357,224 |
def annotate(wsdjar: Binary = Binary("[wsd.jar]"),
sense_model: Model = Model("[wsd.sense_model]"),
context_model: Model = Model("[wsd.context_model]"),
out: Output = Output("<token>:wsd.sense", cls="token:sense",
description="Sense disambiguated ... | 5,357,225 |
def get_all(url):
"""A wrapper for `get_many()`: a generator getting and iterating through all results"""
data = get_many(url, limit=50)
yield from data['data']
while 'paging' in data and 'next' in data['paging']:
data = get_many(data['paging']['next'])
yield from data['data'] | 5,357,226 |
def prepare_saab_data(sequence):
"""
Processing data after anarci parsing.
Preparing data for SAAB+
------------
Parameters
sequence - sequence object ( OAS database format )
------------
Return
sequence.Sequence - full (not-numbered) antibody sequence
oas_o... | 5,357,227 |
def covariance_align(data):
"""Covariance align continuous or windowed data in-place.
Parameters
----------
data: np.ndarray (n_channels, n_times) or (n_windows, n_channels, n_times)
continuous or windowed signal
Returns
-------
aligned: np.ndarray (n_channels x n_times) or (n_wind... | 5,357,228 |
def test_scope_dunder_methods(sample_scope_object):
"""Tests dunder methods for a scope object."""
assert repr(sample_scope_object) == "Scope(arg='kw', base='select')"
assert str(sample_scope_object) == "Scope(arg='kw', base='select', included=False)"
assert not bool(sample_scope_object) | 5,357,229 |
def test_theme_eq():
"""Test Theme.__eq__"""
theme1 = Theme(
name="test", description="Test theme", styles={"test": Style(color="red")}
)
theme2 = Theme(
name="test", description="Test theme", styles={"test": Style(color="red")}
)
assert theme1 == theme2
theme3 = Theme(
... | 5,357,230 |
def _is_equidistant(array: np.ndarray) -> bool:
"""
Check if the given 1D array is equidistant. E.g. the
distance between all elements of the array should be equal.
:param array: The array that should be equidistant
"""
step = abs(array[1] - array[0])
for i in range(0, len(array) - 1):
... | 5,357,231 |
def list_a_minus_b(list1, list2):
"""Given two lists, A and B, returns A-B."""
return filter(lambda x: x not in list2, list1) | 5,357,232 |
def is_equivalent(a, b):
"""Compares two strings and returns whether they are the same R code
This is unable to determine if a and b are different code, however. If this returns True you may assume that they
are the same, but if this returns False you must not assume that they are different.
i... | 5,357,233 |
def solve(lines, n):
"""Solve the problem."""
grid = Grid(lines)
for _ in range(n):
grid.step()
return grid.new_infections | 5,357,234 |
def get_ingredient_id():
"""Need to get ingredient ID in order to access all attributes"""
query = request.args["text"]
resp = requests.get(f"{BASE_URL_SP}/food/ingredients/search?", params={"apiKey":APP_KEY,"query":query})
res = resp.json()
lst = {res['results'][i]["name"]:res['results'][i]["id"] ... | 5,357,235 |
def xticks(ticks=None, labels=None, **kwargs):
"""
Get or set the current tick locations and labels of the x-axis.
Call signatures::
locs, labels = xticks() # Get locations and labels
xticks(ticks, [labels], **kwargs) # Set locations and labels
Parameters
----------
... | 5,357,236 |
def main() -> None:
"""
Program entry point.
:return: Nothing
"""
try:
connection = connect_to_db2()
kwargs = {'year_to_schedule': 2018}
start = timer()
result = run(connection, **kwargs)
output_results(result, connection)
end = timer()
print... | 5,357,237 |
def _generate_cfg_dir(cfg_dir: Path = None) -> Path:
"""Make sure there is a working directory.
Args:
cfg_dir: If cfg dir is None or does not exist then create sub-directory
in CFG['output_dir']
"""
if cfg_dir is None:
scratch_dir = CFG["output_dir"]
# TODO this time... | 5,357,238 |
def p_identifier_list_singleton(p: yacc.YaccProduction) -> yacc.YaccProduction:
"""
identifier_list : IDENTIFIER
"""
p[0] = [p[1]] | 5,357,239 |
def test_get_novelty_mask():
"""Test `get_novelty_mask()`."""
num_triples = 7
base = torch.arange(num_triples)
mapped_triples = torch.stack([base, base, 3 * base], dim=-1)
query_ids = torch.randperm(num_triples).numpy()[:num_triples // 2]
exp_novel = query_ids != 0
col = 2
other_col_ids ... | 5,357,240 |
def test_md041_good_heading_top_level_setext():
"""
Test to make sure this rule does not trigger with a document that
contains a good top level setext heading.
"""
# Arrange
scanner = MarkdownScanner()
supplied_arguments = [
"scan",
"test/resources/rules/md041/good_heading_t... | 5,357,241 |
def delete(home_id):
"""
Delete A About
---
"""
try:
return custom_response({"message":"deleted", "id":home_id}, 200)
except Exception as error:
return custom_response(str(error), 500) | 5,357,242 |
def round_to_sigfigs(x, sigfigs=1):
"""
>>> round_to_sigfigs(12345.6789, 7) # doctest: +ELLIPSIS
12345.68
>>> round_to_sigfigs(12345.6789, 1) # doctest: +ELLIPSIS
10000.0
>>> round_to_sigfigs(12345.6789, 0) # doctest: +ELLIPSIS
100000.0
>>> round_to_sigfigs(12345.6789, -1) # doctest:... | 5,357,243 |
def filter_netcdf(filename1, filename2, first=0, last=None, step=1):
"""Filter data file, selecting timesteps first:step:last.
Read netcdf filename1, pick timesteps first:step:last and save to
nettcdf file filename2
"""
from Scientific.IO.NetCDF import NetCDFFile
# Get NetCDF
infile =... | 5,357,244 |
def load_api_data (API_URL):
"""
Download data from API_URL
return: json
"""
#actual download
with urllib.request.urlopen(API_URL) as url:
api_data = json.loads(url.read().decode())
#testing data
##with open('nrw.json', 'r') as testing_set:
## api_data = json... | 5,357,245 |
def test_parsing(monkeypatch, capfd, configuration, expected_record_keys):
"""Verifies the feed is parsed as expected"""
def mock_get(*args, **kwargs):
return MockResponse()
test_tap: Tap = TapFeed(config=configuration)
monkeypatch.setattr(test_tap.streams["feed"]._requests_session, "send", mo... | 5,357,246 |
def hsl(h, s, l):
"""Converts an Hsl(h, s, l) triplet into a color."""
return Color.from_hsl(h, s, l) | 5,357,247 |
def factor(afunc):
"""decompose the string m.f or m.f(parms) and return function and parameter dictionaries
afunc has the form xxx or xxx(p1=value, p2=value,...)
create a dictionary from the parameters consisting of at least _first:True.
parameter must have the form name=value, name=value,...
"""
... | 5,357,248 |
def spline(xyz, s=3, k=2, nest=-1):
""" Generate B-splines as documented in
http://www.scipy.org/Cookbook/Interpolation
The scipy.interpolate packages wraps the netlib FITPACK routines
(Dierckx) for calculating smoothing splines for various kinds of
data and geometries. Although the data is evenly ... | 5,357,249 |
def inputs_def():
"""
# Date-x: str: dates of the sample (Date-0 is today and we aim to predict price action in the next 4 days)
# averageDailyVolume10Day: Average volume of the last 10 days. Notice that due to limitation of Yahoo, we could not
put the true average at Date-0. ... | 5,357,250 |
def plot_sample_imgs(get_imgs_fun, img_shape, plot_side=5, savepath=None, cmap='gray'):
"""
Generate visual samples and plot on a grid
:param get_imgs_fun: function that given a int return a corresponding number of generated samples
:param img_shape: shape of image to plot
:param plot_side: samples ... | 5,357,251 |
def download_image(path, image_url):
"""
图片下载
Parameters:
path - str 图片保存地址
image_url - str 图片下载地址
Returns:
None
"""
print(image_url)
filename = image_url.split('/')[-1]
image_path = os.path.join(path, filename)
download_headers = {'Accept': '*/*',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Lang... | 5,357,252 |
def main():
""" Entry point """
moves = "U D"
cube = Cube()
for move_string in moves.split():
move_to_make = CubeMove.parse(move_string)
cube.make_move(move_to_make)
print(cube) | 5,357,253 |
def load_supercomputers(log_file, train_ratio=0.5, windows_size=20, step_size=0, e_type='bert', mode="balance",
no_word_piece=0):
""" Load BGL, Thunderbird, and Spirit unstructured log into train and test data
Parameters
----------
log_file: str, the file path of raw log (extensi... | 5,357,254 |
def is_running(service: Service) -> bool:
"""Is the given pyodine daemon currently running?
:raises ValueError: Unknown `service`.
"""
try:
return bool(TASKS[service]) and not TASKS[service].done()
except KeyError:
raise ValueError("Unknown service type.") | 5,357,255 |
def test_is_not_positive_semidefinite():
"""Test that non-positive semidefinite matrix returns False."""
mat = np.array([[-1, -1], [-1, -1]])
np.testing.assert_equal(is_positive_semidefinite(mat), False) | 5,357,256 |
def PropertyWrapper(prop):
"""Wrapper for db.Property to make it look like a Django model Property"""
if isinstance(prop, db.Reference):
prop.rel = Relation(prop.reference_class)
else:
prop.rel = None
prop.serialize = True
return prop | 5,357,257 |
def plot_metric(
path_csv: str,
metric: str,
path_save: Optional[str] = None,
title: Optional[str] = None,
ymin: Optional[float] = None,
ymax: Optional[float] = None,
) -> None:
"""Plots box-plot of model performance according to some metric.
Parameters
----------
path_csv
... | 5,357,258 |
def drowLine(cord,orient,size):
"""
The function provides the coordinates of the line.
Arguments:
starting x or y coordinate of the line, orientation
(string. "vert" or "hor") and length of the line
Return:
list of two points (start and end of the line)
"""
glo... | 5,357,259 |
def bluetoothRead():
""" Returns the bluetooth address of the robot (if it has been previously stored)
arguments:
none
returns:
string - the bluetooth address of the robot, if it has been previously stored; None otherwise
"""
global EEPROM_BLUETOOTH_ADDRESS
... | 5,357,260 |
def is_step_done(client, step_name):
"""Query the trail status using the client and return True if step_name has completed.
Arguments:
client -- A TrailClient or similar object.
step_name -- The 'name' tag of the step to check for completion.
Returns:
True -- if the step has succeeded.... | 5,357,261 |
def counter(filename:Path, window:int):
"""Part one (without window) and part two (with window) of day one."""
if window:
print(
f"sum (window = {window}): "
f"{count_increases(number_from_window(filename, window))}"
)
else:
print(f"sum: {count_increases(numbe... | 5,357,262 |
def bubblesort_2(list_):
"""
Sort the items in list_ in non-decreasing order.
@param list list_: list to sort
@rtype: None
"""
j = len(list_) - 1
swapped = True
# Stop when no elements are swapped.
while swapped and j != 0:
swapped = False
# Swap every item that is o... | 5,357,263 |
def on_chat_send(message):
"""Broadcast chat message to a watch room"""
# Check if params are correct
if 'roomId' not in message:
return {'status_code': 400}, request.sid
room_token = message['roomId']
# Check if room exist
if not db.hexists('rooms', room_token):
{'status_code'... | 5,357,264 |
def arima(size: int = 100,
phi: Union[float, ndarray] = 0,
theta: Union[float, ndarray] = 0,
d: int = 0,
var: float = 0.01,
random_state: float = None) -> ndarray:
# inherit from arima_with_seasonality
"""Simulate a realization from an ARIMA characterist... | 5,357,265 |
def gt_dosage(gt):
"""Convert unphased genotype to dosage"""
x = gt.split(b'/')
return int(x[0])+int(x[1]) | 5,357,266 |
def check_cwd_is_repo_root():
"""Check that script is being called from root of Git repo."""
cwd = os.getcwd()
cwd_name = os.path.split(cwd)[1]
if not os.path.exists(join(cwd, '.git')) or cwd_name != 'wge':
raise RuntimeError('Must run script from root of the Git repository.') | 5,357,267 |
def create_key_pair_in_ssm(
ec2: EC2Client,
ssm: SSMClient,
keypair_name: str,
parameter_name: str,
kms_key_id: Optional[str] = None,
) -> Optional[KeyPairInfo]:
"""Create keypair in SSM."""
keypair = create_key_pair(ec2, keypair_name)
try:
kms_key_label = "default"
kms_a... | 5,357,268 |
def test__string():
""" test graph.string and graph.from_string
"""
for sgr in C8H13O_SGRS:
assert sgr == automol.graph.from_string(automol.graph.string(sgr)) | 5,357,269 |
def sumofsq(im, axis=0):
"""Compute square root of sum of squares.
Args:
im: Raw image.
axis: Channel axis.
Returns:
Square root of sum of squares of input image.
"""
out = np.sqrt(np.sum(im.real * im.real + im.imag * im.imag, axis=axis))
return out | 5,357,270 |
def get_airflow_home():
"""Get path to Airflow Home"""
return expand_env_var(os.environ.get('AIRFLOW_HOME', '~/airflow')) | 5,357,271 |
def read_mapping_file(map_file):
"""
Mappings are simply a CSV file with three columns.
The first is a string to be matched against an entry description.
The second is the payee against which such entries should be posted.
The third is the account against which such entries should be posted.
If... | 5,357,272 |
def biquad_bp2nd(fm, q, fs, q_warp_method="cos"):
"""Calc coeff for bandpass 2nd order.
input:
fm...mid frequency in Hz
q...bandpass quality
fs...sampling frequency in Hz
q_warp_method..."sin", "cos", "tan"
output:
B...numerator coefficients Laplace transfer function
A...denominator... | 5,357,273 |
def pullAllData():
""" Pulls all available data from the database
Sends all analyzed data back in a json with fileNames and list of list
of all "spots" intensities and backgrounds.
Args:
db.d4Images (Mongo db collection): Mongo DB collection with processed
... | 5,357,274 |
def f2():
"""
>>> # +--------------+-----------+-----------+------------+-----------+--------------+
>>> # | Chromosome | Start | End | Name | Score | Strand |
>>> # | (category) | (int32) | (int32) | (object) | (int64) | (category) |
>>> # |--------------+--... | 5,357,275 |
def latin(n, d):
"""
Build latin hypercube.
Parameters
----------
n : int
Number of points.
d : int
Size of space.
Returns
-------
lh : ndarray
Array of points uniformly placed in d-dimensional unit cube.
"""
# spread function
def spread(points):... | 5,357,276 |
def test_read_ego_SE3_sensor(test_data_root_dir: Path) -> None:
"""Read sensor extrinsics for a particular log."""
ego_SE3_sensor_path = test_data_root_dir / "sensor_dataset_logs" / "test_log"
sensor_name_to_sensor_pose = read_ego_SE3_sensor(ego_SE3_sensor_path)
assert sensor_name_to_sensor_pose is not... | 5,357,277 |
def _get_valid_dtype(series_type, logical_type):
"""Return the dtype that is considered valid for a series
with the given logical_type"""
backup_dtype = logical_type.backup_dtype
if ks and series_type == ks.Series and backup_dtype:
valid_dtype = backup_dtype
else:
valid_dtype = logic... | 5,357,278 |
def geometric_mean_longitude(t='now'):
"""
Returns the geometric mean longitude (in degrees).
Parameters
----------
t : {parse_time_types}
A time (usually the start time) specified as a parse_time-compatible
time string, number, or a datetime object.
"""
T = julian_centuries... | 5,357,279 |
def calculate_value_functions_and_flow_utilities(
wages,
nonpec,
continuation_values,
draws,
delta,
is_inadmissible,
value_functions,
flow_utilities,
):
"""Calculate the choice-specific value functions and flow utilities.
Parameters
----------
wages : numpy.ndarray
... | 5,357,280 |
def kill(update: Update, context: CallbackContext):
"""Juega a la ruleta rusa"""
try:
user = update.effective_user
context.bot.sendChatAction(chat_id=update.message.chat_id, action=ChatAction.TYPING, timeout=10)
time = datetime.datetime.now()
context.bot.restrictChatMember(chat_i... | 5,357,281 |
def create_feature_data_batch(im_dir,video_ids):
"""
create_feature_data_batch
Similar function to create_feature_data however utilizing the batch version of functions used in the original function
suited towards larger set of images
Input : directory of thumbnails, list of video ids
Output : ... | 5,357,282 |
def test_tick_fontsize_setter():
"""Assert that the tick_fontsize setter works as intended."""
with pytest.raises(ValueError):
BasePlotter().tick_fontsize = 0 | 5,357,283 |
def export_to_sunrise_from_halolist(ds,fni,star_particle_type,
halo_list,domains_list=None,**kwargs):
"""
Using the center of mass and the virial radius
for a halo, calculate the regions to extract for sunrise.
The regions are defined on the root grid, and so indi... | 5,357,284 |
def GetEnvironFallback(var_list, default):
"""Look up a key in the environment, with fallback to secondary keys
and finally falling back to a default value."""
for var in var_list:
if var in os.environ:
return os.environ[var]
return default | 5,357,285 |
def produce_quick_fig_mol(
molecules, filename, labels=True, mpr=5, ims=200
):
"""
Produce figure showing all the 2D coordinates of molecules.
"""
DrawingOptions.bondLineWidth = 1.8
DrawingOptions.atomLabelFontSize = 16
mols = [Chem.MolFromSmiles(x) for x in molecules.values()]
for m in... | 5,357,286 |
def write_band_table(results,filename,band_definition,fields=None,default=np.nan):
"""Writes level energy, moment, and in-band transition data.
With default arguments, recovers behavior of write_level_table.
Each output line is written in the form
"seq"=0 J p n T Eabs <"E2_moments"> <"M1_moments"... | 5,357,287 |
def get_or_create(model, **kwargs):
"""Get or a create a database model."""
instance = model.query.filter_by(**kwargs)
if instance:
return instance
else:
instance = model(**kwargs)
db.session.add(instance)
return instance | 5,357,288 |
def test_class_id_cube_strategy_elliptic_paraboloid(experiment_enviroment,
renormalize,
thread_flag):
""" """
tm, dataset, experiment, dictionary = experiment_enviroment
class_id_params = {
"class... | 5,357,289 |
def apply_filters(filters: Dict, colnames: List, row: List) -> List:
"""
Process data based on filter chains
:param filters:
:param colnames:
:param row:
:return:
"""
if filters:
new_row = []
for col, data in zip(colnames, row):
if col in filters:
... | 5,357,290 |
def kaiming(shape, dtype, partition_info=None):
"""Kaiming initialization as described in https://arxiv.org/pdf/1502.01852.pdf"""
return tf.random.truncated_normal(shape) * tf.sqrt(2 / float(shape[0])) | 5,357,291 |
def version():
"""Show version or update meta descriptor"""
pass | 5,357,292 |
def save_all_detection(im_array, detections, imdb_classes=None, thresh=0.7):
"""
save all detections in one image with result.png
:param im_array: [b=1 c h w] in rgb
:param detections: [ numpy.ndarray([[x1 y1 x2 y2 score]]) for j in classes ]
:param imdb_classes: list of names in imdb
:param thr... | 5,357,293 |
def trunc_artist(df: pd.DataFrame, artist: str, keep: float = 0.5, random_state: int = None):
"""
Keeps only the requested portion of songs by the artist
(this method is not in use anymore)
"""
data = df.copy()
df_artist = data[data.artist == artist]
data = data[data.artist != artist]
... | 5,357,294 |
async def test_postprocess_results(original, expected):
"""Test Application._postprocess_results."""
callback1_called = False
callback2_called = False
app = Application("testing")
@app.result_postprocessor
async def callback1(app, message):
nonlocal callback1_called
callback1_c... | 5,357,295 |
def toContinuousCategory(
oX: pd.DataFrame,
features: list = [],
drop: bool = True,
int_: bool = True,
float_: bool = True,
quantile: bool = True,
nbin: int = 10,
inplace: bool = True,
verbose: bool = True,
) -> pd.DataFrame:
"""
Transforms any float, continuous integer value... | 5,357,296 |
def test_command_line_interface():
"""Test the CLI."""
runner = CliRunner()
result = runner.invoke(cli.main)
assert result.exit_code == 0
assert 'fibonacci_calculator.cli.main' in result.output
help_result = runner.invoke(cli.main, ['--help'])
assert help_result.exit_code == 0
assert '--... | 5,357,297 |
def task_migrate():
"""Create django databases"""
return {
'actions': ['''cd CCwebsite && python3 manage.py migrate''']
} | 5,357,298 |
def distance_to_arc(alon, alat, aazimuth, plons, plats):
"""
Calculate a closest distance between a great circle arc and a point
(or a collection of points).
:param float alon, alat:
Arc reference point longitude and latitude, in decimal degrees.
:param azimuth:
Arc azimuth (an angl... | 5,357,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.