content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def printTrees(d,l,k,rp, n=None) :
"""
A nice print of all the trees generated by treeReiterable.
Each tree is displayed using :py:func:`stree` from the :py:mod:`treeReiterator` module;
so a tree is represented by a block of lines in DFS order,
with each line containing the nodeDecoration of a single vertex,
indent... | 78,700 |
def read_halos(path):
"""
Reads a list of halos with columns:
rho_s (Msun/kpc^3), r_s (kpc), v (km/s)
"""
data = np.loadtxt(path)
if data.shape[1] > 2:
return data[:,0], data[:,1], data[:,2]
else:
return data[:,0], data[:,1], None | 78,701 |
def simpleMultivariateNormalPdf(z, detFactorSigma):
""" Assuming z has been transformed to a mean of zero and an identity matrix of covariances.
Needs to provide the determinant of the factorized (real) covariance matrix. """
dim = len(z)
return exp(-0.5 * dot(z, z)) / (power(2.0 * pi, dim / 2.) * detFa... | 78,702 |
def _get_change_extent(str1, str2):
"""
Determines the extent of differences between two strings. Returns a tuple
containing the offset at which the changes start, and the negative offset
at which the changes end. If the two strings have neither a common prefix
nor a common suffix, (0, 0) is re... | 78,703 |
def set_logging(hostenv):
"""Set logging levels, handlers"""
# adding line to silence warning
logging.getLogger('googleapiclient.discovery_cache').setLevel(logging.ERROR)
logger = logging.getLogger()
logger.setLevel(getattr(logging, app_configs[hostenv]['log_level']))
formatter = logging.Formatter('... | 78,704 |
def _replace_file_in_command(command, specified_file, name):
""" Replace example file with cheetah variable name in supplied command
or command template. Be sure to quote the name.
"""
# TODO: check if the supplied variant was single quoted already.
if '"%s"' % specified_file in command:
# S... | 78,705 |
def FilterByLength(max_length, min_length=0, # pylint: disable=invalid-name
length_keys=None, length_axis=0):
"""Returns a function that filters out examples by length.
Args:
max_length: int. If not None, indicates maximum length.
min_length: int. If not None, indicates minimum length.
... | 78,706 |
def set_attr(obj, path, value):
"""
SAME AS object.__setattr__(), BUT USES DOT-DELIMITED path
RETURN OLD VALUE
"""
try:
return _set_attr(obj, split_field(path), value)
except Exception as e:
Log = get_logger()
if PATH_NOT_FOUND in e:
Log.warning(PATH_NOT_FOUND... | 78,707 |
def cli(
date,
date_delta,
time,
time_delta,
timezone,
inspect,
compare_exif,
push_exif,
pull_exif,
match_time,
add_to_album,
exiftool_path,
verbose_,
library,
plain,
):
"""photos_time_warp: adjust date/time/timezone of photos in Apple Photos.
Changes ... | 78,708 |
def f1():
"""
f1
:return:
"""
print('running f1()') | 78,709 |
def test_eip_associate_invalid_args_boto3():
"""Associate EIP, invalid args """
client = boto3.client("ec2", region_name="us-east-1")
ec2 = boto3.resource("ec2", region_name="us-east-1")
reservation = client.run_instances(ImageId=EXAMPLE_AMI_ID, MinCount=1, MaxCount=1)
instance = ec2.Instance(reser... | 78,710 |
def get_res_dataframe_as_dict(which_results_table :str, sharelist :str, ov_audit_cols, suppression_spec :str = ''):
""" extract share dataframe from HDFStore """
data_store = None
data_store_key = None
# if ov_audit_cols has content, we're going to have to grab an Ov
ov_df = None
if len(ov_aud... | 78,711 |
def brac(
transitions=None,
# Common settings
discount_factor=0.99,
# Adam optimizer settings
lr_q=1e-3,
lr_pi=1e-3,
# Training settings
bc_iters=5000,
minibatch_size=100,
polyak_rate=0.005,
alpha=0.1
):
"""
Bootstrapping er... | 78,712 |
def stddev(e):
"""
:rtype: Column
"""
return col(StddevSamp(column=parse(e))) | 78,713 |
def create_changelog(milestone, issues, changelog_path, owner, repository):
"""Create a changelog for the given milestone"""
from apply_pr import fabfile
log_level = getattr(logging, os.environ.get('LOG_LEVEL', 'INFO').upper())
logging.basicConfig(level=log_level)
changelog_task = WrappedCallableTa... | 78,714 |
def process(execute_kwargs=None):
"""Function for execute a set of command lines"""
if not execute_kwargs:
execute_kwargs = {}
commands = execute_kwargs["commands"]
if not isinstance(commands, list):
commands = [execute_kwargs["commands"]]
output_results = []
for command in com... | 78,715 |
def test_invalid_weights_summmary():
"""Test that invalid value for weights_summary raises an error."""
with pytest.raises(MisconfigurationException, match="`mode` can be None, .* got temp"):
summarize(UnorderedModel, mode="temp")
with pytest.raises(MisconfigurationException, match="`weights_summar... | 78,716 |
def _is_start_date_before_end_date(start: datetime, end: datetime) -> bool:
"""Whether the start date is before the end date.
Args:
start: The start date of an event.
end: The end date of an event.
Returns:
True if valid, otherwise returns False.
"""
return start <= end | 78,717 |
def sens_expand(x: torch.Tensor, sens_maps: torch.Tensor) -> torch.Tensor:
"""
Expand a single image into num_coils individual coil images using estimates of the sensitivity maps.
This is the inverse of sens_reduce.
Args:
x: An image of shape (H, W, 2).
sens_maps: Sensitivity maps o... | 78,718 |
def radrad_scan(ts_zma, ts_info, hs_info,
ts_formula, high_mul, active_space,
rct_info, rct_ichs, rcts_cnf_fs, rcts_gra,
grid1, grid2, coord_name, frm_bnd_keys,
mod_var_scn_thy_info,
mod_var_sp1_thy_info, # Need an unmodifie
... | 78,719 |
def associate_pokemon_info_with_moves(pokemon_info: List[Dict[str, Any]]) -> None:
"""
Associates the pokemon information in the database with all of the moves they are associated with.
"""
def apply_move_assocs(pokemon: Dict[str, Any]) -> None:
moves = pokemon['moves']
# We put a h... | 78,720 |
def test_checkIfExists() -> None:
"""Check if the given path exists, is a file or directory."""
file_path1 = tests.test_project_path
file_path2 = "/".join([tests.test_project_path, "project_config.json"])
file_path3 = "/".join([tests.test_project_path, "this_does_not_exist"])
files_to_test = {
... | 78,721 |
def parseWithBioPython(path, props, chains_filter=None):
"""
Parse values from file that can be parsed using BioPython library
@return a dict containing the properties that were processed
"""
pdb = './pdb'
full_path = os.path.abspath(os.path.join(pdb, path))
chains = props['chains']
... | 78,722 |
def structure(self: Client) -> StructureProxy:
"""Delegates to a
:py:class:`mcipc.rcon.be.commands.structure.StructureProxy`
"""
return StructureProxy(self, 'structure') | 78,723 |
def get_data_folder():
"""
Returns the location of the folder containing data files.
"""
path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'data')
return os.path.normpath(path) | 78,724 |
def _points_from_xy(x, y, z=None):
"""
Generate list of shapely Point geometries from x, y(, z) coordinates.
Parameters
----------
x, y, z : iterable
Returns
-------
list : list
"""
if not len(x) == len(y):
raise ValueError("x and y arrays must be equal length.")
if... | 78,725 |
def box(width,depth,height,center=None,R=None,t=None,world=None,name=None,mass=float('inf'),type='TriangleMesh'):
"""Makes a box with dimensions width x depth x height. The box is centered
at (0,0,0) by default.
Args:
width,depth,height (float): x,y,z dimensions of the box
center (list of ... | 78,726 |
def get_disabled_container_list(duthost):
"""Gets the container/service names which are disabled.
Args:
duthost: Host DUT.
Return:
A list includes the names of disabled containers/services
"""
disabled_containers = []
container_status, succeeded = duthost.get_feature_status()
... | 78,727 |
def _SignedVarintDecoder(mask):
"""Like _VarintDecoder() but decodes signed values."""
local_ord = ord
def DecodeVarint(buffer, pos):
result = 0
shift = 0
while 1:
if pos > len(buffer) - 1:
raise NotEnoughDataExcption("Not enough data to decode varint")
... | 78,728 |
def ConvertIndexListToSet(index_list):
"""Creates a set containing the indices of all '1' entries in the index
list
"""
return set(i + 1 for i, j in enumerate(index_list) if j == 1) | 78,729 |
def update_scope(period: Optional[float] = None, sample_rate: Optional[float] = 27e3,
input_channels : Optional[Dict[str, int]] = None,
input_ranges: Optional[Tuple[float, float]] = (1.0, 1.0),
limits: Optional[Tuple[float, float]] = (0.0, 1.0),
trigge... | 78,730 |
def decrypt(text_enc: Tuple[int, int]) -> str:
"""Function that decrypt the tuple of tokens
and re-convert them into string.
:param text_enc: the tuple of the text encrypted
:return: the text decrypted
"""
encrypted = text_enc[0] ^ text_enc[1]
decrypted = encrypted.to_bytes((encrypted.bit_l... | 78,731 |
def build_lattice_sprinkle(ratio_a=0.2, ratio_b=0.2, ic_radius_fraction=0.1):
"""Sprinkle cells in the center, IC edge size n * m
Args:
ratio_a, ratio_b: determine sprinkling in IC region
ic_radius_fraction: size fraction of IC radius
"""
# ic setup
ic_radius_units = int(n * ic_radiu... | 78,732 |
def hypersphere_point(Gr, agent_pos):
"""
For each agent determines a random point inside the hypersphere (Gr,|Gr-X|),
where Gr is its center, |Gr-X| is its radius, and X is the agent position.
"""
nPop, nVar = agent_pos.shape
# Hypersphere radius of each agent
r_max = np.linalg.norm(Gr - a... | 78,733 |
def iterable_validator(schema):
"""Return a validator for casting part of schema."""
return SchemaValidator(
Draft7Validator(
schema['definitions']['iterable'],
format_checker=draft7_format_checker,
),
) | 78,734 |
def remove_suffix_ness(word: str):
"""Remove the suffix from the word while keeping spelling in mind.
:param word: str - of word to remove suffix from.
:return: str - of word with suffix removed & spelling adjusted.
For example: "heaviness" becomes "heavy", but "sadness" becomes "sad".
"""
suf... | 78,735 |
def train_nonsegmented(language_model, dataset_fnames, segment_filtering=False):
"""
Trains a classifier that maps document similarity to relevance labels.
The non-segmented version disregards segmentation and computes similarity directly between
documents.
If segment_filtering is n... | 78,736 |
def count_words(text):
"""
this function counts words
param sentence: string containing words
"""
if not isinstance(text, str):
raise TypeError("word counter accepts only strings")
normal_word_splits = text.split(" ")
new_words = []
for asplit in normal_word_splits:
if "\... | 78,737 |
def edit_food(id):
"""Update a food entry if the current user is the creator"""
db = get_db()
food_entry = get_food_entry(id)
old_food_name = food_entry['food_name']
old_food_code = food_entry['food_code']
if request.method == 'POST':
if request.form['action'] == 'Update Entry':
... | 78,738 |
def run_simulation(sim_object, forest_dimension):
"""
Run a single simulation with RBF and report the filter accuracy.
:param sim_object: LatticeForest simulation object.
:param forest_dimension: int representing the size of one side of the square LatticeForest.
:return: tuple of (observation accur... | 78,739 |
def print_solution(sudokuMatrix, sudokuVars, model):
""" Create a copy of the original sudoku matrix problem and fill
the blanks (i.e. zeros) with the solutions from the model
"""
solvedMatrix = deepcopy(sudokuMatrix)
for i in range(GRID_SIZE):
for j in range(GRID_SIZE):
if sol... | 78,740 |
def configure_logger():
"""Fancy logging is nicer"""
formatter = ColoredFormatter(
"%(log_color)s%(levelname)s - %(message)s",
datefmt=None,
reset=True,
log_colors={
"DEBUG": "yellow",
"INFO": "cyan",
"WARNING": "purple",
"ERROR": "... | 78,741 |
def test_read_configuration_from_stdin():
"""Test that a finder chart configuration can be read from stdin."""
result = runner.invoke(app, [], input="xyz123: configuration")
assert "Failed validating" in result.stdout and "xyz123" in result.stdout | 78,742 |
def lisser(chaine):
"""Retourne la chaîne lisser.
On lisse une chaîne en remplaçant certains schémas comme
" de le " par " du ".
"""
schemas = (
(" le a", " l'a"),
(" le e", " l'e"),
(" le hom", " l'hom"),
(" le hum", " l'hum"),
(" le i", " l'i"),
("... | 78,743 |
def plot_mixture_fit(X, log_pdf, mu, var, mp, fig_num=1, W=None, title=''):
""" Plot mixture fit.
Args:
X (torch.tensor): (N, C).
fig_num (int, optional): Defaults to 1.
W (torch.tensor, optional): Defaults to no weights.
title (string, optional): Defaults to ''.
"""
if... | 78,744 |
def ignore_pred(pred_boxes, gt_ignored_index, gt_polys, precision_thr):
"""Ignore the predicted box if it hits any ignored ground truth.
Args:
pred_boxes (list[ndarray or list]): The predicted boxes of one image.
gt_ignored_index (list[int]): The ignored ground truth index list.
gt_poly... | 78,745 |
def crawl_ve_from_remote_logs(mi_info, dn):
"""
deprecated do not use
Args:
mi_info : a dict mapping from model iter to ModelSearchInfo
dn : directory path of the one that directly contains the server log.log, i.e.,
the remote logs are in {dn}/{model_iter}/log.log
"""
for mi in mi_info:... | 78,746 |
def compareBamRecords(this, other):
"""Compare this (a BamAlignment object) with other
(a BamZmwRead object)"""
assert(isinstance(this, BamAlignment) and
isinstance(other, BamZmwRead))
return (this.readName == other.readName and
this.zmwName == other.zmw.zmwName and
... | 78,747 |
def miter_join_framings(framings):
"""Set mitter joins for selected framings"""
for framing in framings:
# select first start/end joins
# TODO: add selecting join by angle or similar way
joins = get_element_joins(framing)
start_join = joins[0][0] if joins[0] else None
en... | 78,748 |
def moveZeroes(nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
j = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[j] = nums[i]
j += 1
k = len(nums)-j
while (k > 0):
nums[-k] = 0
... | 78,749 |
def get_lag(feature, target_feature=None):
"""Return the lag duration as an integer.
Optionally a specific target feature can be required.
Args:
feature (str): Feature to extract month from.
target_feature (str): If given, this feature is required for a successful
match.
R... | 78,750 |
def _map_header(keymap, dold, nulldict=None):
"""
Returns a dictionary of values from dictionary dold,
mapped to new key, if provided.
Parameters
----------
keymap: dict
The map between old and new dictionary keys.
Of the form {oldkey: newkey, ...}
dold: dict
The val... | 78,751 |
def avgpool(prev_layer):
"""
Return the AveragePooling layer.
"""
return tf.nn.avg_pool(prev_layer, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') | 78,752 |
def vec3(*args):
"""Create 3D vector from input ``args``."""
if len(args) == 1: args = args[0]
return np.asarray(args, dtype='f8') | 78,753 |
def pyro_log():
"""
Set environment variables to activate Pyro logging. The log level is
set to "DEBUG".
"""
os.environ['PYRO_LOGFILE'] = 'pyro_osbrain.log'
os.environ['PYRO_LOGLEVEL'] = 'DEBUG' | 78,754 |
def full_jitter(value):
"""Jitter the value across the full range (0 to value).
Copied from https://github.com/litl/backoff/blob/master/backoff.py (MIT License)
This corresponds to the "Full Jitter" algorithm specified in the
AWS blog's post on the performance of various jitter algorithms.
(http:/... | 78,755 |
def enum_folder(parent_folder, fn):
"""
:type parent_folder: Folder
:type fn: (File)-> None
"""
parent_folder.expand(["Files", "Folders"]).get().execute_query()
for file in parent_folder.files: # type: File
fn(file)
for folder in parent_folder.folders: # type: Folder
enum_f... | 78,756 |
def get_argument_parser():
"""Set up command line arguments and usage."""
parser = argparse.ArgumentParser()
parser.add_argument(
'location',
type=str,
help='file or directory containing unit tests'
)
parser.add_argument(
'--pattern',
'-p',
default='^(test_.*|.*_test)\\.py$',
type... | 78,757 |
def _init() -> None:
"""Initialize relic."""
from . import _relic
import atexit
needs_cleanup, core_success, pair_success = _relic._relic_init()
if needs_cleanup:
atexit.register(_relic._relic_clean)
if not core_success:
raise RuntimeError("Failed to initialize relic (core)!")... | 78,758 |
def plotVisibility(xi, yi, zi, save_dir='.'):
"""
功能:
绘制能见度等值线
输入:
xi: 插值格点后的经向numpy array
yi: 插值格点后的纬向numpy array
zi: 经过matplotlib.mlab.griddata插值后的二维numpy array
输出:
save_dir/tempfile.png
"""
fig = plt.figure(frameon=False)... | 78,759 |
def get_mentored_team(mentor, hackathon):
""" Retrieve all mentored teams for a Judge at a Hackathon """
mentored_teams = None
mentored_teams = mentor.mentored_teams.filter(
hackathon=hackathon).order_by('display_name')
return mentored_teams | 78,760 |
def get_ranges(uid_number, inc=0):
"""
Return two block ranges to be used to create subnets for
Atmosphere users.
NOTE: If you change MAX_SUBNET then you should likely change
the related math.
"""
MAX_SUBNET = 4064 # Note 16 * 256
n = uid_number % MAX_SUBNET
# 16-31
block1 = (... | 78,761 |
def returnRectangles(a,x):
""" Returns 2D discrete integral array using the rectangle method
The calculation for each array element is
:math:`(\Delta y_i = 0.5(a_{n-1}+a_{n})*(x_{n-1}-x_{n})`
Parameters
----------
a : numpy.ndarray
Description: Array of y(x) function with N+1 elements
... | 78,762 |
def google(query: str, suggestion_count: int = 0) -> bool:
"""Uses Google's search engine parser and gets the first result that shows up on a Google search.
Notes:
- If it is unable to get the result, Jarvis sends a request to ``suggestqueries.google.com``
- This is to rephrase the query and th... | 78,763 |
def strip_id(url):
"""Get MP database ID from url."""
url = url.split('/')
return url[-2] | 78,764 |
def load_json_fixture(filename: str) -> Any:
"""Load a json fixture."""
path = Path(Path(__file__).parent.joinpath("fixtures"), filename)
return json.loads(path.read_text(encoding="utf-8")) | 78,765 |
def set_lower_tor_admin_forwarding_state(nic_simulator_url, port, state):
"""Set lower ToR admin forwarding state."""
pass | 78,766 |
def extract_notes_from_midi(midi_file: music21.stream.Stream) -> List:
"""
This function extract all the notes out of the midi files in the signed data path
:param midi_file: Midi file
:return: return list of notes out of the midi files
"""
notes = []
parts = music21.instrument.partitionBy... | 78,767 |
def plot_trajectory(proj_file, dir_file, show=False):
""" Plot optimization trajectory on the plane spanned by given directions."""
print(proj_file)
assert exists(proj_file), 'Projection file does not exist.'
f = h5py.File(proj_file, 'r')
fig = plt.figure()
plt.plot(f['proj_xcoord'], f['proj_yc... | 78,768 |
def batch_index_iterator(len_l, batch_size, skip_end=True):
"""
Provides indices that iterate over a list
:param len_l: int representing size of thing that we will
iterate over
:param batch_size: size of each batch
:param skip_end: if true, don't iterate over the last batch
:return: A ge... | 78,769 |
def find_channel(channel_name, source):
"""
Search for channel by name on the given object
"""
name = channel_name.lower()
for channel in source.channels:
if channel.name.lower() == name:
return channel
return None | 78,770 |
def paired_to_read2(reader):
"""Generator that yields the second read from an iterator over read pairs.
"""
for _, read2 in reader:
yield read2 | 78,771 |
def render_file(path: str):
"""
Route for getting either a supporting file or the root index.html file for the UI
:param path: the path requested for a UI file to render,
note this is a catch all, so may improperly catch other misspelled routes
and therefore fail to render them
:return:... | 78,772 |
def get_device_status(host):
"""
:param host: Hostname or ip to fetch status from
:type host: str
:return: The device status as a named tuple.
:rtype: pychromecast.dial.DeviceStatus or None
"""
try:
req = CC_SESSION.get(
FORMAT_BASE_URL.format(host) + "/ssdp/device-desc.... | 78,773 |
def delta_V(V_0, V_f, beta_0, inc_0, inc_f):
"""Compute required increment of velocity."""
delta_i_f = abs(inc_f - inc_0)
if delta_i_f == 0:
return abs(V_f - V_0)
return V_0 * np.cos(beta_0) - V_0 * np.sin(beta_0) / np.tan(
np.pi / 2 * delta_i_f + beta_0
) | 78,774 |
def depth_first_solve(puzzle: SudokuPuzzle) -> Optional[SudokuPuzzle]:
"""
An iterative depth first search to solve the puzzle.
"""
if puzzle.is_solved():
return puzzle
puzzle_queue = puzzle.extensions()
while puzzle_queue:
curr = puzzle_queue.pop()
if curr.is_solved():
... | 78,775 |
def quicksort_recursive(arr):
"""
1. Pick a random element arr[pivotindx] as pivot
2. Construct three arrays
(a) less: all values < arr[pivotindx]
(b) same: all values = arr[pivotindx]
(c) more: all values > arr[pivotindx]
3. recursively apply function to less and more
"""
... | 78,776 |
def Interp_doppler_savememory(grid, wteff, wlogg, wmu, wwav, jteff, jlogg, jmu, jwav, mu_grid, area, val_mu):
"""
Simple interpolation of an atmosphere grid having axes (logtemp, logg, wav).
This grid interpolation is made for a grid which is linear in the velocity
or redshift space, e.g. log lambda.
... | 78,777 |
def main(lr, train_path, eval_path, save_path):
"""Problem: Poisson regression with gradient ascent.
Args:
lr: Learning rate for gradient ascent.
train_path: Path to CSV file containing dataset for training.
eval_path: Path to CSV file containing dataset for evaluation.
save_pat... | 78,778 |
def conf(db, context, log, fields):
"""Perform CONF command.
This is supposed to adjust the configuration of the Crusher database.
"""
"""Configure the database."""
db.configure(fields[1])
"""Copy the configuration command to the log."""
log.write("{}\t{}\n".format(fields[0], fields[1]))
... | 78,779 |
def sample_diversity(labels, features, max_to_return=20):
"""
Attempt to create a diverse, model-independent sample of
images to tag. PCA-reduce feature vectors an then use k-means
for sampling.
:features: (num_samples, input_dim) array of feature vectors
:max_to_return: if not None; max nu... | 78,780 |
def validate(filters):
""" Validation of function parameters """
def decorator(f):
@wraps(f)
def wrapper(request, data):
_strip(data)
data = _check(data, filters)
return f(request, data)
return wrapper
return decorator | 78,781 |
def clean_decimal_2(text: Text) -> Optional[Decimal]:
"""
Remove $ and , from a string, return a Decimal.
>>> clean_decimal_2("$1,234.56")
Decimal('1234.56')
"""
if text is None:
return None
return Decimal(replace(replace(text, "$", ""), ",", "")) | 78,782 |
def make_san_mask(xs, xlens, unidirectional=False, lookahead=0):
"""Mask self-attention mask.
Args:
xs (FloatTensor): `[B, T, d_model]`
xlens (InteTensor): `[B]` (on CPU)
unidirectional (bool): pad future context
lookahead (int): lookahead frame
Returns:
xx_mask (Byt... | 78,783 |
def calc_R_sq_adj(var_basis, matrix_coeffs, responses):
"""
Inputs: var_basis- evaluated variable basis
matrix_coeffs- matrix coefficients
responses- vector of responses
Calculates the adjusted R squared statistic for the given system.
Design and Analysis of Experiments... | 78,784 |
def assert_submission_id(method):
"""Decorate `method` to guard against unset submission ID.
"""
@wraps(method)
def wrapped(self, *args, **kwds):
if not self.submission_id:
lgr.warning("Cannot check status without a submission ID")
return "unknown", None
return m... | 78,785 |
def a08_curve_function(curve: CustomCurve):
"""
Computes the lower and upper bound of class number of the maximal order of the endomorphism algebra
Upper bound:
Inequality class number<= sqrt(d)*log(d)*constant (see below)
#https://en.wikipedia.org/wiki/Class_number_formula#Dirichlet_class_number_f... | 78,786 |
def arithmatex_fenced_format(**kwargs):
"""Specify which type of formatter you want and the wrapping tag."""
mode = kwargs.get('mode', 'generic')
tag = kwargs.get('tag', 'div')
preview = kwargs.get('preview', False)
if mode == 'generic':
return partial(_fence_generic_format, tag=tag)
e... | 78,787 |
def validate_query_result(student_key, student_val, query_result):
"""
Compare query result with expected key and value.
"""
assert len(query_result) == 2
sql_row = dict(zip(query_result[0], query_result[1]))
assert sql_row['ID'] == student_key.ID
assert sql_row['DEPT'] == student_key.DEPT
... | 78,788 |
def run_pipe_file(pipe_fpath, dry=False):
"""
Executes pipeline_runner with a specific pipe file.
"""
import os
runner_fpath = find_pipeline_runner()
if runner_fpath is None:
raise Exception('Cannot find pipeline_runner. Is it in your PATH?')
# '/home/joncrall/code/VIAME/build/instal... | 78,789 |
def fill_holes(image, thresh=0.001):
"""Fill holes in a binary image
Args:
image:
thresh:
Returns:
"""
from skimage.morphology import reconstruction
seed = np.copy(image)
seed[1:-1, 1:-1] = image.max()
mask = image
filled = reconstruction(seed, mask, method='eros... | 78,790 |
def get_search_args() -> None:
"""Parse command line arguments."""
parser = argparse.ArgumentParser()
parser.add_argument(
"exec_fname",
metavar="C",
type=str,
default="main.py",
help="Filename to import `main(config)` function from.",
)
parser.add_argument(
... | 78,791 |
def _allreduce(tensor, name=None):
"""An op which reduces an input tensor over all the Bluefog processes. The
default reduction is a sum.
The reduction operation is keyed by the name of the op. The tensor type and
shape must be the same on all Bluefog processes for a given name. The reduction
will ... | 78,792 |
def bbox_transform_inv(boxes, deltas, mean=None, std=None):
""" Applies deltas (usually regression results) to boxes (usually anchors).
Before applying the deltas to the boxes, the normalization that was previously applied (in the generator) has to be removed.
The mean and std are the mean and std as appli... | 78,793 |
def make_custom_entity(
device: hm_device.HmDevice,
address: str,
custom_entity_class: type,
device_enum: EntityDefinition,
group_base_channels: list[int],
) -> list[hm_entity.BaseEntity]:
"""
Creates custom_entities.
We use a helper-function to avoid raising exceptions during object-ini... | 78,794 |
def classroom_add_student_new(course_id):
"""
Adds a student to a course, the teacher has access to.
The file token.json stores the user's access and refresh tokens, and is
created automatically when the authorization flow completes for the first
time.
Load pre-authorized user credentials from t... | 78,795 |
def gru_with_backend_selection(inputs, init_h, kernel, recurrent_kernel, bias,
mask, time_major, go_backwards, sequence_lengths,
zero_output_for_mask, return_sequences):
"""Call the GRU with optimized backend kernel selection.
Under the hood, this funct... | 78,796 |
def write_basic(f, k, elem, dataset_kwargs=MappingProxyType({})):
"""Write methods which underlying library handles nativley."""
f.create_dataset(k, data=elem, **dataset_kwargs) | 78,797 |
def test_next_schedule_after_friday(timetable: Timetable, restriction: TimeRestriction):
"""The run after Friday's run covers Monday."""
last_automated_data_interval = DataInterval(WEEK_1_WEEKDAYS[-1], WEEK_1_SATURDAY)
expected_next_info = DagRunInfo.interval(WEEK_2_MONDAY, WEEK_2_TUESDAY)
next_info = ... | 78,798 |
def adjust_learning_rate(optimizer, epoch, args):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
if args.arch == "alexnet":
lr = float(args.lr) * (0.94 ** (epoch // 2))
else:
lr = float(args.lr) * (0.1 ** (epoch // 30))
for param_group in optimizer.param_gro... | 78,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.