content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def vgg13_bn(**kwargs):
"""
VGG 13-layer model (configuration "B") with batch normalization
"""
model = VGG(make_layers(cfg['B'], batch_norm=True), **kwargs)
return model | 5,325,700 |
def lr_insight_wr():
"""Return 5-fold cross validation scores r2, mae, rmse"""
steps = [('scaler', t.MyScaler(dont_scale='for_profit')),
('knn', t.KNNKeepDf())]
pipe = Pipeline(steps)
pipe.fit(X_raw)
X = pipe.transform(X_raw)
lr = LinearRegression()
lr.fit(X, y)
cv_results ... | 5,325,701 |
def complete_list_value(exe_context, return_type, field_asts, info, result):
"""
Complete a list value by completing each item in the list with the inner type
"""
assert isinstance(result, collections.Iterable), \
('User Error: expected iterable, but did not find one ' +
'for field {}.{... | 5,325,702 |
def projection_ERK(rkm, dt, f, eta, deta, w0, t_final):
"""Explicit Projection Runge-Kutta method."""
rkm = rkm.__num__()
w = np.array(w0) # current value of the unknown function
t = 0 # current time
ww = np.zeros([np.size(w0), 1]) # values at each time step
ww[:,0] = w.copy()
tt = np.zeros... | 5,325,703 |
def integer(name, value):
"""Validate that the value represents an integer
:param name: Name of the argument
:param value: A value representing an integer
:returns: The value as an int, or None if value is None
:raises: InvalidParameterValue if the value does not represent an integer
"""
if... | 5,325,704 |
def generate_Euler_Maruyama_propagators():
"""
importer function
function that creates two functions:
1. first function created is a kernel propagator (K)
2. second function returns the kernel ratio calculator
"""
# let's make the kernel propagator first: this is just a batched ULA move
... | 5,325,705 |
def test_save_works(client):
"""Save should work."""
proto_reminder['message'] = 'test_save_works'
res = client.post('/api/reminders', json=proto_reminder)
assert res.status_code == 201
assert res.content_type == 'application/json'
assert proto_reminder['message'].encode() in res.data | 5,325,706 |
def get_vtx_neighbor(vtx, faces, n=1, ordinal=False, mask=None):
"""
Get one vertex's n-ring neighbor vertices
Parameters
----------
vtx : integer
a vertex's id
faces : numpy array
the array of shape [n_triangles, 3]
n : integer
specify which ring should be got
o... | 5,325,707 |
def assert_value_in_cell_is_equal(test_case, expected_cell, actual_cell):
"""
:param TestCase test_case:
:param Cell expected_cell:
:param Cell actual_cell:
:return:
"""
expected_val = expected_cell.value
actual_val = actual_cell.value
if isinstance(expected_val, str):
if ex... | 5,325,708 |
def run_from_text(text: str, n_merges: int=sys.maxsize) -> Tuple[str, int, Optional[List[BpePerformanceStatsEntry]]]:
"""
>>> def run_and_get_merges(text: str):
... return [(m, occ) for m, occ, _ in run_from_text(text)]
>>> run_and_get_merges("a")
[]
>>> run_and_get_merges("ab")
[('a b... | 5,325,709 |
def load_line_delimited_json(filename):
"""Load data from the file that is stored as line-delimited JSON.
Parameters
----------
filename : str
Returns
-------
dict
"""
objects = []
with open(filename) as f_in:
for i, line in enumerate(f_in):
text = line.str... | 5,325,710 |
def tolower(x: StringOrIter) -> StringOrIter:
"""Convert strings to lower case
Args:
x: A string or vector of strings
Returns:
Converted strings
"""
x = as_character(x)
if is_scalar(x):
return x.lower()
return Array([elem.lower() for elem in x]) | 5,325,711 |
def initialize_course(header, stu):
"""
Helper function for initialize. This function takes in the request header
and uses either the UQ SSO header or default values to add the student
and course pairing into the database.
:param header: a Http Request received by the initialize view
:param stu... | 5,325,712 |
def MWA_Tile_analytic(za, az,
freq=100.0e6,
delays=None,
zenithnorm=True,
power=False,
dipheight=config.DIPOLE_HEIGHT,
dip_sep=config.DIPOLE_SEPARATION,
delay_int=con... | 5,325,713 |
def traindata():
"""Generate Plots in the traindata page.
Args:
None
Returns:
render_template(render_template): Render template for the plots
"""
# read data and create visuals
df_features = read_data_csv("./data/features_data.csv")
... | 5,325,714 |
def import_file(file_path, title, source_mime_type, dest_mime_type):
"""Imports a file with conversion to the native Google document format.
Expects the env var GOOGLE_APPLICATION_CREDENTIALS to be set for
credentials.
Args:
path (str): Path to file to import
title(str): The title of th... | 5,325,715 |
def init_prop_sheet(target: T.Target, prefix=''):
"""
References:
https://stackoverflow.com/questions/2611892/how-to-get-the-parents-of-a
-python-class
"""
assert all((
hasattr(target, 'qid'),
# hasattr(target, 'name'),
hasattr(target, '_properties'),
))
... | 5,325,716 |
def test_extract_requested_slot_from_text_with_not_intent():
"""Test extraction of a slot value from text with certain intent
"""
# noinspection PyAbstractClass
class CustomFormAction(FormAction):
def slot_mappings(self):
return {"some_slot": self.from_text(not_intent='some_intent')}... | 5,325,717 |
def test_dewpoint():
"""Test dewpoint calculation."""
assert_almost_equal(dewpoint(6.112 * units.mbar), 0. * units.degC, 2) | 5,325,718 |
def stop():
"""Stop ckan service (gunicorn)."""
control('stop') | 5,325,719 |
def _get_info_file_path():
"""Get path to info file for the current process.
As with `_get_info_dir`, the info directory will be created if it does
not exist.
"""
return os.path.join(_get_info_dir(), "pid-%d.info" % os.getpid()) | 5,325,720 |
def create_generic_io_object(ioclass, filename=None, directory=None,
return_path=False, clean=False):
"""
Create an io object in a generic way that can work with both
file-based and directory-based io objects
If filename is None, create a filename.
If return_path is Tr... | 5,325,721 |
def select_channels(img_RGB):
"""
Returns the R' and V* channels for a skin lesion image.
Args:
img_RGB (np.array): The RGB image of the skin lesion
"""
img_RGB_norm = img_RGB / 255.0
img_r_norm = img_RGB_norm[..., 0] / (
img_RGB_norm[..., 0] + img_RGB_norm[..., 1] + img_RGB_nor... | 5,325,722 |
def upper_case(string):
"""
Returns its argument in upper case.
:param string: str
:return: str
"""
return string.upper() | 5,325,723 |
def repositoryDefinitions():
"""
Load repositoryDefinitions page
"""
i_d = wmc.repository.get_definition_details()
p_d = json.dumps(i_d, indent=4) + " "
msg = Markup(JSONtoHTML(p_d))
return render_template('repositoryDefinitions.html', data=msg) | 5,325,724 |
def available_adapter_names():
"""Return a string list of the available adapters."""
return [str(adp.name) for adp in plugins.ActiveManifest().adapters] | 5,325,725 |
def parse_user_arguments(*args, **kwds):
"""
Parses the arguments of the program
"""
parser = argparse.ArgumentParser(
description = "Generate the profiles of the input drug",
epilog = "@oliva's lab 2017")
parser.add_argument('-d','--drug_name',dest='drug_name',action = 'store'... | 5,325,726 |
def apply_d2v_rel_corpus():
"""
Evaluate the doc2vec feature vectors on the smaller corpus for
cited/random and relevant/irrelevant labellings
"""
# load text
#pat_corpus = PatentCorpus()
#pat_corpus.mode = 'd2v'
#list(pat_corpus)
combis = np.load('human_eval/corpus_info/combis.npy')... | 5,325,727 |
def error(msg, **kwargs):
"""log level error"""
log(LEVELS['error'], msg, **kwargs) | 5,325,728 |
def createNewLetterSession(letter):
"""
# Take letter and create next session folder (session id is current max_id + 1)
# Return path to session directory
"""
# Search for last training folder
path = "gestures_database/"+letter+"/"
last = -1
for r,d,f in os.walk(path):
for folder in d:
last = max(last, ... | 5,325,729 |
def count_sort(seq):
""" perform count sort and return sorted sequence without
affecting the original
"""
counts = defaultdict(list)
for elem in seq:
counts[elem].append(elem)
result = []
for i in range(min(seq), max(seq)+1):
result.extend(counts[i])
return result | 5,325,730 |
def detect_overrides(cls, obj):
"""
For each active plugin, check if it wield a packet hook. If it does, add
make a not of it. Hand back all hooks for a specific packet type when done.
"""
res = set()
for key, value in cls.__dict__.items():
if isinstance(value, classmethod):
... | 5,325,731 |
def morningCalls():
"""localhost:8080/morningcalls"""
session = APIRequest.WebServiceSafra()
return session.listMorningCalls() | 5,325,732 |
def resize_image(img, h, w):
""" resize image """
image = cv2.resize(img, (w, h), interpolation=cv2.INTER_NEAREST)
return image | 5,325,733 |
def train_one_epoch(train_loader, model, criterion, optimizer, epoch, writer):
"""
Run one train epoch
"""
batch_time = AverageMeter()
data_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
# switch to train mode
model.train()
print_period = (len(train_loa... | 5,325,734 |
def view_vwap(
s_ticker: str,
ohlc: pd.DataFrame,
offset: int = 0,
s_interval: str = "",
export: str = "",
external_axes: Optional[List[plt.Axes]] = None,
):
"""Plots EMA technical indicator
Parameters
----------
s_ticker : str
Ticker
ohlc : pd.DataFrame
Data... | 5,325,735 |
def _parse_pars(pars) -> Dict:
"""
Takes dictionary of parameters, converting values to required type
and providing defaults for missing values.
Args:
pars: Parameters dictionary.
Returns:
Dictionary of converted (and optionally validated) parameters.
"""
# Fallback to defa... | 5,325,736 |
def _get_base_class_names_of_parent_and_child_from_edge(schema_graph, current_location):
"""Return the base class names of a location and its parent from last edge information."""
edge_direction, edge_name = _get_last_edge_direction_and_name_to_location(current_location)
edge_element = schema_graph.get_edge... | 5,325,737 |
def projection(
v: GridVariableVector,
solve: Callable = solve_fast_diag,
) -> GridVariableVector:
"""Apply pressure projection to make a velocity field divergence free."""
grid = grids.consistent_grid(*v)
pressure_bc = boundaries.get_pressure_bc_from_velocity(v)
q0 = grids.GridArray(jnp.zeros(grid.sha... | 5,325,738 |
def a07_curve_function(curve: CustomCurve):
"""Computes the embedding degree (with respect to the generator order) and its complement"""
q = curve.q()
if q.nbits()>300:
return {"embedding_degree_complement":None,"complement_bit_length":None}
l = curve.order()
embedding_degree = curve.embeddi... | 5,325,739 |
def _horizontal_metrics_from_coordinates(xcoord,ycoord):
"""Return horizontal scale factors computed from arrays of projection
coordinates.
Parameters
----------
xcoord : xarray dataarray
array of x_coordinate used to build the grid metrics.
either plane_x_coord... | 5,325,740 |
def ultosc(
df,
high,
low,
close,
ultosc,
time_period_1=7,
time_period_2=14,
time_period_3=28,
):
"""
The Ultimate Oscillator (ULTOSC) by Larry Williams is a momentum oscillator
that incorporates three different time periods to improve the overbought and
oversold signals.... | 5,325,741 |
def mating(child_id, parent1, parent2, gt_matrix):
"""
Given the name of a child and two parents + the genotype matrices, mate them
"""
child_gen = phase_parents(parent1, parent2, gt_matrix)
parent1.add_children(child_id)
parent2.add_children(child_id)
child = Person(child_id)
child.se... | 5,325,742 |
def fix_bathy(infile, mindep):
"""
Simple script to enforce minimum depth and fix the longitudes.
Run this on the file produced by agrif_create_bathy.exe.
"""
with nc.Dataset(infile, 'r+') as f:
# Enforce minimum bathymetry
bm = f.variables['Bathymetry'][:]
idx = (bm > 0) & ... | 5,325,743 |
def chunks( l, n ):
""" Yield successive n-sized chunks from l.
"""
tmp = None
for i in l:
if tmp is None:
tmp = []
tmp.append( i )
if n == len( tmp ):
yield tmp
tmp = None
if tmp is not None:
yield tmp | 5,325,744 |
def _tmp(
generator_reconstructed_encoded_fake_data,
encoded_random_latent_vectors,
real_data,
encoded_real_data,
generator_reconstructed_encoded_real_data,
alpha=0.7,
scope="anomaly_score",
add_summaries=False):
"""anomaly score.
See https://arx... | 5,325,745 |
def print_success(message: str):
"""
Print success
:param message: message to print
:type message: str
"""
global verbose
if verbose:
print("%s%s%s" % (KGRN, message, KNRM)) | 5,325,746 |
def get_key_metrics_fig(confirmed_ser, recovered_ser, deaths_ser, metric_type):
"""
Return key metrics graph object figure
Parameters
----------
confirmed_ser: pandas.Series
Confirmed pandas series objects with index=dates,
values=number of cases
r... | 5,325,747 |
def cms_post_popup(r):
"""
Customized Map popup for cms_post resource
- style like the cards
- currently unused
"""
record = r.record
pkey = "cms_post.id"
# Construct the item ID
map_id = "default_map" # @ToDo: provide the map_id as a var in order to be able to support ... | 5,325,748 |
def pr_curve(results: List[TrecEvalResults]) -> plt:
"""
Create a precision-recall graph from trec_eval results.
:param results: A list of TrecEvalResults files.
:return: a matplotlib plt object
"""
names = [r.run_id for r in results]
iprec = [[r.results['iprec_at_recall_0.00'],
... | 5,325,749 |
def test_6_1_4_etc_shadow_isfile(host):
"""
CIS Ubuntu 20.04 v1.0.0 - Rule # 6.1.4
Tests if /etc/shadow is a file
"""
assert host.file(ETC_SHADOW).is_file | 5,325,750 |
def plotData(datalist, part = "real", progressive = True, color = None, clip = False, tcutoff = None):
"""Plot real or imaginary parts of a given list of functions.
arguments:
datalist (list of tuples, each tuple of form (xlist,ylist)): data to plot;
xlist should be real numbers, ylist can be comp... | 5,325,751 |
def expand_word_wrap(base_url, name, tokens):
"""Expand the ``word-wrap`` legacy property.
See http://http://www.w3.org/TR/css3-text/#overflow-wrap
"""
keyword = overflow_wrap(tokens)
if keyword is None:
raise InvalidValues
yield 'overflow-wrap', keyword | 5,325,752 |
def train_and_test(model, dataset, robustness_tests=None, base_config_dict=None, save_model=True):
"""
Train a recommendation model and run robustness tests.
Args:
model (str): Name of model to be trained.
dataset (str): Dataset name; must match the dataset's folder name located in 'data_pat... | 5,325,753 |
def total_cost(content_cost, style_cost, alpha, beta):
"""Return a tensor representing the total cost."""
return alpha * content_cost + beta * style_cost | 5,325,754 |
def create_command_using_pip_action(
num_bash_entries=10, uninstall_use_creation_time=False, skip=0):
"""Create commands using latest pip action."""
valid_pip_commands = get_valid_pip_history(num_bash_entries)[skip:]
assert valid_pip_commands, 'No undoable pip commands.'
last_valid_pip_command =... | 5,325,755 |
def extract_word_pos_sequences(form, unknown_category, morpheme_splitter=None, extract_morphemes=False):
"""Return the unique word-based pos sequences, as well as (possibly) the morphemes, implicit in the form.
:param form: a form model object
:param morpheme_splitter: callable that splits a strings into i... | 5,325,756 |
def download_hmi(date: datetime, outdir=None, resolution='1k'):
"""
Downloads hourly HMI files for the date selected if not already
available locally.
"""
if outdir is None:
outdir = pathlib.Path.cwd() / 'solar_images'
else:
outdir = pathlib.Path(outdir)
if not outdir.exists... | 5,325,757 |
def model_test(Py, Px_y, testDataArr, testLabelArr):
"""
模型测试
@Args:
Py: 先验概率分布
Px_y: 条件概率分布
testDataArr: 测试集数据
testLabelArr: 测试集标签
@Returns:
准确率
@Riase:
"""
# 错误值
errorCnt = 0
# 循环遍历测试集中的每一个样本
for i in range(len(testDataArr... | 5,325,758 |
def test_more():
"""Test on more than one file"""
# rv, out = getstatusoutput(f'{prg} {fox} {sonnet}')
expected = (' 1 9 45 ../inputs/fox.txt\n'
' 17 118 661 ../inputs/sonnet-29.txt\n'
' 18 127 706 total')
# assert rv == 0
# as... | 5,325,759 |
def int2c2e(shortname: str, wrapper: LibcintWrapper,
other: Optional[LibcintWrapper] = None) -> torch.Tensor:
"""
2-centre 2-electron integrals where the `wrapper` and `other1` correspond
to the first electron, and `other2` corresponds to another electron.
The returned indices are sorted bas... | 5,325,760 |
def send_group_membership_request(request, group_id, template='group_send_request.html'):
"""
Send membership request to the administrator
of a private group.
"""
if request.method == 'POST':
form = GroupMembershipRequestForm(request.POST)
if form.is_valid():
group = Grou... | 5,325,761 |
def arg_parse():
"""Base all default folders from script location
scripts: ./pymetric/tools/cimis
tools: ./pymetric/tools
output: ./pymetric/cimis
"""
script_folder = sys.path[0]
code_folder = os.path.dirname(script_folder)
project_folder = os.path.dirname(code_folder)
... | 5,325,762 |
def _dataset_type_dir(signer):
"""Returns the directory name of the corresponding dataset type.
There is a `TFRecord` file written for each of the 25 signers. The `TFRecord` files of the first 17 signers are
assigned to the train dataset, the `TFRecord` files of the next 4 signers are assigned to the valid... | 5,325,763 |
def _merge_blanks(src, targ, verbose=False):
"""Read parallel corpus 2 lines at a time.
Merge both sentences if only either source or target has blank 2nd line.
If both have blank 2nd lines, then ignore.
Returns tuple (src_lines, targ_lines), arrays of strings sentences.
"""
merges_done = [] #... | 5,325,764 |
def get_line(file_path, line_rule):
"""
搜索指定文件的指定行到指定行的内容
:param file_path: 指定文件
:param line_rule: 指定行规则
:return:
"""
s_line = int(line_rule.split(',')[0])
e_line = int(line_rule.split(',')[1][:-1])
result = []
# with open(file_path) as file:
file = codecs.open(file_path, "... | 5,325,765 |
def save_with_metadata_temp(metadata, data, dir=None):
"""saves the data and metadata to a csv file at the
end of the test, named "Test_temp.csv" """
if dir == None:
filename = "test_temp.csv"
else:
filename = os.path.join(dir,"test_temp.csv")
emptyrow = []
fieldnames = ... | 5,325,766 |
def dlls_setup(base_address):
"""Find the pattern for loading dynamically DLLs by using LoadLibrary API,
set the name for the retrieved dll.
Args:
base_address -- the address for Oski procsSetup function
"""
"""LoadLibrary pattern
mov eax, aBcryptdll
push e... | 5,325,767 |
def files_in(directory: Path) -> Iterable[Path]:
"""Yields every file that is a descendent of directory."""
try:
for subpath in directory.iterdir():
if subpath.is_dir():
for file_path in files_in(subpath):
yield file_path
else:
yield subpath
except FileNotFoundError:
pass | 5,325,768 |
def _generate_odd_sequence(sequence_id: int, start_value: int,
k_factor: int, max_iterations: int):
"""
This method generates a Collatz sequence containing only odd numbers.
:param sequence_id: ID of the sequence.
:param start_value: The integer value to start with. The value... | 5,325,769 |
def find_initcpio_features(partitions, root_mount_point):
"""
Returns a tuple (hooks, modules, files) needed to support
the given @p partitions (filesystems types, encryption, etc)
in the target.
:param partitions: (from GS)
:param root_mount_point: (from GS)
:return 3-tuple of lists
"... | 5,325,770 |
def _is_unique_rec_name(info_name):
"""
helper method to see if we should use the uniqueness recommendation on the
fact comparison
"""
UNIQUE_INFO_SUFFIXES = [".ipv4_addresses", ".ipv6_addresses", ".mac_address"]
UNIQUE_INFO_PREFIXES = ["fqdn"]
if info_name.startswith("network_interfaces.lo... | 5,325,771 |
def do_volume_create(cs, args):
"""Add a new volume."""
cs.volumes.create(args.size,
args.snapshot_id,
args.display_name,
args.display_description) | 5,325,772 |
def initialized():
"""
Connection finished initializing?
"""
return __context__["netmiko_device"].get("initialized", False) | 5,325,773 |
def n_round(a, b):
"""safe round"""
element_round = np.vectorize(np.round)
return element_round(a, intify(b)) | 5,325,774 |
def send_single (addr, port, data):
"""
Send a single packet
Args:
addr: a string representation of destination address
port: destination port
data: data to be sent
"""
family, sockaddr = get_addr(addr, port)
with create_socket(family) as sock:
send_data(sock, sockaddr, data) | 5,325,775 |
def _json_view_params(shape, affine, vmin, vmax, cut_slices, black_bg=False,
opacity=1, draw_cross=True, annotate=True, title=None,
colorbar=True, value=True):
""" Create a dictionary with all the brainsprite parameters.
Returns: params
"""
# Set color pa... | 5,325,776 |
def get_timestamps_from_df_data(df) -> List[datetime.datetime]:
"""Get a list of timestamp from rows of a DataFrame containing
raw data.
"""
timestamps = []
for index, row in df.iterrows():
year = int(row["dteday"][:4])
month = int(row["dteday"][5:7])
day ... | 5,325,777 |
def list_security_configurations(Marker=None):
"""
Lists all the security configurations visible to this account, providing their creation dates and times, and their names. This call returns a maximum of 50 clusters per call, but returns a marker to track the paging of the cluster list across multiple ListSecur... | 5,325,778 |
def test_enum_symbols_validation__correct(symbol):
"""https://github.com/fastavro/fastavro/issues/551"""
invalid_schema = {
"type": "record",
"name": "my_schema",
"fields": [
{
"name": "enum_field",
"type": {
"name": "my_enu... | 5,325,779 |
def debug_user(request):
"""
Allows superusers to log in as a regular user to troubleshoot problems.
"""
if not settings.DEBUG:
messages.error(request, "Can only use when in debug mode.")
redirect("/")
target = request.GET.get("uid", "")
profile = Profile.objects.filter(uid=tar... | 5,325,780 |
def select(var_name, attr_name=None):
"""
Return attribute(s) of a variable given the variable name and an optional field name, or list of attribute name(s)
:param var_name: Name of the variable we're interested in.
:param attr_name: A string representing the name of the attribute whose value we want to... | 5,325,781 |
def print_last_word(words):
"""Prints the last word after popping it off."""
#prints the last word, or "first negative" word
#think about this as being the word furthest form the top
word = words.pop(-1)
print word | 5,325,782 |
def _parseWinBuildTimings(logfile):
"""Variant of _parseBuildTimings for Windows builds."""
res = {'Compile': re.compile(r'\d+>Time Elapsed (\d+):(\d+):([0-9.]+)'),
'Test running': re.compile(r'.*?\.+.*?([0-9.]+) sec')}
times = dict([(k, 0.0) for k in res])
for line in logfile:
for ke... | 5,325,783 |
def _try_to_extract_issuing_url_from_well_known_metadata(well_known_address: str) -> typing.Optional[str]:
"""
Try to extract token issuing url from well-known location
:param well_known_address: well-known URL
:type well_known_address: str
:return: str or None -- token issuing URL
"""
try:... | 5,325,784 |
def get_malid(anime: AnimeThemeAnime) -> int:
"""
Returns anime theme of resource.
"""
for resource in anime['resources']:
if resource["site"] == "MyAnimeList":
return resource['external_id'] | 5,325,785 |
def wav16khz2mfcc(dir_name):
"""
Loads all *.wav files from directory dir_name (must be 16kHz), converts them into MFCC
features (13 coefficients) and stores them into a dictionary. Keys are the file names
and values and 2D numpy arrays of MFCC features.
"""
features = {}
for f in glob(dir_... | 5,325,786 |
def add_metadata(infile, outfile, sample_metadata):
"""Add sample-level metadata to a biom file. Sample-level metadata
should be in a format akin to
http://qiime.org/tutorials/tutorial.html#mapping-file-tab-delimited-txt
:param infile: String; name of the biom file to which metadata
... | 5,325,787 |
def test_something():
"""
Test function for a method from module package_name.module_name
"""
assert True | 5,325,788 |
def multinomial(n):
"""Finds the multinomial coefficient for a given array of numbers.
Args:
n (list): the interegs to be used.
"""
binomials = [[np.sum(n),n[0]]]
for i in range(1,len(n)):
new_sum = binomials[i-1][0]-binomials[i-1][1]
binomials.append([new_sum,n[i]])
... | 5,325,789 |
def get_qc_data(sample_prj, p_con, s_con, fc_id=None):
"""Get qc data for a project, possibly subset by flowcell.
:param sample_prj: project identifier
:param p_con: object of type <ProjectSummaryConnection>
:param s_con: object of type <SampleRunMetricsConnection>
:returns: dictionary of qc resul... | 5,325,790 |
def sql_sanitize(sql_name):
"""
Return a SQL name (table or column) cleaned of problematic characters.
ex. punctuation )(][; whitespace
Don't use with values, which can be properly escaped with parameterization.
Ideally retaining only alphanumeric char.
Credits: Donald Miner, Source: StackOverfl... | 5,325,791 |
def test_get_portfolio_cash_balance():
"""
Tests get_portfolio_cash_balance method for:
* Raising ValueError if portfolio_id not in keys
* Correctly obtaining the value after cash transfers
"""
start_dt = pd.Timestamp('2017-10-05 08:00:00', tz=pytz.UTC)
exchange = ExchangeMock()
data_han... | 5,325,792 |
def add_event_number(job_metrics, workdir):
"""
Extract event number from file and add to job metrics if it exists
:param job_metrics: job metrics (string).
:param workdir: work directory (string).
:return: updated job metrics (string).
"""
path = os.path.join(workdir, 'eventLoopHeartBeat.... | 5,325,793 |
def exists(name):
"""
`True` if a category named `name` exists;
`False` otherwise.
"""
return db.cursor().execute('SELECT COUNT(*) FROM categories WHERE name = ?', (name,)).fetchone()[0] != 0 | 5,325,794 |
def ESMP_MeshGetOwnedElementCount(mesh):
"""
Preconditions: An ESMP_Mesh has been created.\n
Postconditions: The owned elementCount for 'mesh' has been
returned.\n
Arguments:\n
:RETURN: integer :: elementCount\n
ESMP_Mesh :: mesh\n
"""
lec = ct.c_int(0)... | 5,325,795 |
def remove_control_chars_author(input):
"""
:param input:
:return:
"""
return CONTROL_CHAR_RE.sub('', input) | 5,325,796 |
def publish_pages(name, paths, git_repo, published_repo, extra_message=''):
"""publish helm chart index to github pages"""
version = last_modified_commit(*paths)
checkout_dir = '{}-{}'.format(name, version)
subprocess.check_call([
'git', 'clone', '--no-checkout',
'git@github.com:{}'.form... | 5,325,797 |
def PrintCounts(group):
"""
Print the most common values for each key in a collection of dicts.
This is a (currently unused) utility method for examining the patterns in the
various JSON files, to get a feel for them. It can tell you which fields carry
no data (because they're always set to the same value), ... | 5,325,798 |
def write_version(filename: str = os.path.join(*["airflow", "git_version"])):
"""
Write the Semver version + git hash to file, e.g. ".dev0+2f635dc265e78db6708f59f68e8009abb92c1e65".
:param str filename: Destination file to write
"""
text = "{}".format(git_version(version))
with open(filename, '... | 5,325,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.