content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def log_exception(function):
"""Exception logging wrapper."""
@functools.wraps(function)
def wrapper(*args, **kwargs):
try:
return function(*args, **kwargs)
except:
err = "There was an exception in "
err += function.__name__
logger.exception(e... | 19,600 |
def test_forecast_example_inputs():
"""Note: this test is extremely minimal, and only checks if a solution is
similar to a previous result.
This test may also fail if parallelisation is used (which may be in the
case in MKL versions of numpy), since the order of random number accessing
from differe... | 19,601 |
def calculate_triad_connectivity(tt1, tt2, tt3, ipi1, ipi2, tau_z_pre, tau_z_post,
base_time, base_ipi, resting_time, n_patterns):
"""
This function gives you the connectivity among a triad, assuming that all the other temporal structure outside of
the trial is homogeneus
... | 19,602 |
def random_date_from(date,
min_td=datetime.timedelta(seconds=0),
max_td=datetime.timedelta(seconds=0)):
"""
Produces a datetime at a random offset from date.
Parameters:
date: datetime
The reference datetime.
min_td: timedelta, optional... | 19,603 |
def generate_log_normal_dist_value(frequency, mu, sigma, draws, seed_value):
"""
Generates random values using a lognormal distribution,
given a specific mean (mu) and standard deviation (sigma).
https://stackoverflow.com/questions/51609299/python-np-lognormal-gives-infinite-
results-for-big-average... | 19,604 |
def enableStandardSearchPath( enable = True ):
"""Whether or not the standard search path should be searched. This standard
search path is is by default searched *after* the standard data library,
and is built by concatenating entries in the NCRYSTAL_DATA_PATH
environment variables with entries in... | 19,605 |
def do(args):
""" Main entry point for depends action. """
build_worktree = qibuild.parsers.get_build_worktree(args, verbose=(not args.graph))
project = qibuild.parsers.get_one_build_project(build_worktree, args)
collected_dependencies = get_deps(
build_worktree, project, args.direct, args.runti... | 19,606 |
def test_sign_image_same_image_source(
registry_v2_image_source: RegistryV2ImageSource, image: str
):
"""Test image signing."""
src_image_name = ImageName.parse(image)
dest_image_name = copy.deepcopy(src_image_name)
dest_image_name.tag = "{0}_signed".format(dest_image_name.tag)
def assertions(r... | 19,607 |
def test_definition_list_single_item():
"""A definition list with a single item."""
content = ";Foo : Bar"
wikicode = mwparserfromhell.parse(content)
assert compose(wikicode) == "<dl><dt>Foo </dt><dd> Bar</dd></dl>" | 19,608 |
def auto_regenerate_axes(elements: List[int]) -> None:
"""regenerate element axis system
Args:
elements (List[int]): element IDs
""" | 19,609 |
def compute_mean_field(
grain_index_field,
field_data,
field_name,
vx_size=(1.0, 1.0, 1.0),
weighted=False,
compute_std_dev=False,
):
"""
Compute mean shear system by grains.
Args:
grain_index_field : VTK field containing index
field_data : VTK field... | 19,610 |
def evaluate_argument_value(xpath_or_tagname, datafile):
"""This function takes checks if the given xpath_or_tagname exists in the
datafile and returns its value. Else returns None."""
tree = ET.parse(datafile)
root = tree.getroot()
if xpath_or_tagname.startswith(root.tag + "/"):
xpath_or_ta... | 19,611 |
def test_savings_flexible_user_left_quota():
"""Tests the API endpoint to get left daily purchase quota of flexible product"""
client = Client(key, secret)
response = client.savings_flexible_user_left_quota(productId=1)
response.should.equal(mock_item) | 19,612 |
def update():
"""Update a resource"""
pass | 19,613 |
def normalise_genome_position(x):
"""
Normalise position (circular genome)
"""
x['PositionNorm0'] = np.where(x['Position'] > (x['GenomeLength'] / 2),
(x['GenomeLength'] - x['Position']),
x['Position'])
x['PositionNorm'] = x['... | 19,614 |
def random_address(invalid_data):
"""
Generate Random Address
return: string containing imitation postal address.
"""
fake = Faker(['en_CA']) # localized to Canada
return fake.address().replace('\n',', '), global_valid_data | 19,615 |
def rot_poly(angle, polygon, n):
"""rotate polygon into 2D plane in order to determine if a point exists
within it. The Shapely library uses 2D geometry, so this is done in order
to use it effectively for intersection calculations.
Parameters
----------
angle : float
Euler angle to... | 19,616 |
def bytes_isspace(x: bytes) -> bool:
"""Checks if given bytes object contains only whitespace elements.
Compiling bytes.isspace compiles this function.
This function is only intended to be executed in this compiled form.
Args:
x: The bytes object to examine.
Returns:
Result of che... | 19,617 |
def snake_case(name: str):
"""
https://stackoverflow.com/a/1176023/1371716
"""
name = re.sub('(\\.)', r'_', name)
name = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
name = re.sub('__([A-Z])', r'_\1', name)
name = re.sub('([a-z0-9])([A-Z])', r'\1_\2', name)
return name.lower() | 19,618 |
def generate_aggregate_plots(countries):
"""
Generate a set of visualizing settlement distribution and size.
"""
# all_data = []
for country in countries:
iso3 = country[0]
data = pd.read_csv(os.path.join(RESULTS, iso3, 'aggregate_results.csv'))#[:100]
data['strategy'] ... | 19,619 |
def run():
"""Log in and store credentials"""
args = parse_args()
appname = sys.argv[0]
hostname = platform.node()
codetools.setup_logging(args.debug)
password = ''
if args.token_path is None and args.delete_role is True:
cred_path = os.path.expanduser('~/.sq_github_token_delete'... | 19,620 |
def get_loss_data():
"""
This function returns a list of paths to all .npy loss
files.
Returns
-------
path_list : list of strings
The list of paths to output files
"""
path = "./data/*_loss.npy"
path_list = glob.glob(path, recursive=True)
return path_list | 19,621 |
def autocommit(connection, value):
"""
Set autocommit
:Parameters:
`value` : ``bool``
yes or no?
"""
connection.autocommit(int(bool(value))) | 19,622 |
def ranked_avg_knn_scores(batch_states, memory, k=10, knn=batch_count_scaled_knn):
"""
Computes ranked average KNN score for each element in batch of states
\sum_{i = 1}^{K} (1/i) * d(x, x_i)
Parameters
----------
k: k neighbors
batch_states: numpy array of size [batch_size x state_size]
... | 19,623 |
def export_geopackage(
eopatch,
geopackage_path,
feature,
geometry_column: str = "geometry",
columns: Optional[List[str]] = None,
):
"""A utility function for exporting
:param eopatch: EOPatch to save
:param geopackage_path: Output path where Geopackage will be written.
:param featu... | 19,624 |
def login_exempt(view_func):
"""登录豁免,被此装饰器修饰的action可以不校验登录."""
def wrapped_view(*args, **kwargs):
return view_func(*args, **kwargs)
wrapped_view.login_exempt = True
return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view) | 19,625 |
def to_uint8_image(message : ImageMessage) -> ImageMessage:
"""Convert image type to uint8.
Args:
message (ImageMessage): Image to be converted
Returns:
ImageMessage: Resulting iamge
"""
message.image = np.uint8(message.image*255)
if message.mask is not None:
message.ma... | 19,626 |
def list_zero_alphabet() -> list:
"""Build a list: 0, a, b, c etc."""
score_dirs = ['0']
for char in string.ascii_lowercase:
score_dirs.append(char)
return score_dirs | 19,627 |
def proxy(values=(0,), names=('constant',), types=('int8',)):
""" Create a proxy image with the given values, names and types
:param values: list of values for every band of the resulting image
:type values: list
:param names: list of names
:type names: list
:param types: list of band types. Op... | 19,628 |
def aiff2mp3(infile_path: str) -> None:
"""Convert AIFF to MP3 using lame."""
args = [_LAME_CLT]
args.append(infile_path)
subprocess.run(args) | 19,629 |
def _to_versions(raw_ls_remote_lines, version_join, tag_re, tag_filter_re):
"""Converts raw ls-remote output lines to a sorted (descending)
list of (Version, v_str, git_hash) objects.
This is used for source:git method to find latest version and git hash.
"""
ret = []
for line in raw_ls_remote_lines:
g... | 19,630 |
def arraysum(x: int)->int:
"""
These function gives sum of all elements of list by iterating through loop and adding them.
Input: Integer
Output: Interger
"""
sum = 0
for i in x:
sum += i
return sum | 19,631 |
def get_sensitivity_scores(model, features, top_n):
"""
Finds the sensitivity of each feature in features for model. Returns the top_n
feature names, features_top, alongside the sensitivity values, scores_top.
"""
# Get just the values of features
x_train = features.values
# Apply min max no... | 19,632 |
def mad(data):
"""Median absolute deviation"""
m = np.median(np.abs(data - np.median(data)))
return m | 19,633 |
def test_larger_cases(arg, expected) -> None:
"""Test a few other integers."""
assert fib(arg) == expected | 19,634 |
async def get_intents(current_user: User = Depends(Authentication.get_current_user_and_bot)):
"""
Fetches list of existing intents for particular bot
"""
return Response(data=mongo_processor.get_intents(current_user.get_bot())).dict() | 19,635 |
def pars(f):
"""
>>> list(pars(StringIO('a\nb\nc\n\nd\ne\nf\n')))
[['a\n','b\n','c\n'],['d\n','e\n','f\n']]
"""
par = []
for line in f:
if line == '\n':
yield par
par = []
else:
par.append(line)
if par != []:
yield par | 19,636 |
def launch(result_images, source):
"""
Launch the GUI.
"""
entries = find_failing_tests(result_images, source)
if len(entries) == 0:
print("No failed tests")
sys.exit(0)
app = QtWidgets.QApplication(sys.argv)
dialog = Dialog(entries)
dialog.show()
filter = EventFilt... | 19,637 |
def test_fsp_id_range():
"""
Verify that fsp id is in the range of 1 to 27
"""
fsp_id = 0
with pytest.raises(ValueError):
_ = FSPConfiguration(fsp_id, FSPFunctionMode.CORR, 1, 140, 0)
fsp_id = 28
with pytest.raises(ValueError):
_ = FSPConfiguration(fsp_id, FSPFunctionMode.COR... | 19,638 |
def test_makedirs_with_extant_directories(tmpdir):
"""
``makedirs_exist_ok`` doesn't care if the directories already exist.
"""
d = tmpdir.join('a', 'b', 'c')
d.ensure(dir=True)
files.makedirs_exist_ok(d.strpath)
assert d.exists() | 19,639 |
def open_beneath(
path: Union[AnyStr, "os.PathLike[AnyStr]"],
flags: int,
*,
mode: int = 0o777,
dir_fd: Optional[int] = None,
no_symlinks: bool = False,
remember_parents: bool = False,
audit_func: Optional[Callable[[str, int, AnyStr], None]] = None,
) -> int:
"""
Open a file "ben... | 19,640 |
def train():
"""Train CIFAR-10/100 for a number of steps."""
with tf.Graph().as_default(), tf.device('/cpu:0'):
# Create a variable to count the number of train() calls. This equals the
# number of batches processed * FLAGS.num_gpus.
global_step = tf.get_variable(
'global_ste... | 19,641 |
def find_offset(
ax: Numbers, ay: Numbers, bx: Numbers, by: Numbers, upscale: bool = True
) -> float:
"""Finds value, by which the spectrum should be shifted along x-axis to best
overlap with the first spectrum. If resolution of spectra is not identical,
one of them will be interpolated to match resolut... | 19,642 |
def And(*xs, simplify=True):
"""Expression conjunction (product, AND) operator
If *simplify* is ``True``, return a simplified expression.
"""
xs = [Expression.box(x).node for x in xs]
y = exprnode.and_(*xs)
if simplify:
y = y.simplify()
return _expr(y) | 19,643 |
def test_lif_builtin(rng):
"""Test that the dynamic model approximately matches the rates."""
dt = 1e-3
t_final = 1.0
N = 10
lif = nengo.LIF()
gain, bias = lif.gain_bias(
rng.uniform(80, 100, size=N), rng.uniform(-1, 1, size=N))
x = np.arange(-2, 2, .1).reshape(-1, 1)
J = gain ... | 19,644 |
def get_assignment_submissions(course_id, assignment_id):
""" return a list of submissions for an assignment """
return api.get_list('courses/{}/assignments/{}/submissions'.format(course_id, assignment_id)) | 19,645 |
def send_email(to, content=None, title=None, mail_from=None,
attach=None, cc=None, bcc=None, text=None, html=None, headers=None):
"""
:param to: 收件人,如 'linda@gmail.com' 或 'linda@gmail.com, tom@gmail.com' 或 ['linda@gmail.com, tom@gmail.com']
:param content: 邮件内容,纯文本或HTML str
:param title:... | 19,646 |
def get_abbreviation(res_type, abbr):
"""
Returns abbreviation value from data set
@param res_type: Resource type (html, css, ...)
@type res_type: str
@param abbr: Abbreviation name
@type abbr: str
@return dict, None
"""
return get_settings_resource(res_type, abbr, 'abbreviations') | 19,647 |
def get_stock_list(month_before=12, trade_date='20200410', delta_price=(10, 200), total_mv=50, pe_ttm=(10, 200)):
"""
month_before : 获取n个月之前所有上市公司的股票列表,
默认为获取一年前上市公司股票列表
delta_price :用于剔除掉金额大于delta_price的股票,若为空则不剔除
TIPS : delta_price 和今天的股价进行比较
"""
stock_... | 19,648 |
def dim_axis_label(dimensions, separator=', '):
"""
Returns an axis label for one or more dimensions.
"""
if not isinstance(dimensions, list): dimensions = [dimensions]
return separator.join([d.pprint_label for d in dimensions]) | 19,649 |
def get_random_idx(k: int, size: int) -> np.ndarray:
"""
Get `k` random values of a list of size `size`.
:param k: number or random values
:param size: total number of values
:return: list of `k` random values
"""
return (np.random.rand(k) * size).astype(int) | 19,650 |
def bitmask_8bit(array, pad_value=None):
"""Return 8-bit bitmask for cardinal and diagonal neighbours."""
shape, padded = shape_padded(array, pad_value=pad_value)
cardinals = get_cardinals(shape, padded)
diagonals = get_diagonals(shape, padded)
# TODO: https://forum.unity.com/threads/2d-tile-bitmas... | 19,651 |
def fhir_search_path_meta_info(path: str) -> Union[tuple, NoneType]:
""" """
resource_type = path.split(".")[0]
properties = path.split(".")[1:]
model_cls = resource_type_to_resource_cls(resource_type)
result = None
for prop in properties:
for (
name,
jsname,
... | 19,652 |
def _is_camel_case_ab(s, index):
"""Determine if the index is at 'aB', which is the start of a camel token.
For example, with 'workAt', this function detects 'kA'."""
return index >= 1 and s[index - 1].islower() and s[index].isupper() | 19,653 |
def global_ox_budget(
devstr,
devdir,
devrstdir,
year,
dst='./1yr_benchmark',
is_gchp=False,
overwrite=True,
spcdb_dir=None
):
"""
Main program to compute TransportTracersBenchmark budgets
Arguments:
maindir: str
Top-level ... | 19,654 |
def test_xgb_boston(tmpdir, model_format, objective):
# pylint: disable=too-many-locals
"""Test XGBoost with Boston data (regression)"""
X, y = load_boston(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, shuffle=False)
dtrain = xgb.DMatrix(X_train, label=y_t... | 19,655 |
def create_folder():
"""
This Function Create Empty Folder At Begin
:return:folder status as boolean
"""
folder_flag = 0
list_of_folders = os.listdir(SOURCE_DIR)
for i in ["doc", "image", "output", "font"]:
if i not in list_of_folders:
os.mkdir(i)
folder_flag ... | 19,656 |
def create_bulleted_tool_list(tools):
"""
Helper function that returns a text-based bulleted list of the given tools.
Args:
tools (OrderedDict): The tools whose names (the keys) will be added to the
text-based list.
Returns:
str: A bulleted list of tool names.
"""
r... | 19,657 |
def _c3_merge(sequences, cls, context):
"""Merges MROs in *sequences* to a single MRO using the C3 algorithm.
Adapted from http://www.python.org/download/releases/2.3/mro/.
"""
result = []
while True:
sequences = [s for s in sequences if s] # purge empty sequences
if not sequence... | 19,658 |
def rgb2hex(rgb: tuple) -> str:
"""
Converts RGB tuple format to HEX string
:param rgb:
:return: hex string
"""
return '#%02x%02x%02x' % rgb | 19,659 |
def min_var_portfolio(cov_mat, allow_short=False):
"""
Computes the minimum variance portfolio.
Note: As the variance is not invariant with respect
to leverage, it is not possible to construct non-trivial
market neutral minimum variance portfolios. This is because
the variance approaches zero w... | 19,660 |
def validate(doc,method):
"""checks if the mobile number is unique if email and mobile number are same then it allows to save the customer """
doc.date=datetime.datetime.now()
points_earned=0
points_consumed=0
total_points=0
remaining_points=0
if doc.get("points_table"):
... | 19,661 |
def relu(fd: DahliaFuncDef) -> str:
"""tvm.apache.org/docs/api/python/relay/nn.html#tvm.relay.nn.relu"""
data, res = fd.args[0], fd.dest
num_dims = get_dims(data.comp)
args = data.comp.args
indices = ""
var_name = CHARACTER_I
for _ in range(num_dims):
indices += f'[{var_name}]'
... | 19,662 |
def detect_on_image(img_path, img_is_path=False, threshold=0.5, rect_th=1, text_th=1, text_size=1):
"""
img_path: absolute path, or an RGB tensor.
threshold: determines minimum confidence in order to consider prediction.
img_is_path: toggles if img_path is an absolute path or an RGB tensor.
"""
... | 19,663 |
def base_hillclimb(base_sol: tuple, neighbor_method: str, max_fevals: int, searchspace: Searchspace, all_results, kernel_options, tuning_options, runner, restart=True, randomize=True, order=None):
""" Hillclimbing search until max_fevals is reached or no improvement is found
Base hillclimber that evaluates nei... | 19,664 |
def filter_dates(dates):
"""filter near dates"""
j = 0
while j < len(dates):
date = dates[j]
i = 3
j += 1
while True:
date += timedelta(days=1)
if date in dates:
i += 1
else:
if i > 2:
del... | 19,665 |
def tar_and_gzip(dir, out_path, filter=None, prefix=''):
"""Tar and gzip the given *dir* to a tarball at *out_path*.
If we encounter symlinks, include the actual file, not the symlink.
:type dir: str
:param dir: dir to tar up
:type out_path: str
:param out_path: where to write the tarball too
... | 19,666 |
def biweight_location(a, c=6.0, M=None, axis=None, eps=1e-8):
"""
Copyright (c) 2011-2016, Astropy Developers
Compute the biweight location for an array.
Returns the biweight location for the array elements.
The biweight is a robust statistic for determining the central
location of... | 19,667 |
def update_copy(src, dest):
"""
Possibly copy `src` to `dest`. No copy unless `src` exists.
Copy if `dest` does not exist, or mtime of dest is older than
of `src`.
Returns: None
"""
if os.path.exists(src):
if (not os.path.exists(dest) or
os.path.getmtime(dest) < os.path.... | 19,668 |
def model_21(GPUS = 1):
""" one dense: 3000 """
model = Sequential()
model.add(Convolution3D(60, kernel_size = (3, 3, 3), strides = (1, 1, 1), input_shape = (9, 9, 9, 20))) # 32 output nodes, kernel_size is your moving window, activation function, input shape = auto calculated
model.add(BatchNormalization())
... | 19,669 |
def test_genomic_dup4(test_normalize, genomic_dup4_default,
genomic_dup4_rse_lse, genomic_dup4_free_text_default,
genomic_dup4_free_text_rse_lse):
"""Test that genomic duplication works correctly."""
q = "NC_000020.11:g.(?_30417576)_(31394018_?)dup" # 38
resp = t... | 19,670 |
def strWeekday(
date: str,
target: int,
after: bool = False,
) -> str:
"""
Given a ISO string `date` return the nearest `target` weekday.
**Parameters**
- `date`: The date around which the caller would like target searched.
- `target`: Weekday number as in the `datetime` Standard Libr... | 19,671 |
def main():
"""Main runner
"""
if len(sys.argv) < 2:
exit_with_error("No file or folder specified.")
path = sys.argv[1]
compress_path(path) | 19,672 |
def combine_bincounts_kernelweights(
xcounts, ycounts, gridsize, colx, coly, L, lenkernel, kernelweights, mid, binwidth
):
"""
This function combines the bin counts (xcounts) and bin averages (ycounts) with
kernel weights via a series of direct convolutions. As a result, binned
approximations to X'W... | 19,673 |
def test_z_ratios_theory():
""" Test that the theoretical shear changes properly with redshift"""
nfw_1 = offset_nfw.NFWModel(cosmo, delta=200, rho='rho_c')
base = nfw_1.gamma_theory(1., 1.E14, 4, 0.1, 0.15)
new_z = numpy.linspace(0.15, 1.1, num=20)
new_gamma = nfw_1.gamma_theory(1, 1.E14, 4, 0.1, n... | 19,674 |
def get_icon_for_group(group):
"""Get the icon for an AOVGroup."""
# Group has a custom icon path so use. it.
if group.icon is not None:
return QtGui.QIcon(group.icon)
if isinstance(group, IntrinsicAOVGroup):
return QtGui.QIcon(":ht/rsc/icons/aovs/intrinsic_group.png")
return QtGui... | 19,675 |
def tempdir():
"""Creates and returns a temporary directory, deleting it on exit."""
path = tempfile.mkdtemp(suffix='bbroll')
try:
yield path
finally:
shutil.rmtree(path) | 19,676 |
def close_and_commit(cur, conn):
"""Closes the cursor and connection used to query a db,
also commits the transaction.
Args:
cur (int): the connection used to connect to the db DB_NAME
conn (str): the cursor used to retrieve results from the query
"""
cur.close()
conn.commit()
... | 19,677 |
def listCtdProfilesJson(request):
""" Generates a JSON file containing a list of datasets and their properties. """ | 19,678 |
def kde(ctx, fxyz, design_matrix, use_atomic_descriptors, only_use_species,
prefix, savexyz, savetxt):
"""
Kernel density estimation using the design matrix.
This command function evaluated before the specific ones,
we setup the general stuff here, such as read the files.
"""
if not fxy... | 19,679 |
def unix_to_windows_path(path_to_convert, drive_letter='C'):
"""
For a string representing a POSIX compatible path (usually
starting with either '~' or '/'), returns a string representing an
equivalent Windows compatible path together with a drive letter.
Parameters
----------
path_to_conve... | 19,680 |
def pool_stats(ctx, poolid):
"""Get statistics about a pool"""
ctx.initialize_for_batch()
convoy.fleet.action_pool_stats(
ctx.batch_client, ctx.config, pool_id=poolid) | 19,681 |
def recordview_create_values(
coll_id="testcoll", view_id="testview", update="RecordView", view_uri=None,
view_entity_type="annal:Test_default",
num_fields=4, field3_placement="small:0,12",
extra_field=None, extra_field_uri=None
):
"""
Entity values used when creating a ... | 19,682 |
def calculateZ(f, t2, a0, a1, a2=0, a3=0):
""" given the frequency array and the filter coefficients,
return Z(s) as a np.array()
"""
s = np.array(f)*2*math.pi*1j ####################
z = (1 + s*t2)/(s*(a3*s**3 + a2*s**2 + a1*s + a0))
return z | 19,683 |
def get_team_project_default_permissions(team, project):
"""
Return team role for given project.
"""
perms = get_perms(team, project)
return get_role(perms, project) or "" | 19,684 |
def update_secrets(newsecrets_ldb, secrets_ldb, messagefunc):
"""Update secrets.ldb
:param newsecrets_ldb: An LDB object that is connected to the secrets.ldb
of the reference provision
:param secrets_ldb: An LDB object that is connected to the secrets.ldb
of the updated provision
"""
... | 19,685 |
def readPlistFromResource(path, restype='plst', resid=0):
"""Read plst resource from the resource fork of path.
"""
from Carbon.File import FSRef, FSGetResourceForkName
from Carbon.Files import fsRdPerm
from Carbon import Res
fsRef = FSRef(path)
resNum = Res.FSOpenResourceFile(fsRef, FSGetRe... | 19,686 |
def plot_confusion_matrix(
cm, classes, normalize=False, title="Confusion matrix", cmap=plt.cm.Blues
):
"""Plots a confusion matrix.
Args:
cm (np.array): The confusion matrix array.
classes (list): List wit the classes names.
normalize (bool): Flag to normalize data.
tit... | 19,687 |
def simple_satunet(
input_shape,
kernel=(2, 2),
num_classes=1,
activation="relu",
use_batch_norm=True,
dropout=0.1,
dropout_change_per_layer=0.0,
dropout_type="standard",
use_dropout_on_upsampling=False,
filters=8,
num_layers=4,
strides=(1, 1),
):
"""
Customisabl... | 19,688 |
def fracday2datetime(tdata):
"""
Takes an array of dates given in %Y%m%d.%f format and returns a
corresponding datetime object
"""
dates = [datetime.strptime(str(i).split(".")[0], "%Y%m%d").date()
for i in tdata]
frac_day = [i - np.floor(i) for i in tdata]
ratios = [(Fraction(i)... | 19,689 |
def set_env_variables_permanently_win(key_value_pairs, whole_machine = False):
"""
Similar to os.environ[var_name] = var_value for all pairs provided, but instead of setting the variables in the
current process, sets the environment variables permanently at the os MACHINE level.
NOTE: process must be "... | 19,690 |
def train(ctx, cids, msday, meday, acquired):
"""Trains a random forest model for a set of chip ids
Args:
ctx: spark context
cids (sequence): sequence of chip ids [(x,y), (x1, y1), ...]
msday (int): ordinal day, beginning of training period
meday (int); ordinal day, end of train... | 19,691 |
def leave_out(y, model, path, leave=1, **kwargs):
"""
Parameters
----------
y: test set
model: model fit by training set
leave: how many neurons are left-out
Returns
-------
"""
from scipy.linalg import svd
_, nbin, z_dim = model["mu"].shape
y_dim = y.shape[-1]
#... | 19,692 |
def install():
"""Routine to be run by the win32 installer with the -install switch."""
from IPython.core.release import version
# Get some system constants
prefix = sys.prefix
python = pjoin(prefix, 'python.exe')
# Lookup path to common startmenu ...
ip_start_menu = pjoin(get... | 19,693 |
def flatten(iterable):
"""
Unpacks nested iterables into the root `iterable`.
Examples:
```python
from flashback.iterating import flatten
for item in flatten(["a", ["b", ["c", "d"]], "e"]):
print(item)
#=> "a"
#=> "b"
#=> "c"
#=> "d"
... | 19,694 |
def test_top_level_domains_db_is_loaded():
"""The TLD database should be loaded."""
assert dnstwist.DB_TLD | 19,695 |
def get_file_info(bucket, filename):
"""Returns information about stored file.
Arguments:
bucket: a bucket that contains the file.
filename: path to a file relative to bucket root.
Returns:
FileInfo object or None if no such file.
"""
try:
stat = cloudstorage.stat(
'/%s/%s' % (bucket... | 19,696 |
def generate_tree(depth, max_depth, max_args):
"""Generate tree-like equations.
Args:
depth: current depth of the node, int.
max_depth: maximum depth of the tree, int.
max_args: maximum number of arguments per operator, int.
Returns:
The root node of a tree structure.
"""
if depth < max_dept... | 19,697 |
def create_experiment(body): # noqa: E501
"""create a experiment
instantiate/start experiment # noqa: E501
:param body: Experiment Object
:type body: dict | bytes
:rtype: ApiResponse
"""
if connexion.request.is_json:
req = Experiment.from_dict(connexion.request.get_json()) # noq... | 19,698 |
def test_lookup_capacity():
"""
Unit test.
"""
with pytest.raises(KeyError):
lookup_capacity({}, 'test', 'test', 'test', 'test','test') | 19,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.