content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def sort_files(pool_size, filenames):
""" Sort files by batches using a multiprocessing Pool """
with Pool(pool_size) as pool:
counters = pool.map(sorter, filenames)
with open('sorted_nums.txt','w') as fp:
for i in range(1, MAXINT+1):
count = sum([x.get(str(i)+'\n',0) for x in counters])
if count>0:
fp.write((str(i)+'\n')*count)
print('Sorted') | 33,100 |
def test_find_contiguous_blocks():
""" This tests the find contiguous block function """
first_seq = [1, 2, 3, 4, 6, 6, 6, 7, 8, 10, 20, 10, 100]
assert list(find_contiguous_blocks(first_seq)) == [(1, 4), (6, 8)]
second_seq = [1, 2, 3, 4, 5, 6, 7]
assert list(find_contiguous_blocks(second_seq)) == [(1, 7)] | 33,101 |
def test_len_size():
"""Check length of Time objects and that scalar ones do not have one."""
t = Time(np.arange(50000, 50010), format='mjd', scale='utc')
assert len(t) == 10 and t.size == 10
t1 = Time(np.arange(50000, 50010).reshape(2, 5), format='mjd', scale='utc')
assert len(t1) == 2 and t1.size == 10
# Can have length 1 or length 0 arrays.
t2 = t[:1]
assert len(t2) == 1 and t2.size == 1
t3 = t[:0]
assert len(t3) == 0 and t3.size == 0
# But cannot get length from scalar.
t4 = t[0]
with pytest.raises(TypeError) as err:
len(t4)
# Ensure we're not just getting the old error of
# "object of type 'float' has no len()".
assert 'Time' in str(err) | 33,102 |
def main(args):
"""Main function for lattice arc tagging."""
global LOGGER
LOGGER = utils.get_logger(args.verbose, log_file_name=os.path.join(args.file_list_dir, 'targets-info'))
dst_dir = os.path.join(args.dst_dir, 'target_overlap_{}'.format(args.threshold))
utils.mkdir(dst_dir)
np_conf_dir = os.path.join(args.processed_npz_dir)
ctm_dir = os.path.join(args.ctm_dir)
baseline_dict = load_baseline(args.one_best)
file_list = []
subset_list = ['train.cn.txt', 'cv.cn.txt', 'test.cn.txt']
for subset in subset_list:
file_list.append(os.path.join(args.file_list_dir, subset))
cn_list = []
for cn_subset_file in file_list:
with open(os.path.abspath(cn_subset_file), 'r') as file_in:
for path_to_lat in file_in:
cn_list.append(path_to_lat.strip())
for cn in cn_list:
label(cn, ctm_dir, dst_dir, baseline_dict, np_conf_dir, args.threshold) | 33,103 |
def relabel_sig(sig:BaseSignature, arg_map:TDict[str, str]=None,
new_vararg:str=None, kwarg_map:TDict[str, str]=None,
new_varkwarg:str=None,
output_map:TDict[str, str]=None) -> BaseSigMap:
"""
Given maps along which to rename signature elements, generate a new
signature and an associated signature mapping from the original signature to
the new signature.
"""
arg_map = {} if arg_map is None else arg_map
kwarg_map = {} if kwarg_map is None else kwarg_map
if output_map is not None and (not sig.has_fixed_outputs):
raise ValueError()
output_map = {} if output_map is None else output_map
defaults_key_map = {**arg_map, **kwarg_map}
ord_args = [(arg_map[name], tp) for name, tp in sig.ord_poskw]
vararg = None if sig.vararg is None else (new_vararg, sig.vararg[1])
kwargs = {kwarg_map[name]: tp for name, tp in sig.kw.items()}
varkwarg = None if sig.varkwarg is None else (new_varkwarg, sig.varkwarg[1])
if sig.has_fixed_outputs:
ord_outputs = [(output_map[name], tp) for name, tp in sig.ord_outputs]
fixed_outputs = True
else:
ord_outputs = None
fixed_outputs = False
defaults = {defaults_key_map[k]: v for k, v in sig.defaults.items()}
renamed_sig = Signature(
ord_poskw=ord_args, kw=kwargs,
ord_outputs=ord_outputs, vararg=vararg,
varkwarg=varkwarg, defaults=defaults,
fixed_outputs=fixed_outputs
)
sig_map = SigMap(source=sig, target=renamed_sig, kwarg_map=kwarg_map)
return sig_map | 33,104 |
def inferred_batch_shape_tensor(batch_object,
bijector_x_event_ndims=None,
**parameter_kwargs):
"""Infers an object's batch shape from its parameters.
Each parameter contributes a batch shape of
`base_shape(parameter)[:-event_ndims(parameter)]`, where a parameter's
`base_shape` is its batch shape if it defines one (e.g., if it is a
Distribution, LinearOperator, etc.), and its Tensor shape otherwise,
and `event_ndims` is as annotated by
`batch_object.parameter_properties()[parameter_name].event_ndims`.
Parameters with structured batch shape
(in particular, non-autobatched JointDistributions) are not currently
supported.
Args:
batch_object: Python object, typically a `tfd.Distribution` or
`tfb.Bijector`. This must implement the method
`batched_object.parameter_properties()` and expose a dict
`batched_object.parameters` of the parameters passed to its constructor.
bijector_x_event_ndims: If `batch_object` is a bijector, this is the
(structure of) integer(s) value of `x_event_ndims` in the current context
(for example, as passed to `experimental_batch_shape`). Otherwise, this
argument should be `None`.
Default value: `None`.
**parameter_kwargs: Optional keyword arguments overriding parameter values
in `batch_object.parameters`. Typically this is used to avoid multiple
Tensor conversions of the same value.
Returns:
batch_shape_tensor: `Tensor` broadcast batch shape of all parameters.
"""
batch_shapes = map_fn_over_parameters_with_event_ndims(
batch_object,
get_batch_shape_tensor_part,
bijector_x_event_ndims=bijector_x_event_ndims,
require_static=False,
**parameter_kwargs)
return functools.reduce(ps.broadcast_shape, tf.nest.flatten(batch_shapes), []) | 33,105 |
def fsevent_log(self, event_id_status_message):
"""Amend filesystem event history with a logging message
"""
event_id = event_id_status_message[0]
status = event_id_status_message[1]
message = event_id_status_message[2]
dbc = db_collection()
history_entry = {
'state': fsevents.UPDATED,
'message': message,
'timestamp': datetime.datetime.now()
}
dbc.update_one({'id': event_id}, {'$push': {
'history': history_entry
}},
upsert=True)
return (event_id, status) | 33,106 |
def fetch_synthetic_2d(lags=0):
"""
Build synthetic 2d data.
Parameters
----------
lags : int, optional
If greater than 0 it's added time dependence.
The default is 0.
Returns
-------
data : numpy.ndarray, shape=(3000, 2)
Synthetic data.
"""
seed = 98
np.random.seed(seed)
mu_1, mu_2 = 1, 30
sigma_1, sigma_2 = 3, 1
num_samples = 3000
changes = {'incip': [
{'add': 50, 'where': (1000, 1300)},
{'add': 0, 'where': (1300, 1600)},
{'add': -50, 'where': (1600, 1650)}
],
'sudden': [
{'add': -50, 'where': (2000, 2200)}
]
}
labels = np.ones(num_samples, dtype=np.uint8)
labels[1070:1250] = 2
labels[1250:1602] = 3
labels[1602:1640] = 2
labels[2000:2200] = 4
x_1, x_2 = build_2d_gauss_data(mu_1, mu_2, sigma_1, sigma_2,
samples=num_samples, changes=changes,
alpha=0.15, w=10, lags=lags)
return np.c_[np.arange(1, 3001), x_1, x_2, labels] | 33,107 |
def prepare_data() -> tuple:
"""Do the whole data preparation - incl. data conversion and test/train split.
Returns:
tuple: (X_train, y_train, X_test, y_test)
"""
(data, labels) = get_data()
from sklearn.preprocessing import MultiLabelBinarizer
mlb = MultiLabelBinarizer()
mlb.fit(labels)
y = mlb.transform(labels)
# read and decode images
images = [tf.io.read_file(path).numpy() for path in data.image]
print("images read")
# create an empty array to allocate storage --> much faster than converting a list into a numpy-array using np.array(...)
X = np.zeros(shape=(len(images), 60, 80, 3))
for i in range(len(images)):
# pass encoded images into X
X[i] = (decode_img(images[i], 60, 80))
print("images decoded")
# split data into training and test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42)
print("Data prep finished")
return (X_train, y_train, X_test, y_test) | 33,108 |
def current_url_name(request):
"""
Adds the name for the matched url pattern for the current request to the
request context.
"""
try:
match = resolve(request.path)
url_name = match.url_name
except Http404:
url_name = None
return {
'current_url_name': url_name
} | 33,109 |
def get_crypto_key():
"""Shows your crypto key"""
key = load_key()
if key:
click.secho("your actual crypto key:", fg = "blue")
return click.echo(load_key()) | 33,110 |
def get_entropies(data: pd.DataFrame):
"""
Compute entropies for words in wide-format df
"""
counts = pd.DataFrame(apply_count_values(
data.to_numpy(copy=True)), columns=data.columns)
probs = (counts / counts.sum(axis=0)).replace(0, np.nan)
nplogp = -probs * np.log2(probs)
return nplogp.sum() | 33,111 |
def create_dataset(dataset_path,
do_train,
image_size=224,
interpolation='BILINEAR',
crop_min=0.05,
repeat_num=1,
batch_size=32,
num_workers=12,
autoaugment=False,
mixup=0.0,
num_classes=1001):
"""create_dataset"""
if hasattr(Inter, interpolation):
interpolation = getattr(Inter, interpolation)
else:
interpolation = Inter.BILINEAR
print('cannot find interpolation_type: {}, use {} instead'.format(interpolation, 'BILINEAR'))
device_num = int(os.getenv("RANK_SIZE", '1'))
rank_id = int(os.getenv('RANK_ID', '0'))
if do_train:
ds = de.ImageFolderDataset(dataset_path, num_parallel_workers=num_workers, shuffle=True,
num_shards=device_num, shard_id=rank_id)
else:
batch_per_step = batch_size * device_num
print("eval batch per step: {}".format(batch_per_step))
if batch_per_step < 50000:
if 50000 % batch_per_step == 0:
num_padded = 0
else:
num_padded = batch_per_step - (50000 % batch_per_step)
else:
num_padded = batch_per_step - 50000
print("eval dataset num_padded: {}".format(num_padded))
if num_padded != 0:
# padded_with_decode
white_io = BytesIO()
Image.new('RGB', (image_size, image_size), (255, 255, 255)).save(white_io, 'JPEG')
padded_sample = {
'image': np.array(bytearray(white_io.getvalue()), dtype='uint8'),
'label': np.array(-1, np.int32)
}
sample = [padded_sample for x in range(num_padded)]
ds_pad = de.PaddedDataset(sample)
ds_imagefolder = de.ImageFolderDataset(dataset_path, num_parallel_workers=num_workers)
ds = ds_pad + ds_imagefolder
distribute_sampler = de.DistributedSampler(num_shards=device_num, shard_id=rank_id, \
shuffle=False, num_samples=None)
ds.use_sampler(distribute_sampler)
else:
ds = de.ImageFolderDataset(dataset_path, num_parallel_workers=num_workers, \
shuffle=False, num_shards=device_num, shard_id=rank_id)
print("eval dataset size: {}".format(ds.get_dataset_size()))
mean = [0.485*255, 0.456*255, 0.406*255]
std = [0.229*255, 0.224*255, 0.225*255]
# define map operations
if do_train:
trans = [
C.RandomCropDecodeResize(image_size, scale=(crop_min, 1.0), \
ratio=(0.75, 1.333), interpolation=interpolation),
C.RandomHorizontalFlip(prob=0.5),
]
if autoaugment:
trans += [
P.ToPIL(),
ImageNetPolicy(),
ToNumpy(),
]
trans += [
C.Normalize(mean=mean, std=std),
C.HWC2CHW(),
]
else:
resize = int(int(image_size / 0.875 / 16 + 0.5) * 16)
print('eval, resize:{}'.format(resize))
trans = [
C.Decode(),
C.Resize(resize, interpolation=interpolation),
C.CenterCrop(image_size),
C.Normalize(mean=mean, std=std),
C.HWC2CHW()
]
type_cast_op = C2.TypeCast(ms.int32)
ds = ds.repeat(repeat_num)
ds = ds.map(input_columns="image", num_parallel_workers=num_workers, operations=trans, python_multiprocessing=True)
ds = ds.map(input_columns="label", num_parallel_workers=num_workers, operations=type_cast_op)
if do_train and mixup > 0:
one_hot_encode = C2.OneHot(num_classes)
ds = ds.map(operations=one_hot_encode, input_columns=["label"])
ds = ds.batch(batch_size, drop_remainder=True)
if do_train and mixup > 0:
trans_mixup = C.MixUpBatch(alpha=mixup)
ds = ds.map(input_columns=["image", "label"], num_parallel_workers=num_workers, operations=trans_mixup)
return ds | 33,112 |
def _numeric_adjust_widgets(caption: str, min: float, max: float) -> HBox:
"""Return a HBox with a label, a text box and a linked slider."""
label = Label(value=caption)
text = BoundedFloatText(min=min, max=max, layout=wealth.plot.text_layout)
slider = FloatSlider(readout=False, min=min, max=max)
widgets.jslink((text, "value"), (slider, "value"))
box = HBox([label, text, slider])
return box | 33,113 |
def test_show_help(capsys):
"""
Shows help.
Arguments:
capsys: Pytest fixture to capture output.
"""
with pytest.raises(SystemExit):
cli.review(["-h"])
captured = capsys.readouterr()
assert "review" in captured.out | 33,114 |
def project_assignments():
"""
Generator that will provide all of the assignments that a user has
:return:
"""
current_page = 1
while True:
assignment_data = harvest.current_assignments(current_page)
for project_assignment in assignment_data['project_assignments']:
yield project_assignment
current_page = assignment_data['next_page']
if current_page is None:
break | 33,115 |
def visualize_stft(eeg_data,fs,title,ax,showPlot=False):
"""
eeg_data: (time_steps,channels)
averages over all frequency spectrums
"""
if not ax:
fig = plt.figure()
ax = fig.gca()
showPlot=True
else:
fig = ax.get_figure()
eeg_fft = fftpack.fft(eeg_data,axis=0)
Tmess = eeg_data.shape[0]/fs
print(Tmess,type(fs))
frequency_axis = np.arange(0,fs/2,1/Tmess)
print('frq ax:',1/Tmess,frequency_axis.shape,np.abs(eeg_data.mean(axis=-1)).shape,np.arange(-fs/2,fs/2,1/Tmess))
#frequency_axis/=fs
ax.plot(frequency_axis,2/eeg_data.shape[0]*np.abs(eeg_fft.mean(axis=-1)[:eeg_data.shape[0]//2]))
ax.set_title(title)
if showPlot:
fig.tight_layout()
fig.show() | 33,116 |
def evaluate(benchmark, solution):
"""Evaluate the solution against the benchmark."""
# Get test data
root = os.path.dirname(__file__)
path = os.path.join(root, "../../task/regression/data/{}_test.csv".format(benchmark))
df_test = pd.read_csv(path, header=None)
X = df_test.values[:, :-1].T # X values are the same for noisy/noiseless
y_test = df_test.values[:, -1]
var_y_test = np.var(y_test)
# Get noiseless test data
if "_n" in benchmark and "_d" in benchmark:
noise_str = benchmark.split('_')[1]
benchmark_noiseless = benchmark.replace(noise_str, "n0.00")
path = os.path.join(root, "../../task/regression/data/{}_test.csv".format(benchmark_noiseless))
df_test_noiseless = pd.read_csv(path, header=None)
y_test_noiseless = df_test_noiseless.values[:, -1]
var_y_test_noiseless = np.var(y_test_noiseless)
else:
y_test_noiseless = y_test
var_y_test_noiseless = var_y_test
# Parse solution as sympy expression
inputs = ["x{}".format(i+1) for i in range(X.shape[0])]
solution = solution.replace("^", "**")
f_hat = lambdify(inputs, solution, "numpy")
# Compare against test data
y_hat = f_hat(*X)
nmse_test = np.mean((y_test - y_hat)**2) / var_y_test
nmse_test_noiseless = np.mean((y_test_noiseless - y_hat)**2) / var_y_test_noiseless
success = nmse_test_noiseless < THRESHOLD
return nmse_test, nmse_test_noiseless, success | 33,117 |
def where_handle(tokens):
"""Process where statements."""
internal_assert(len(tokens) == 2, "invalid where statement tokens", tokens)
final_stmt, init_stmts = tokens
return "".join(init_stmts) + final_stmt + "\n" | 33,118 |
def plot_figure(ms_label, ms_counts, left, right, params_dict, save_directory):
"""
'ms_label' mass shift in string format.
'ms_counts' entries in a mass shift.
'left
"""
#figure parameters
b = 0.2 # shift in bar plots
width = 0.4 # for bar plots
labels = params_dict['labels']
distributions = left[0]
errors = left[1]
# print(right)
bar_plot, bar_left = plt.subplots()
bar_plot.set_size_inches(params_dict['figsize'])
# print(np.arange(b, 2*len(labels), 2), len(np.arange(b, 2*len(labels), 2)))
# print(distributions.loc[labels,ms_label], len(distributions.loc[labels,ms_label]))
bar_left.bar(np.arange(b, 2 * len(labels), 2), distributions.loc[labels,ms_label],
yerr=errors.loc[labels], width=width, color=colors[2], linewidth=0,
label=ms_label+' Da mass shift,\n'+str(ms_counts)+' peptides')
bar_left.set_ylabel('Relative AA abundance', color=colors[2])
bar_left.set_xticks(np.arange(2 * b , 2 * len(labels) + 2 * b, 2))#
bar_left.set_xticklabels(labels)
bar_left.hlines(1, -1, 2* len(labels), linestyles='dashed', color=colors[3])
bar_right = bar_left.twinx()
bar_right.bar(np.arange(4 * b, 2 * len(labels) + 4 * b, 2),right, width=width, linewidth=0, color=colors[0])
bar_right.set_ylim(0,125)
bar_right.set_yticks(np.arange(0,120, 20))
bar_right.set_ylabel('Peptides with AA, %', color=colors[0])
bar_left.spines['left'].set_color(colors[2])
bar_right.spines['left'].set_color(colors[2])
bar_left.spines['right'].set_color(colors[0])
bar_right.spines['right'].set_color(colors[0])
bar_left.tick_params('y', colors=colors[2])
bar_right.tick_params('y', colors=colors[0])
bar_right.annotate(ms_label + ' Da mass shift,' + '\n' + str(ms_counts) +' peptides',
xy=(29,107), bbox=dict(boxstyle='round',fc='w', edgecolor='dimgrey'))
bar_left.set_xlim(-3*b, 2*len(labels)-2 +9*b)
bar_left.set_ylim(0,distributions.loc[labels, ms_label].max()*1.3)
bar_plot.savefig(os.path.join(save_directory, ms_label + '.png'), dpi=500)
bar_plot.savefig(os.path.join(save_directory, ms_label + '.svg'))
plt.close() | 33,119 |
def nltk_ngram_pos_tagger(input_dict):
"""
A tagger that chooses a token's tag based on its word string and
on the preceding n word's tags. In particular, a tuple
(tags[i-n:i-1], words[i]) is looked up in a table, and the
corresponding tag is returned. N-gram taggers are typically
trained on a tagged corpus.
Train a new NgramTagger using the given training data or
the supplied model. In particular, construct a new tagger
whose table maps from each context (tag[i-n:i-1], word[i])
to the most frequent tag for that context. But exclude any
contexts that are already tagged perfectly by the backoff
tagger.
:param training_corpus: A tagged corpus included with NLTK, such as treebank, brown, cess_esp, floresta,
or an Annotated Document Corpus in the standard TextFlows' adc format
:param backoff_tagger: A backoff tagger, to be used by the new
tagger if it encounters an unknown context.
:param cutoff: If the most likely tag for a context occurs
fewer than *cutoff* times, then exclude it from the
context-to-tag table for the new tagger.
:param n: N-gram is a contiguous sequence of n items from a given sequence of text or speech.
:returns pos_tagger: A python dictionary containing the POS tagger object and its arguments.
"""
chunk = input_dict['training_corpus']['chunk']
corpus = input_dict['training_corpus']['corpus']
training_corpus=corpus_reader(corpus, chunk)
backoff_tagger=input_dict['backoff_tagger']['object'] if input_dict['backoff_tagger'] else DefaultTagger('-None-')
n=int(input_dict['n']) #default 2
cutoff=int(input_dict['cutoff']) #default 0
return {'pos_tagger': {
'function':'tag_sents',
'object': NgramTagger(n, train=training_corpus, model=None,
backoff=backoff_tagger, cutoff=0)
}
} | 33,120 |
def pkg(root,
version,
output,
identifier=CONFIG['pkgid'],
install_location='/',
sign=CONFIG['sign_cert_cn'],
ownership='recommended'
):
"""
Create a package.
Most of the input parameters should be recognizable for most admins.
`output` is the path so make sure and attach the pkg extension.
Return:
The exit code from pkgbuild. If non-zero an error has occurred
"""
cmd = ['/usr/bin/pkgbuild', '--root', root,
'--install-location', install_location,
'--identifier', identifier,
'--version', version,
'--ownership', ownership]
# When sign_cert_cn are passed we should sign the package
if sign:
cmd.append('--sign')
cmd.append(sign)
# Always append the output path so signing will work
cmd.append(output)
print(cmd)
proc = subprocess.Popen(cmd, shell=False, bufsize=-1,
stdin=subprocess.PIPE,
stdout=sys.stdout, stderr=subprocess.PIPE)
(output, dummy_error) = proc.communicate()
return proc.returncode | 33,121 |
def remove_app(INSTALLED_APPS, app):
""" remove app from installed_apps """
if app in INSTALLED_APPS:
apps = list(INSTALLED_APPS)
apps.remove(app)
return tuple(apps)
return INSTALLED_APPS | 33,122 |
def get_feature(cluster, sample, i):
"""Turn a cluster into a biopython SeqFeature."""
qualifiers = OrderedDict(ID="%s_%d" % (sample, i))
for attr in cluster.exportable:
qualifiers[attr] = getattr(cluster, attr.lower())
feature = SeqFeature(FeatureLocation(cluster.start, cluster.end), type=cluster.type, strand=1, qualifiers=qualifiers)
if cluster.feature_args:
seqfeature_args = cluster.feature_args
base_args = {'location': FeatureLocation(cluster.start, cluster.end), 'strand': 1}
subfeatures = []
for feature_args in seqfeature_args:
feature_args = feature_args.to_feature_args()
args = base_args.copy()
args.update(feature_args)
subfeatures.append(SeqFeature(**args))
feature.sub_features = subfeatures
return cluster.tid, feature | 33,123 |
def loss(Y, spectra, beta, Yval, val_spec):
"""
Description
-----------
Calculate the loss for a specfic set of beta values
Parameters
----------
Y: labels (0 or 1)
spectra: flux values
beta: beta values
Yval: validation set labels (0 or 1)
val_spec: validation flux values
Returns
-------
J_sum: total loss calculated from all spectra
beta_gradients: gradients for each beat value
J_sum_val: validation loss calaculated from all validation spectra
"""
J_total = []
i = 0
while i < len(Y):
#do logistic regression
sum_p = param_sum(spectra[i],beta)
lr = log_reg(sum_p)
#deal with log(0) cases
if (lr == 1 and Y[i] == 0) or (lr == 0 and Y[i] == 1):
J_iter = 1e+30
else:
J_iter = (-Y[i]*np.log(lr)) - ((1-Y[i])*np.log(1-lr))
J_total.append(J_iter)
i += 1
J_sum = (1/len(Y))*np.sum(J_total)
J_total_val = []
#validation
i = 0
while i < len(Yval):
sum_p_val = param_sum(val_spec[i],beta)
lr_val = log_reg(sum_p_val)
if (lr_val == 1 and Yval[i] == 0) or (lr_val == 0 and Yval[i] == 1):
J_iter_val = 1e+30
else:
J_iter_val = (-Yval[i]*np.log(lr_val)) - ((1-Yval[i])*np.log(1-lr_val))
J_total_val.append(J_iter_val)
i += 1
J_sum_val = (1/len(Yval))*np.sum(J_total_val)
#shuffle the data for SGD
Y, spectra = unison_shuffled_copies(Y, spectra)
#select subset of data
batch = 100
Y_batch = Y[0:batch]
spectra_batch = spectra[0:batch]
beta_gradients = np.zeros(len(beta))
i = 0
#calculate gradients
while i < len(Y_batch):
sum_p = param_sum(spectra_batch[i],beta)
for j in range(len(beta)):
if j == 0:
beta_gradients[j] += gradient1(Y_batch[i], sum_p)
else:
beta_gradients[j] += gradient2(Y_batch[i], spectra_batch[i][j-1], sum_p)
i += 1
return J_sum, beta_gradients, J_sum_val | 33,124 |
def video_detail_except():
"""取得channelPlayListItem/videoDetail兩表video_id的差集
Returns:
[list]: [目前尚未儲存詳細資料的影片ID]
"""
playlist_id = get_db_ChannelPlayListItem_video_id()
video_detail_id = get_db_VideoDetail_video_id()
if video_detail_id and playlist_id:
filter_video = list(set(playlist_id).difference(set(video_detail_id)))
return filter_video
return False | 33,125 |
def nodes(xmrs):
"""Return the list of Nodes for *xmrs*."""
nodes = []
_props = xmrs.properties
varsplit = sort_vid_split
for p in xmrs.eps():
sortinfo = None
iv = p.intrinsic_variable
if iv is not None:
sort, _ = varsplit(iv)
sortinfo = _props(iv)
sortinfo[CVARSORT] = sort
nodes.append(
Node(p.nodeid, p.pred, sortinfo, p.lnk, p.surface, p.base, p.carg)
)
return nodes | 33,126 |
def get_figure(a=None, e=None, scale=10):
""" Creates the desired figure setup:
1) Maximize Figure
2) Create 3D Plotting Environment
3) Rotate Z axis label so it is upright
4) Let labels
5) Increase label font size
6) Rotate camera to ideal (predetermined) angle """
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rcParams["savefig.directory"] = "."
fig = plt.figure()
fig.set_size_inches(1920/1080*scale, scale)
ax = fig.add_subplot(111, projection='3d')
ax.zaxis.set_rotate_label(False) # disable automatic rotation, otherwise you can't manually override
ax.xaxis._axinfo['label']['space_factor'] = 6.8
ax.yaxis._axinfo['label']['space_factor'] = 4.8
ax.zaxis._axinfo['label']['space_factor'] = 4.8
ax.view_init(azim=a, elev=e)
return fig, ax | 33,127 |
def plot_metric(history, metric="loss", ylim=None, start_epoch=0):
"""Plot the given metric from a Keras history
Parameters
----------
history : tf.keras.callbacks.History
History object obtained from training
metric : str, optional
Metric monitored in training, by default 'loss'
ylim : tuple of numbers, optional
Use to set the y-axis limits, by default None
start_epoch : int, optional
The epoch at which to start plotting. Useful if plots have large
values for the first few epochs that render analysis of later epochs
impossible, by default 0
"""
# Define plot attrs here as we modify metric later
title = f"{metric.title()} - Training and Validation"
ylabel = f"{metric.title()}"
is_one_minus_metric = False
if metric.startswith("1-"):
# i.e. we calculate and plot 1 - metric rather than just metric
is_one_minus_metric = True
metric = metric[2:]
metric = metric.lower()
fig, ax = plt.subplots()
num_epochs_trained = len(history.history[metric])
epochs = range(1, num_epochs_trained + 1)
values = history.history[metric]
val_values = history.history[f"val_{metric}"]
if is_one_minus_metric:
values = 1 - np.array(values)
val_values = 1 - np.array(val_values)
ax.plot(epochs[start_epoch:], values[start_epoch:], "b", label="Training")
ax.plot(epochs[start_epoch:], val_values[start_epoch:], "r", label="Validation")
ax.set(title=title, xlabel="Epoch", ylabel=ylabel, ylim=ylim)
ax.legend()
wandb.log({title: wandb.Image(fig)})
plt.show() | 33,128 |
def get_data_loader(transformed_data, is_training_data=True):
"""
Creates and returns a data loader from transformed_data
"""
return torch.utils.data.DataLoader(transformed_data, batch_size=50, shuffle=True) if is_training_data else torch.utils.data.DataLoader(transformed_data, batch_size=50) | 33,129 |
def resolve_authconfig(authconfig, registry=None):
"""
Returns the authentication data from the given auth configuration for a
specific registry. As with the Docker client, legacy entries in the config
with full URLs are stripped down to hostnames before checking for a match.
Returns None if no match was found.
"""
if 'credsStore' in authconfig:
log.debug(
'Using credentials store "{0}"'.format(authconfig['credsStore'])
)
return _resolve_authconfig_credstore(
authconfig, registry, authconfig['credsStore']
)
# Default to the public index server
registry = resolve_index_name(registry) if registry else INDEX_NAME
log.debug("Looking for auth entry for {0}".format(repr(registry)))
if registry in authconfig:
log.debug("Found {0}".format(repr(registry)))
return authconfig[registry]
for key, config in six.iteritems(authconfig):
if resolve_index_name(key) == registry:
log.debug("Found {0}".format(repr(key)))
return config
log.debug("No entry found")
return None | 33,130 |
def structured_rand_arr(size, sample_func=np.random.random,
ltfac=None, utfac=None, fill_diag=None):
"""Make a structured random 2-d array of shape (size,size).
If no optional arguments are given, a symmetric array is returned.
Parameters
----------
size : int
Determines the shape of the output array: (size,size).
sample_func : function, optional.
Must be a function which when called with a 2-tuple of ints, returns a
2-d array of that shape. By default, np.random.random is used, but any
other sampling function can be used as long as it matches this API.
utfac : float, optional
Multiplicative factor for the upper triangular part of the matrix.
ltfac : float, optional
Multiplicative factor for the lower triangular part of the matrix.
fill_diag : float, optional
If given, use this value to fill in the diagonal. Otherwise the diagonal
will contain random elements.
Examples
--------
>>> np.random.seed(0) # for doctesting
>>> np.set_printoptions(precision=4) # for doctesting
>>> structured_rand_arr(4)
array([[ 0.5488, 0.7152, 0.6028, 0.5449],
[ 0.7152, 0.6459, 0.4376, 0.8918],
[ 0.6028, 0.4376, 0.7917, 0.5289],
[ 0.5449, 0.8918, 0.5289, 0.0871]])
>>> structured_rand_arr(4,ltfac=-10,utfac=10,fill_diag=0.5)
array([[ 0.5 , 8.3262, 7.7816, 8.7001],
[-8.3262, 0.5 , 4.6148, 7.8053],
[-7.7816, -4.6148, 0.5 , 9.4467],
[-8.7001, -7.8053, -9.4467, 0.5 ]])
"""
# Make a random array from the given sampling function
rmat = sample_func((size,size))
# And the empty one we'll then fill in to return
out = np.empty_like(rmat)
# Extract indices for upper-triangle, lower-triangle and diagonal
uidx = triu_indices(size,1)
lidx = tril_indices(size,-1)
didx = diag_indices(size)
# Extract each part from the original and copy it to the output, possibly
# applying multiplicative factors. We check the factors instead of
# defaulting to 1.0 to avoid unnecessary floating point multiplications
# which could be noticeable for very large sizes.
if utfac:
out[uidx] = utfac * rmat[uidx]
else:
out[uidx] = rmat[uidx]
if ltfac:
out[lidx] = ltfac * rmat.T[lidx]
else:
out[lidx] = rmat.T[lidx]
# If fill_diag was provided, use it; otherwise take the values in the
# diagonal from the original random array.
if fill_diag is not None:
out[didx] = fill_diag
else:
out[didx] = rmat[didx]
return out | 33,131 |
def dell_apply_bios_settings(url=None):
"""
Apply BIOS settings found at the given URL
:param url: Full URL to the BIOS file
"""
# TODO: Implement this
assert url
raise NotImplementedError | 33,132 |
def test_show_retrieve_all():
"""Testing for :py:meth:`wwdtm.show.Show.retrieve_all`
"""
show = Show(connect_dict=get_connect_dict())
shows = show.retrieve_all()
assert shows, "No shows could be retrieved"
assert "id" in shows[0], "No Show ID returned for the first list item" | 33,133 |
def append_empty_args(func):
"""To use to transform an ingress function that only returns kwargs to one that
returns the normal form of ingress functions: ((), kwargs)"""
@wraps(func)
def _func(*args, **kwargs):
return (), func(*args, **kwargs)
return _func | 33,134 |
def cron_start(instant: bool = True):
"""Start the crontab.
"""
if queue.crontab:
print('Crontab already exists.')
return
now = datetime.now()
cmd = (
"bash -c 'source $HOME/.bashrc; {cmd} cron:run {opt}' >> {log} 2>&1"
.format(
cmd=sys.argv[0],
log=log,
opt=('--dir=' + params['homedir']) if params['homedir'] else '',
)
)
crontab = CronTab(user=True)
cronjob = crontab.new(
command=cmd,
comment=f'Auto created by {__name__} on {now.isoformat()}',
)
if system == 'Darwin' or system == 'Linux':
cronjob.every(1).days()
now = now - timedelta(0, 60+now.second) # subtract a minute
if instant:
now += timedelta(0, 120)
cronjob.hour.on(now.hour)
cronjob.minute.on(now.minute)
else:
print('crontab does not work in Windows.')
return
cronjob.enable()
crontab.write()
queue.crontab = str(crontab)
queue.write_lock()
print('Crontab added.')
cron_info() | 33,135 |
def gateway(job, app, tool, user, user_email):
"""
Function to specify the destination for a job. At present this is exactly the same
as using dynamic_dtd with tool_destinations.yml but can be extended to more complex
mapping such as limiting resources based on user group or selecting destinations
based on queue size.
Arguments to this function can include app, job, job_id, job_wrapper, tool, tool_id,
user, user_email (see https://docs.galaxyproject.org/en/latest/admin/jobs.html)
"""
if user_email in user_destinations.keys():
if hasattr(tool, 'id') and isinstance(tool.id, str) and tool.id.startswith('toolshed'): # map shed tools only
return user_destinations[user_email]
if user:
user_roles = [role.name for role in user.all_roles() if not role.deleted]
# If any of these are prefixed with 'training-'
if any([role.startswith('training-') for role in user_roles]):
# Then they are a training user, we will send their jobs to pulsar,
# Or give them extra resources
if hasattr(tool, 'id') and isinstance(tool.id, str) and tool.id.startswith('toolshed') and tool.id.split('/')[-2] in pulsar_list:
return app.job_config.get_destination('pulsar_destination')
else:
return app.job_config.get_destination('slurm_dest')
destination = map_tool_to_destination(job, app, tool, user_email, path=TOOL_DESTINATION_PATH)
return destination | 33,136 |
def process_command_line():
"""
Return a 1-tuple: (args list).
`argv` is a list of arguments, or `None` for ``sys.argv[1:]``.
"""
parser = argparse.ArgumentParser(description='usage') # add description
# positional arguments
parser.add_argument('d1s', metavar='domain1-source', type=str, help='domain 1 source')
parser.add_argument('d1t', metavar='domain1-target', type=str, help='domain 1 target')
parser.add_argument('d2s', metavar='domain2-source', type=str, help='domain 2 source')
parser.add_argument('d2t', metavar='domain2-target', type=str, help='domain 2 target')
parser.add_argument('v', metavar='vocab', type=str, help='shared bpe vocab')
# optional arguments
parser.add_argument('-x', '--averaging-over', dest='x', type=int, default=10, help='How many PAD approximations to compute and average over')
parser.add_argument('-b', '--batch-size', dest='b', type=int, default=320, help='batch_size')
args = parser.parse_args()
return args | 33,137 |
def mqtt_gateway(broker, port, **kwargs):
"""Start an mqtt gateway."""
with run_mqtt_client(broker, port) as mqttc:
gateway = MQTTGateway(
mqttc.publish, mqttc.subscribe, event_callback=handle_msg, **kwargs
)
run_gateway(gateway) | 33,138 |
def pprint(matrix: list) -> str:
"""
Preety print matrix string
Parameters
----------
matrix : list
Square matrix.
Returns
-------
str
Preety string form of matrix.
"""
matrix_string = str(matrix)
matrix_string = matrix_string.replace('],', '],\n')
return matrix_string | 33,139 |
def sigmoid(x : np.ndarray, a : float, b : float, c : float) -> np.ndarray :
"""
A parameterized sigmoid curve
Args:
x (np.ndarray or float): x values to evaluate the sigmoid
a (float): vertical stretch parameter
b (float): horizontal shift parameter
c (float): horizontal stretch parameter
Returns:
evalutated sigmoid curve at x values for the given parameterization
"""
return a / (b + np.exp(-1.0 * c * x)) | 33,140 |
def merge_testcase_data(leaf, statsname, x_axis):
"""
statsname might be a function. It will be given the folder path
of the test case and should return one line.
"""
res = get_leaf_tests_stats(leaf, statsname)
return merge_testcase_data_set_x(res, x_axis) | 33,141 |
def get_account_ids(status=None, table_name=None):
"""return an array of account_ids from the Accounts table. Optionally, filter by status"""
dynamodb = boto3.resource('dynamodb')
if table_name:
account_table = dynamodb.Table(table_name)
else:
account_table = dynamodb.Table(os.environ['ACCOUNT_TABLE'])
account_list = []
response = account_table.scan(
AttributesToGet=['account_id', 'account_status']
)
while 'LastEvaluatedKey' in response:
# Means that dynamoDB didn't return the full set, so ask for more.
account_list = account_list + response['Items']
response = account_table.scan(
AttributesToGet=['account_id', 'account_status'],
ExclusiveStartKey=response['LastEvaluatedKey']
)
account_list = account_list + response['Items']
output = []
for a in account_list:
if status is None: # Then we get everything
output.append(a['account_id'])
elif a['account_status'] == status: # this is what we asked for
output.append(a['account_id'])
# Otherwise, don't bother.
return(output) | 33,142 |
def dashed_word(answer):
"""
:param answer: str, from random_word
:return: str, the number of '-' as per the length of answer
"""
ans = ""
for i in answer:
ans += '-'
return ans | 33,143 |
def main(urls, daemon):
"""Check url and print their HTTP statuses (w/ colors)
:param urls: URL (or a tuple with multiple URLs) to check
:type urls: str or tuple(str)
:param daemon: If set to True, after checking all URLs,
sleep for 5 seconds and check them again
:type daemon: bool
"""
while True:
for url in urls:
status_code = check_url(url)
if status_code:
colorize(url, status_code)
if not daemon:
break
sleep(5) | 33,144 |
def merge_overpass_jsons(jsons):
"""Merge a list of overpass JSONs into a single JSON.
Parameters
----------
jsons : :obj:`list`
List of dictionaries representing Overpass JSONs.
Returns
-------
:obj:`dict`
Dictionary containing all elements from input JSONS.
"""
elements = []
for osm_json in jsons:
elements.extend(osm_json['elements'])
return {'elements': elements} | 33,145 |
def identity_functions(function, args):
"""This function routes calls to sub-functions, thereby allowing
a single identity function to stay hot for longer
Args:
function (str): for selection of function to call
args: arguments to be passed to the selected function
Returns:
function: If valid function selected, function with args passed
else None
"""
if function == "get_session_info":
from admin.get_session_info import run as _get_session_info
return _get_session_info(args)
elif function == "login":
from admin.login import run as _login
return _login(args)
elif function == "logout":
from admin.logout import run as _logout
return _logout(args)
elif function == "recover_otp":
from admin.recover_otp import run as _recover_otp
return _recover_otp(args)
elif function == "register":
from admin.register import run as _register
return _register(args)
elif function == "request_login":
from admin.request_login import run as _request_login
return _request_login(args)
else:
from admin.handler import MissingFunctionError
raise MissingFunctionError() | 33,146 |
def load_template(tmpl):
"""
Loads the default template file.
"""
with open(tmpl, "r") as stream:
return Template(stream.read()) | 33,147 |
def calculate_id_name(message):
""" Calculates hash value based on message. Useful for unique id - six hex characters. 6 digits - 16777216 permutations.
TODO: check for hash collisions.
"""
hash_object = hashlib.md5(b'%s'% message)
return hash_object.hexdigest()[0:5] | 33,148 |
def get_total_cases():
"""全国の現在の感染者数"""
return col_ref.document(n).get().to_dict()["total"]["total_cases"] | 33,149 |
def _find_db_team(team_id: OrgaTeamID) -> Optional[DbOrgaTeam]:
"""Return the team with that id, or `None` if not found."""
return db.session.query(DbOrgaTeam).get(team_id) | 33,150 |
def make_number(
num: Optional[str],
repr: str = None,
speak: str = None,
literal: bool = False,
special: dict = None,
) -> Optional[Number]:
"""Returns a Number or Fraction dataclass for a number string
If literal, spoken string will not convert to hundreds/thousands
NOTE: Numerators are assumed to have a single digit. Additional are whole numbers
"""
# pylint: disable=too-many-branches
if not num or is_unknown(num):
return None
# Check special
with suppress(KeyError):
item = (special or {}).get(num) or SPECIAL_NUMBERS[num]
if isinstance(item, tuple):
value, spoken = item
else:
value = item
spoken = spoken_number(str(value), literal=literal)
return Number(repr or num, value, spoken)
# Check cardinal direction
if num in CARDINALS:
if not repr:
repr = num
num = str(CARDINALS[num])
# Remove spurious characters from the end
num = num.rstrip("M.")
num = num.replace("O", "0")
num = num.replace("+", "")
# Create Fraction
if "/" in num:
return make_fraction(num, repr, literal)
# Handle Minus values with errors like 0M04
if "M" in num:
val_str = num.replace("MM", "-").replace("M", "-")
while val_str[0] != "-":
val_str = val_str[1:]
else:
val_str = num
# Check value prefixes
speak_prefix = ""
if val_str.startswith("ABV "):
speak_prefix += "above "
val_str = val_str[4:]
if val_str.startswith("BLW "):
speak_prefix += "below "
val_str = val_str[4:]
if val_str.startswith("FL"):
speak_prefix += "flight level "
val_str, literal = val_str[2:], True
# Create Number
if not val_str:
return None
if "." in num:
value = float(val_str)
# Overwrite float 0 due to "0.0" literal
if not value:
value = 0
else:
value = int(val_str)
spoken = speak_prefix + spoken_number(speak or str(value), literal)
return Number(repr or num, value, spoken) | 33,151 |
def _readmapfile(fp, mapfile):
"""Load template elements from the given map file"""
base = os.path.dirname(mapfile)
conf = config.config()
def include(rel, remap, sections):
subresource = None
if base:
abs = os.path.normpath(os.path.join(base, rel))
if os.path.isfile(abs):
subresource = util.posixfile(abs, b'rb')
if not subresource:
if pycompat.ossep not in rel:
abs = rel
subresource = resourceutil.open_resource(
b'mercurial.templates', rel
)
else:
dir = templatedir()
if dir:
abs = os.path.normpath(os.path.join(dir, rel))
if os.path.isfile(abs):
subresource = util.posixfile(abs, b'rb')
if subresource:
data = subresource.read()
conf.parse(
abs,
data,
sections=sections,
remap=remap,
include=include,
)
data = fp.read()
conf.parse(mapfile, data, remap={b'': b'templates'}, include=include)
cache = {}
tmap = {}
aliases = []
val = conf.get(b'templates', b'__base__')
if val and val[0] not in b"'\"":
# treat as a pointer to a base class for this style
path = os.path.normpath(os.path.join(base, val))
# fallback check in template paths
if not os.path.exists(path):
dir = templatedir()
if dir is not None:
p2 = os.path.normpath(os.path.join(dir, val))
if os.path.isfile(p2):
path = p2
else:
p3 = os.path.normpath(os.path.join(p2, b"map"))
if os.path.isfile(p3):
path = p3
fp = _open_mapfile(path)
cache, tmap, aliases = _readmapfile(fp, path)
for key, val in conf[b'templates'].items():
if not val:
raise error.ParseError(
_(b'missing value'), conf.source(b'templates', key)
)
if val[0] in b"'\"":
if val[0] != val[-1]:
raise error.ParseError(
_(b'unmatched quotes'), conf.source(b'templates', key)
)
cache[key] = unquotestring(val)
elif key != b'__base__':
tmap[key] = os.path.join(base, val)
aliases.extend(conf[b'templatealias'].items())
return cache, tmap, aliases | 33,152 |
async def scott_search(ctx, *args):
"""Grabs an SSC article at random if no arguments,
else results of a Google search"""
logging.info("scott command invocation: %s", args)
await ctx.send(search_helper(args, "2befc5589b259ca98")) | 33,153 |
def gif_jtfs_3d(Scx, jtfs=None, preset='spinned', savedir='',
base_name='jtfs3d', images_ext='.png', cmap='turbo', cmap_norm=.5,
axes_labels=('xi2', 'xi1_fr', 'xi1'), overwrite=False,
save_images=False, width=800, height=800, surface_count=30,
opacity=.2, zoom=1, angles=None, verbose=True, gif_kw=None):
"""Generate and save GIF of 3D JTFS slices.
Parameters
----------
Scx : dict / tensor, 4D
Output of `jtfs(x)` with `out_type='dict:array'` or `'dict:list'`,
or output of `wavespin.toolkit.pack_coeffs_jtfs`.
jtfs : TimeFrequencyScattering1D
Required if `preset` is not `None`.
preset : str['spinned', 'all'] / None
If `Scx = jtfs(x)`, then
- 'spinned': show only `psi_t * psi_f_up` and `psi_t * psi_f_dn` pairs
- 'all': show all pairs
`None` is for when `Scx` is already packed via `pack_coeffs_jtfs`.
savedir, base_name, images_ext, overwrite :
See `help(wavespin.visuals.gif_jtfs)`.
cmap : str
Colormap to use.
cmap_norm : float
Colormap norm to use, as fraction of maximum value of `packed`
(i.e. `norm=(0, cmap_norm * packed.max())`).
axes_labels : tuple[str]
Names of last three dimensions of `packed`. E.g. `structure==2`
(in `pack_coeffs_jtfs`) will output `(n2, n1_fr, n1, t)`, so
`('xi2', 'xi1_fr', 'xi1')` (default).
width : int
2D width of each image (GIF frame).
height : int
2D height of each image (GIF frame).
surface_count : int
Greater improves 3D detail of each frame, but takes longer to render.
opacity : float
Lesser makes 3D surfaces more transparent, exposing more detail.
zoom : float (default=1) / None
Zoom factor on each 3D frame. If None, won't modify `angles`.
If not None, will first divide by L2 norm of `angles`, then by `zoom`.
angles : None / np.ndarray / list/tuple[np.ndarray] / str['rotate']
Controls display angle of the GIF.
- None: default angle that faces the line extending from min to max
of `xi1`, `xi2`, and `xi1_fr` (assuming default `axes_labels`).
- Single 1D array: will reuse for each frame.
- 'rotate': will use a preset that rotates the display about the
default angle.
Resulting array is passed to `go.Figure.update_layout()` as
`'layout_kw': {'scene_camera': 'center': dict(x=e[0], y=e[1], z=e[2])}`,
where `e = angles[0]` up to `e = angles[len(packed) - 1]`.
verbose : bool (default True)
Whether to print GIF generation progress.
gif_kw : dict / None
Passed as kwargs to `wavespin.visuals.make_gif`.
Example
-------
Also see `examples/visuals_tour.py`.
::
N, J, Q = 2049, 7, 16
x = toolkit.echirp(N)
jtfs = TimeFrequencyScattering1D(J, N, Q, J_fr=4, Q_fr=2,
out_type='dict:list')
Scx = jtfs(x)
gif_jtfs_3d(Scx, jtfs, savedir='', preset='spinned')
"""
try:
import plotly.graph_objs as go
except ImportError as e:
print("\n`plotly.graph_objs` is needed for `gif_jtfs_3d`.")
raise e
# handle args & check if already exists (if so, delete if `overwrite`)
savedir, savepath_gif, images_ext, save_images, *_ = _handle_gif_args(
savedir, base_name, images_ext, save_images, overwrite, show=False)
if preset not in ('spinned', 'all', None):
raise ValueError("`preset` must be 'spinned', 'all', or None (got %s)" % (
preset))
# handle input tensor
if not isinstance(Scx, (dict, np.ndarray)):
raise ValueError("`Scx` must be dict or numpy array (need `out_type` "
"'dict:array' or 'dict:list'). Got %s" % type(Scx))
elif isinstance(Scx, dict):
ckw = dict(Scx=Scx, meta=jtfs.meta(), reverse_n1=False,
out_3D=jtfs.out_3D,
sampling_psi_fr=jtfs.sampling_psi_fr)
if preset == 'spinned':
_packed = pack_coeffs_jtfs(structure=2, separate_lowpass=True, **ckw)
_packed = _packed[0] # spinned only
elif preset == 'all':
_packed = pack_coeffs_jtfs(structure=2, separate_lowpass=False, **ckw)
else:
raise ValueError("dict `Scx` requires string `preset` (got %s)" % (
preset))
packed = _packed.transpose(-1, 0, 1, 2) # time first
elif isinstance(Scx, np.ndarray):
packed = Scx
# handle labels
supported = ('t', 'xi2', 'xi1_fr', 'xi1')
for label in axes_labels:
if label not in supported:
raise ValueError(("unsupported `axes_labels` element: {} -- must "
"be one of: {}").format(
label, ', '.join(supported)))
frame_label = [label for label in supported if label not in axes_labels][0]
# 3D meshgrid
def slc(i, g):
label = axes_labels[i]
start = {'xi1': .5, 'xi2': .5, 't': 0, 'xi1_fr': .5}[label]
end = {'xi1': 0., 'xi2': 0., 't': 1, 'xi1_fr': -.5}[label]
return slice(start, end, g*1j)
a, b, c = packed.shape[1:]
X, Y, Z = np.mgrid[slc(0, a), slc(1, b), slc(2, c)]
# handle `angles`; camera focus
if angles is None:
eye = np.array([2.5, .3, 2])
eye /= np.linalg.norm(eye)
eyes = [eye] * len(packed)
elif (isinstance(angles, (list, tuple)) or
(isinstance(angles, np.ndarray) and angles.ndim == 2)):
eyes = angles
elif isinstance(angles, str):
assert angles == 'rotate', angles
n_pts = len(packed)
def gauss(n_pts, mn, mx, width=20):
t = np.linspace(0, 1, n_pts)
g = np.exp(-(t - .5)**2 * width)
g *= (mx - mn)
g += mn
return g
x = np.logspace(np.log10(2.5), np.log10(8.5), n_pts, endpoint=1)
y = np.logspace(np.log10(0.3), np.log10(6.3), n_pts, endpoint=1)
z = np.logspace(np.log10(2.0), np.log10(2.0), n_pts, endpoint=1)
x, y, z = [gauss(n_pts, mn, mx) for (mn, mx)
in [(2.5, 8.5), (0.3, 6.3), (2, 2)]]
eyes = np.vstack([x, y, z]).T
else:
eyes = [angles] * len(packed)
assert len(eyes) == len(packed), (len(eyes), len(packed))
# camera zoom
if zoom is not None:
for i in range(len(eyes)):
eyes[i] /= (np.linalg.norm(eyes[i]) * .5 * zoom)
# colormap norm
mx = cmap_norm * packed.max()
# gif configs
volume_kw = dict(
x=X.flatten(),
y=Y.flatten(),
z=Z.flatten(),
opacity=opacity,
surface_count=surface_count,
colorscale=cmap,
showscale=False,
cmin=0,
cmax=mx,
)
layout_kw = dict(
margin_pad=0,
margin_l=0,
margin_r=0,
margin_t=0,
title_pad_t=0,
title_pad_b=0,
margin_autoexpand=False,
scene_aspectmode='cube',
width=width,
height=height,
scene=dict(
xaxis_title=axes_labels[0],
yaxis_title=axes_labels[1],
zaxis_title=axes_labels[2],
),
scene_camera=dict(
up=dict(x=0, y=1, z=0),
center=dict(x=0, y=0, z=0),
),
)
# generate gif frames ####################################################
img_paths = []
for k, vol4 in enumerate(packed):
fig = go.Figure(go.Volume(value=vol4.flatten(), **volume_kw))
eye = dict(x=eyes[k][0], y=eyes[k][1], z=eyes[k][2])
layout_kw['scene_camera']['eye'] = eye
fig.update_layout(
**layout_kw,
title={'text': f"{frame_label}={k}",
'x': .5, 'y': .09,
'xanchor': 'center', 'yanchor': 'top'}
)
savepath = os.path.join(savedir, f'{base_name}{k}{images_ext}')
if os.path.isfile(savepath) and overwrite:
os.unlink(savepath)
fig.write_image(savepath)
img_paths.append(savepath)
if verbose:
print("{}/{} frames done".format(k + 1, len(packed)), flush=True)
# make gif ###############################################################
try:
if gif_kw is None:
gif_kw = {}
make_gif(loaddir=savedir, savepath=savepath_gif, ext=images_ext,
delimiter=base_name, overwrite=overwrite, verbose=verbose,
**gif_kw)
finally:
if not save_images:
# guarantee cleanup
for path in img_paths:
if os.path.isfile(path):
os.unlink(path) | 33,154 |
def PlotHillslopeDataWithBasins(DataDirectory,FilenamePrefix,PlotDirectory):
"""
Function to make plots of hillslope data vs basin id.
Martin probably has nice versions of this but I need something
quick for my poster
Author: FJC
"""
# load the channel data
ChannelData = ReadChannelData(DataDirectory, FilenamePrefix)
#print BasinChannelData
# load the hillslopes data
HillslopeData = ReadHillslopeData(DataDirectory, FilenamePrefix)
basin_dict = MapBasinKeysToJunctions(DataDirectory,FilenamePrefix)
basin_keys = basin_dict.keys()
median_cht = []
cht_lower_err = []
cht_upper_err = []
median_Lh = []
Lh_lower_err = []
Lh_upper_err = []
median_Rstar = []
Rstar_lower_err = []
Rstar_upper_err = []
median_Estar = []
Estar_lower_err = []
Estar_upper_err = []
median_mchi = []
mchi_lower_err = []
mchi_upper_err = []
for key, jn in basin_dict.iteritems():
BasinHillslopeData = HillslopeData[HillslopeData.BasinID == jn]
BasinChannelData = ChannelData[ChannelData.basin_key == key]
# now get all the hillslope data for this basin
this_median = abs(BasinHillslopeData.Cht.median())
median_cht.append(this_median)
cht_lowerP = np.percentile(BasinHillslopeData.Cht, 16)
cht_upperP = np.percentile(BasinHillslopeData.Cht, 84)
cht_lower_err.append(this_median-abs(cht_upperP)) # these are the opposite way round because
cht_upper_err.append(abs(cht_lowerP)-this_median) # I am inverting the axis to show positive Chts
this_median = BasinHillslopeData.Lh.median()
median_Lh.append(this_median)
Lh_lowerP = np.percentile(BasinHillslopeData.Lh, 16)
Lh_upperP = np.percentile(BasinHillslopeData.Lh, 84)
Lh_lower_err.append(this_median-Lh_lowerP)
Lh_upper_err.append(Lh_upperP-this_median)
this_median = BasinHillslopeData.R_Star.median()
median_Rstar.append(this_median)
Rstar_lowerP = np.percentile(BasinHillslopeData.R_Star, 16)
Rstar_upperP = np.percentile(BasinHillslopeData.R_Star, 84)
Rstar_lower_err.append(this_median-Rstar_lowerP)
Rstar_upper_err.append(Rstar_upperP-this_median)
this_median = BasinHillslopeData.E_Star.median()
median_Estar.append(this_median)
Estar_lowerP = np.percentile(BasinHillslopeData.E_Star, 16)
Estar_upperP = np.percentile(BasinHillslopeData.E_Star, 84)
Estar_lower_err.append(this_median-Estar_lowerP)
Estar_upper_err.append(Estar_upperP-this_median)
# get the channel data
this_median = BasinChannelData.m_chi.median()
median_mchi.append(this_median)
mchi_lowerP = np.percentile(BasinChannelData.m_chi, 16)
mchi_upperP = np.percentile(BasinChannelData.m_chi, 84)
mchi_lower_err.append(this_median-mchi_lowerP)
mchi_upper_err.append(mchi_upperP-this_median)
# set up the figure
fig, ax = plt.subplots(nrows = 6, ncols=1, sharex=True, figsize=(6,10), facecolor='white')
# Remove horizontal space between axes
fig.subplots_adjust(hspace=0)
# plot the hillslope length
ax[0].errorbar(basin_keys,median_Lh,yerr=[Lh_lower_err, Lh_upper_err],fmt='o', ecolor='0.5',markersize=5,mec='k')
ax[0].set_ylabel('$L_h$')
#plot the cht
ax[1].errorbar(basin_keys,median_cht,yerr=[cht_lower_err, cht_upper_err],fmt='o', ecolor='0.5',markersize=5,mfc='red',mec='k')
ax[1].set_ylabel('$C_{HT}$')
#plot the R*
ax[2].errorbar(basin_keys,median_Rstar,yerr=[Rstar_lower_err, Rstar_upper_err],fmt='o', ecolor='0.5',markersize=5,mfc='orange',mec='k')
ax[2].set_ylabel('$R*$')
#plot the Mchi
ax[3].errorbar(basin_keys,median_mchi,yerr=[mchi_lower_err, mchi_upper_err],fmt='o', ecolor='0.5',markersize=5,mfc='purple',mec='k')
ax[3].set_ylabel('$k_{sn}$')
# read the uplift data in
# read in the csv
uplift_df = pd.read_csv(DataDirectory+'MTJ_basin_uplift.csv')
dd_df = pd.read_csv(DataDirectory+FilenamePrefix+'_basin_dd.csv')
# get the drainage density
drainage_density = dd_df['drainage_density']
ax[4].scatter(basin_keys, drainage_density, c='k', edgecolors='k', s=20)
ax[4].set_ylim(np.min(drainage_density)-0.001, np.max(drainage_density)+0.001)
ax[4].set_ylabel('Drainage density (m/m$^2$)')
# get the data
uplift_rate = uplift_df['Uplift_rate']
ax[5].plot(basin_keys, uplift_rate, c='k', ls='--')
ax[5].set_ylabel('Uplift rate (mm/yr)')
# set the axes labels
ax[5].set_xlabel('Basin ID')
plt.xticks(np.arange(min(basin_keys), max(basin_keys)+1, 1))
plt.tight_layout()
#save output
plt.savefig(PlotDirectory+FilenamePrefix +"_basin_hillslope_data.png", dpi=300)
plt.clf()
output_list = [('basin_keys', basin_keys),
('uplift_rate', uplift_rate),
('Lh_median', median_Lh),
('Lh_lower_err', Lh_lower_err),
('Lh_upper_err', Lh_upper_err),
('cht_median', median_cht),
('cht_lower_err', cht_lower_err),
('cht_upper_err', cht_upper_err),
('Rstar_median', median_Rstar),
('Rstar_lower_err', Rstar_lower_err),
('Rstar_upper_err', Rstar_upper_err),
('Estar_median', median_Estar),
('Estar_lower_err', Estar_lower_err),
('Estar_upper_err', Estar_upper_err),
('mchi_median', median_mchi),
('mchi_lower_err', mchi_lower_err),
('mchi_upper_err', mchi_upper_err),
('drainage_density', drainage_density)]
# write output to csv
OutDF = pd.DataFrame.from_items(output_list)
csv_outname = PlotDirectory+FilenamePrefix+'_basin_hillslope_data.csv'
OutDF.to_csv(csv_outname,index=False) | 33,155 |
def get_arguments():
"""
Parse command line arguments
:return Namespace: parsed arguments
"""
parser = ArgumentParser(description='')
subparsers = parser.add_subparsers(help='sub-command help', dest='subparser_name')
parser.add_argument(
'-v', '--verbose',
type=int,
default=1,
help='Verbosity level: [under construction]'
)
parser.add_argument(
'-d', '--debug',
action='store_true',
required=False,
help='Debug mode [under construction]'
)
# adding tasks
parser_add = subparsers.add_parser('add', help='Create a new task')
parser_add.add_argument(
'name',
type=str,
help="Name of the task to add"
)
parser_add.add_argument(
'-p', '--priority',
type=int,
default=0,
help="Priority of the task"
)
parser_add.add_argument(
'-t', '--time',
type=validate_time,
help="Start time of the task. Format: -t HH:MM"
)
parser_add.add_argument(
'-w', '--weight',
type=float,
default=0,
help="tbd"
)
parser_add.add_argument(
'-r', '--repeat',
type=validate_time_period,
help="Repetition period. Format examples: "
"'X years' "
"'X months' "
"'X days' "
"workdays"
)
parser_add.add_argument(
'-d', '--date',
default="today",
type=validate_relative_date,
help="Due date. Excepted formats:"
"YYYY-MM-DD"
"today [default]"
"tomorrow"
"'+X days'"
"'+X months'"
"'+X years'"
"no"
)
# listing tasks
parser_list = subparsers.add_parser('list', help='List tasks')
list_group = parser_list.add_mutually_exclusive_group()
list_group.add_argument(
'-t', '--top',
action='store_true',
help="List the highest priority task today"
)
parser_list.add_argument(
'-d', '--date',
type=str,
help="List open tasks at a given date. Format: YYYY-MM-DD"
)
list_group.add_argument(
'-o', '--open',
action='store_true',
help="List open tasks"
)
# modifying tasks
parser_mod = subparsers.add_parser('mod', help='Modify a task')
parser_mod.add_argument(
'id',
type=str,
help="Name of the task to add"
)
parser_mod.add_argument(
'-n', '--name',
type=str,
default="",
help="Name of the task"
)
parser_mod.add_argument(
'-p', '--priority',
type=int,
default=-1,
help="Priority of the task"
)
parser_mod.add_argument(
'-t', '--time',
type=validate_time,
help="Start time of the task. Format HH:MM"
)
parser_mod.add_argument(
'-w', '--weight',
type=float,
default=-1,
help="tbd"
)
parser_mod.add_argument(
'-r', '--repeat',
type=validate_time_period,
help="Repetition period. Format examples: "
"'X days'"
"'X months'"
"'X years'"
"workdays"
)
parser_mod.add_argument(
'-d', '--date',
type=validate_relative_date,
help="Postpone the task. Excepted formats:"
"YYYY-MM-DD"
"today"
"tomorrow"
"'+X days'"
"'+X months'"
"'+X years'"
"no"
)
# closing tasks
parser_close = subparsers.add_parser('close', help='Mark a task as closed')
parser_close.add_argument(
'id',
type=str,
nargs='?',
help="ID of the task to close"
)
# deleting tasks
parser_delete = subparsers.add_parser('delete', help='Permanently delete a task')
parser_delete.add_argument(
'id',
type=str,
help="ID of the task to delete"
)
# reporting
parser_report = subparsers.add_parser('report',
help='Calculate a total weight of tasks. '
'If no arguments specified - '
'weight of all tasks today (both open and closed)')
parser_report.add_argument(
'-d', '--date',
type=str,
help="Total weight of tasks on a given date. Date format: YYYY-MM-DD"
)
parser_report.add_argument(
'-o', '--open',
action='store_true',
help="Total weight of open tasks today"
)
parser_report.add_argument(
'-p', '--plot',
action='store_true',
help="Build a plot of productivity by days"
)
# notes
parser_note = subparsers.add_parser('note',
help='Add a note for a given day')
parser_note.add_argument(
'text',
type=str,
help="The text of the note"
)
parser_note.add_argument(
'-d', '--date',
type=validate_date,
help="Associate the note with a date."
"Default: current date"
)
# RPG extension
parser_rpg = subparsers.add_parser('rpg', help='tbd')
rpg_group = parser_rpg.add_mutually_exclusive_group()
rpg_group.add_argument(
'-l', '--list-quests',
action='store_true',
help='tbd'
)
rpg_group.add_argument(
'-f', '--finish-quest',
type=int,
help='tbd'
)
rpg_group.add_argument(
'-a', '--list-awards',
action='store_true',
help='tbd'
)
rpg_group.add_argument(
'-c', '--claim-award',
type=int,
default=0,
help='tbd'
)
rpg_group.add_argument(
'-p', '--character-parameters',
action='store_true',
help='tbd'
)
args = parser.parse_args()
return args | 33,156 |
def _serialize_account(project):
"""Generate several useful fields related to a project's account"""
account = project.account
return {'goal': account.goal,
'community_contribution': account.community_contribution,
'total_donated': account.total_donated(),
'total_raised': account.total_raised(),
'total_cost': account.total_cost(),
'percent_raised': account.percent_raised(),
'percent_community': account.percent_community(),
'funded': account.funded(),
'remaining': account.remaining()} | 33,157 |
def _NodeThread(node_ip):
"""Check if this IP is a node"""
log = GetLogger()
SetThreadLogPrefix(node_ip)
known_auth = [
("admin", "admin"),
("admin", "solidfire")
]
SFCONFIG_PORT = 442
sock = socket.socket()
sock.settimeout(0.5)
try:
sock.connect((node_ip, SFCONFIG_PORT))
sock.close()
log.debug("Port {} socket connect succeeded".format(SFCONFIG_PORT))
except (socket.timeout, socket.error, socket.herror, socket.gaierror):
# If sfconfig is not running, this does not look like a node
return None
node_info = {}
for user, passwd in known_auth:
api = SolidFireNodeAPI(node_ip, user, passwd, maxRetryCount=0)
try:
result = api.Call("GetClusterConfig", {}, timeout=2)
node_info["cluster"] = result["cluster"]["cluster"]
node_info["name"] = result["cluster"]["name"]
node_info["state"] = result["cluster"]["state"]
if "version" in result["cluster"]:
node_info["version"] = result["cluster"]["version"]
else:
result = api.Call("GetVersionInfo", {}, timeout=6)
node_info["version"] = result["versionInfo"]["sfconfig"]["Version"]
break
except UnauthorizedError:
continue
except SolidFireError as ex:
log.debug(str(ex))
return None
if not node_info:
return None
if not node_info["cluster"]:
node_info["cluster"] = "Available"
return node_info | 33,158 |
def configure_new_8_2_0_cluster(console_url, cluster_name, int_netmask, int_ip_low, int_ip_high,
ext_netmask, ext_ip_low, ext_ip_high, gateway, dns_servers,
encoding, sc_zonename, smartconnect_ip, compliance_license, logger):
"""Walk through the config Wizard to create a functional one-node cluster
:Returns: None
:param console_url: The URL to the vSphere HTML console for the OneFS node
:type console_url: String
:param cluster_name: The name to give the new cluster
:type cluster_name: String
:param int_netmask: The subnet mask for the internal OneFS network
:type int_netmask: String
:param int_ip_low: The smallest IP to assign to an internal NIC
:type int_ip_low: String (IPv4 address)
:param int_ip_high: The largest IP to assign to an internal NIC
:type int_ip_high: String (IPv4 address)
:param ext_ip_low: The smallest IP to assign to an external/public NIC
:type ext_ip_low: String (IPv4 address)
:param ext_ip_high: The largest IP to assign to an external/public NIC
:type ext_ip_high: String (IPv4 address)
:param gateway: The IP address for the default gateway
:type gateway: String (IPv4 address)
:param dns_servers: A common separated list of IPs of the DNS servers to use
:type dns_servers: String
:param encoding: The filesystem encoding to use.
:type encoding: String
:param sc_zonename: The SmartConnect Zone name to use. Skipped if None.
:type sc_zonename: String
:param smartconnect_ip: The IPv4 address to use as the SIP
:type smartconnect_ip: String (IPv4 address)
:param compliance_license: The license key to create a compliance mode cluster
:type compliance_license: String
:param logger: A object for logging information/errors
:type logger: logging.Logger
"""
logger.info('Setting up Selenium')
with vSphereConsole(console_url) as console:
logger.info('Waiting for node to fully boot')
console.wait_for_prompt()
logger.info('Formatting disks')
format_disks(console)
if compliance_license:
logger.info('Rebooting node into compliance mode')
enable_compliance_mode(console)
logger.info('Accepting EULA')
# OneFS 8.1.3 and newer do not require a license to enable SmartLock
make_new_and_accept_eual(console, compliance_license=False, auto_enter=True) # This is the only difference from 8.1.2.0...
logger.info('Setting root and admin passwords')
set_passwords(console)
logger.info("Naming cluster {}".format(cluster_name))
set_name(console, cluster_name) # 8.1.0.4 name comes before ESRS
logger.info("Settings encoding to {}".format(encoding))
set_encoding(console, encoding)
logger.info('Skipping ESRS config')
# ESRS not even set via Wizard...
# setup int network
logger.info('Setting up internal network - Mask: {} Low: {} High: {}'.format(int_netmask, int_ip_low, int_ip_high))
config_network(console, netmask=int_netmask, ip_low=int_ip_low, ip_high=int_ip_high)
# setup ext network
logger.info('Settings up external network - Mask: {} Low: {} High: {}'.format(ext_netmask, ext_ip_low, ext_ip_high))
config_network(console, netmask=ext_netmask, ip_low=ext_ip_low, ip_high=ext_ip_high, ext_network=True)
logger.info('Setting up default gateway for ext network to {}'.format(gateway))
set_default_gateway(console, gateway)
logger.info('Configuring SmartConnect - Zone: {} IP: {}'.format(sc_zonename, smartconnect_ip))
set_smartconnect(console, sc_zonename, smartconnect_ip)
logger.info('Setting DNS servers to {}'.format(dns_servers))
set_dns(console, dns_servers)
logger.info('Skipping timezone config')
set_timezone(console)
logger.info('Skipping join mode config')
set_join_mode(console)
logger.info('Committing changes and waiting for the cluster to form')
commit_config(console)
console.wait_for_prompt()
set_sysctls(console, compliance_mode=bool(compliance_license)) | 33,159 |
def neighbor_smoothing_binary(data_3d, neighbors):
"""
takes a 3d binary (0/1) input, returns a "neighbor" smoothed 3d matrix
Input:
------
data_3d: a 3d np.array (with 0s and 1s) -> 1s are "on", 0s are "off"
neighbors: the value that indicates the number of neighbors around voxel to check
Returns:
--------
smoothed_neighbors: 3d np.array same shape as data_3d
"""
smoothed_neighbors = data_3d.copy()
shape = data_3d.shape
for i in 1 + np.arange(shape[0] - 2):
for j in 1 + np.arange(shape[1] - 2):
for k in 1 + np.arange(shape[2] - 2):
# number of neighbors that need to be positivednm
if np.sum(data_3d[(i - 1):(i + 2),(j - 1):(j + 2),(k - 1):(k + 2)] == 1) < neighbors and data_3d[i, j, k] == 1:
smoothed_neighbors[i, j, k] = 0
return smoothed_neighbors | 33,160 |
def view(
name = None,
description = None,
parameters = (),
devel = False
):
"""
Decorator function to be used to "annotate" the provided
function as an view that is able to return a set of configurations
for the proper display of associated information.
Proper usage of the view definition/decoration is context
based and should vary based on application.
:type name: String
:param name: The name of the view (in plain english)
so that a better user experience is possible.
:type description: String
:param description: The description of the view (in plain english)
so that a better user experience is possible.
:type parameters: Tuple
:param parameters: The sequence containing tuples that describe
the various parameters to be send to the view.
:type devel: bool
:param devel: If the view should only be used/available under
development like environments (eg: debugging purposes).
:rtype: Function
:return: The decorator function that is going to be used to
generated the final function to be called.
"""
def decorator(function, *args, **kwargs):
function._view = View(
method = function.__name__,
name = name or function.__name__,
description = description,
parameters = parameters,
devel = devel
)
return function
return decorator | 33,161 |
def vprint(string):
"""Prints message if verbose is enabled"""
if VERBOSE:
print(string) | 33,162 |
def pprint(j, no_pretty):
"""
Prints as formatted JSON
"""
if not no_pretty:
echo(json.dumps(j, cls=PotionJSONEncoder, sort_keys=True,
indent=4, separators=(',', ': ')))
else:
echo(j) | 33,163 |
def _decode_response(resp_bytes: bytes) -> str:
"""Even though we request identity, rvm.io sends us gzip."""
try:
# Try UTF-8 first, in case they ever fix their bug
return resp_bytes.decode('UTF-8')
except UnicodeDecodeError:
with io.BytesIO(resp_bytes) as bytesio:
with gzip.GzipFile(fileobj=bytesio) as gzipfile:
return gzipfile.read().decode('UTF-8') | 33,164 |
def registrymixin_models():
"""Fixtures for RegistryMixin tests."""
# We have two sample models and two registered items to test that
# the registry is unique to each model and is not a global registry
# in the base RegistryMixin class.
# Sample model 1
class RegistryTest1(BaseMixin, db.Model):
"""Registry test model 1."""
__tablename__ = 'registry_test1'
# Sample model 2
class RegistryTest2(BaseMixin, db.Model):
"""Registry test model 2."""
__tablename__ = 'registry_test2'
# Sample registered item (form or view) 1
class RegisteredItem1:
"""Registered item 1."""
def __init__(self, obj=None):
"""Init class."""
self.obj = obj
# Sample registered item 2
@RegistryTest2.views('test')
class RegisteredItem2:
"""Registered item 2."""
def __init__(self, obj=None):
"""Init class."""
self.obj = obj
# Sample registered item 3
@RegistryTest1.features('is1')
@RegistryTest2.features()
def is1(obj):
"""Assert object is instance of RegistryTest1."""
return isinstance(obj, RegistryTest1)
RegistryTest1.views.test = RegisteredItem1
return SimpleNamespace(**locals()) | 33,165 |
def delete_imgs(lower_quality_set: List[Path]):
"""
Function for deleting the lower quality images that were found after the search
"""
for file in lower_quality_set:
print("\nDeletion in progress...")
deleted = 0
try:
file.unlink()
print("Deleted file:", file)
deleted += 1
except:
print("Could not delete file:", file)
print("\n***\nDeleted", deleted, "duplicates/similar images.") | 33,166 |
def tabulate(*args, **kwargs):
"""Tabulate the output for pretty-printing.
Usage: cat a.csv | ph tabulate --headers --noindex --format=grid
Takes arguments
* --headers
* --noindex
* --format=[grid, latex, pretty, ...].
For a full list of format styles confer the README.
This function uses the tabulate project available as a standalone
package from PyPI.
Using `tabulate` in a pipeline usually means that the `ph` pipeline ends.
This is because of `tabulate`'s focus on user readability over machine
readability.
"""
headers = tuple()
fmt = kwargs.get("format")
index = True
if "--noindex" in args:
index = False
if "--headers" in args:
headers = "keys"
print(tabulate_(pipein(), tablefmt=fmt, headers=headers, showindex=index)) | 33,167 |
def is_test_input_output_file(file_name: str) -> bool:
"""
Return whether a file is used as input or output in a unit test.
"""
ret = is_under_test_dir(file_name)
ret &= file_name.endswith(".txt")
return ret | 33,168 |
def generate_csv_from_queryset(queryset, csv_name = "query_csv"):
"""
Genera un file csv a partire da un oggetto di tipo QuerySet
:param queryset: oggetto di tipo QuerySet
:param csv_name: campo opzionale per indicare il nome di output del csv
:return: oggetto response
"""
try:
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=' + csv_name + '.csv'
model_field_names = []
writer = csv.writer(response, delimiter=';')
if isinstance(queryset.first(), dict):
fields = queryset.first().keys()
else:
fields = [field.attname.split('_id')[0] if field.attname.endswith('_id') else field.attname for field in queryset.first()._meta.local_fields]
for field in fields:
model_field_names.append(field)
writer.writerow(model_field_names)
for query in queryset:
csv_row = []
for field in fields:
csv_row.append(query[field] if isinstance(query, dict) else model_to_dict(query)[field])
writer.writerow(csv_row)
return response
except Exception as e:
return e | 33,169 |
def get(isamAppliance, id, check_mode=False, force=False, ignore_error=False):
"""
Retrieving the current runtime template files directory contents
"""
return isamAppliance.invoke_get("Retrieving the current runtime template files directory contents",
"/mga/template_files/{0}".format(id), ignore_error=ignore_error) | 33,170 |
def update(contxt, vsmapp_id, attach_status=None, is_terminate=False):
"""update storage pool usage"""
if contxt is None:
contxt = context.get_admin_context()
if not vsmapp_id:
raise exception.StoragePoolUsageInvalid()
is_terminate = utils.bool_from_str(is_terminate)
kargs = {
'attach_status': attach_status,
'terminate_at': timeutils.utcnow() if is_terminate else None
}
try:
return db.storage_pool_usage_update(contxt, vsmapp_id, kargs)
except db_exc.DBError as e:
LOG.exception(_("DB Error on updating new storage pool usage %s" % e))
raise exception.StoragePoolUsageFailure() | 33,171 |
def adsgan(orig_data, params):
"""Generate synthetic data for ADSGAN framework.
Args:
orig_data: original data
params: Network parameters
mb_size: mini-batch size
z_dim: random state dimension
h_dim: hidden state dimension
lamda: identifiability parameter
iterations: training iterations
Returns:
synth_data: synthetically generated data
"""
# Reset the tensorflow graph
tf.reset_default_graph()
## Parameters
# Feature no
x_dim = len(orig_data.columns)
# Sample no
no = len(orig_data)
# Batch size
mb_size = params['mb_size']
# Random variable dimension
z_dim = params['z_dim']
# Hidden unit dimensions
h_dim = params['h_dim']
# Identifiability parameter
lamda = params['lamda']
# Training iterations
iterations = params['iterations']
# WGAN-GP parameters
lam = 10
lr = 1e-4
#%% Data Preprocessing
orig_data = np.asarray(orig_data)
def data_normalization(orig_data, epsilon = 1e-8):
min_val = np.min(orig_data, axis=0)
normalized_data = orig_data - min_val
max_val = np.max(normalized_data, axis=0)
normalized_data = normalized_data / (max_val + epsilon)
normalization_params = {"min_val": min_val, "max_val": max_val}
return normalized_data, normalization_params
def data_renormalization(normalized_data, normalization_params, epsilon = 1e-8):
renormalized_data = normalized_data * (normalization_params['max_val'] + epsilon)
renormalized_data = renormalized_data + normalization_params['min_val']
return renormalized_data
orig_data, normalization_params = data_normalization(orig_data)
#%% Necessary Functions
# Xavier Initialization Definition
def xavier_init(size):
in_dim = size[0]
xavier_stddev = 1. / tf.sqrt(in_dim / 2.)
return tf.random_normal(shape = size, stddev = xavier_stddev)
# Sample from uniform distribution
def sample_Z(m, n):
return np.random.uniform(-1., 1., size = [m, n])
# Sample from the real data
def sample_X(m, n):
return np.random.permutation(m)[:n]
#%% Placeholder
# Feature
X = tf.placeholder(tf.float32, shape = [None, x_dim])
# Random Variable
Z = tf.placeholder(tf.float32, shape = [None, z_dim])
#%% Discriminator
# Discriminator
D_W1 = tf.Variable(xavier_init([x_dim, h_dim]))
D_b1 = tf.Variable(tf.zeros(shape=[h_dim]))
D_W2 = tf.Variable(xavier_init([h_dim,h_dim]))
D_b2 = tf.Variable(tf.zeros(shape=[h_dim]))
D_W3 = tf.Variable(xavier_init([h_dim,1]))
D_b3 = tf.Variable(tf.zeros(shape=[1]))
theta_D = [D_W1, D_W2, D_W3, D_b1, D_b2, D_b3]
#%% Generator
G_W1 = tf.Variable(xavier_init([z_dim + x_dim, h_dim]))
G_b1 = tf.Variable(tf.zeros(shape=[h_dim]))
G_W2 = tf.Variable(xavier_init([h_dim,h_dim]))
G_b2 = tf.Variable(tf.zeros(shape=[h_dim]))
G_W3 = tf.Variable(xavier_init([h_dim,h_dim]))
G_b3 = tf.Variable(tf.zeros(shape=[h_dim]))
G_W4 = tf.Variable(xavier_init([h_dim, x_dim]))
G_b4 = tf.Variable(tf.zeros(shape=[x_dim]))
theta_G = [G_W1, G_W2, G_W3, G_W4, G_b1, G_b2, G_b3, G_b4]
#%% Generator and discriminator functions
def generator(z, x):
inputs = tf.concat([z, x], axis = 1)
G_h1 = tf.nn.tanh(tf.matmul(inputs, G_W1) + G_b1)
G_h2 = tf.nn.tanh(tf.matmul(G_h1, G_W2) + G_b2)
G_h3 = tf.nn.tanh(tf.matmul(G_h2, G_W3) + G_b3)
G_log_prob = tf.nn.sigmoid(tf.matmul(G_h3, G_W4) + G_b4)
return G_log_prob
def discriminator(x):
D_h1 = tf.nn.relu(tf.matmul(x, D_W1) + D_b1)
D_h2 = tf.nn.relu(tf.matmul(D_h1, D_W2) + D_b2)
out = (tf.matmul(D_h2, D_W3) + D_b3)
return out
#%% Structure
G_sample = generator(Z,X)
D_real = discriminator(X)
D_fake = discriminator(G_sample)
# Replacement of Clipping algorithm to Penalty term
# 1. Line 6 in Algorithm 1
eps = tf.random_uniform([mb_size, 1], minval = 0., maxval = 1.)
X_inter = eps*X + (1. - eps) * G_sample
# 2. Line 7 in Algorithm 1
grad = tf.gradients(discriminator(X_inter), [X_inter])[0]
grad_norm = tf.sqrt(tf.reduce_sum((grad)**2 + 1e-8, axis = 1))
grad_pen = lam * tf.reduce_mean((grad_norm - 1)**2)
# Loss function
D_loss = tf.reduce_mean(D_fake) - tf.reduce_mean(D_real) + grad_pen
G_loss1 = -tf.sqrt(tf.reduce_mean(tf.square(X - G_sample)))
G_loss2 = -tf.reduce_mean(D_fake)
G_loss = G_loss2 + lamda * G_loss1
# Solver
D_solver = (tf.train.AdamOptimizer(learning_rate = lr, beta1 = 0.5).minimize(D_loss, var_list = theta_D))
G_solver = (tf.train.AdamOptimizer(learning_rate = lr, beta1 = 0.5).minimize(G_loss, var_list = theta_G))
#%% Iterations
sess = tf.Session()
sess.run(tf.global_variables_initializer())
# Iterations
for it in tqdm(range(iterations)):
# Discriminator training
for _ in range(5):
Z_mb = sample_Z(mb_size, z_dim)
X_idx = sample_X(no,mb_size)
X_mb = orig_data[X_idx,:]
_, D_loss_curr = sess.run([D_solver, D_loss], feed_dict = {X: X_mb, Z: Z_mb})
# Generator Training
Z_mb = sample_Z(mb_size, z_dim)
X_idx = sample_X(no,mb_size)
X_mb = orig_data[X_idx,:]
_, G_loss1_curr, G_loss2_curr = sess.run([G_solver, G_loss1, G_loss2], feed_dict = {X: X_mb, Z: Z_mb})
#%% Output Generation
synth_data = sess.run([G_sample], feed_dict = {Z: sample_Z(no, z_dim), X: orig_data})
synth_data = synth_data[0]
# Renormalization
synth_data = data_renormalization(synth_data, normalization_params)
# Binary features
for i in range(x_dim):
if len(np.unique(orig_data[:, i])) == 2:
synth_data[:, i] = np.round(synth_data[:, i])
return synth_data | 33,172 |
def unemployed(year,manu, key,state='*'): #ex manu= 54 is professional, scientific, and technical service industries, year= 2017
"""Yearly data on self-employed manufacturing sectors for all counties. Returns all receipts in thousands of dollars for all counties for the specified state for certain industries.
Parameters
----------
year: int
Only full 4-integer values for years where the Community Survey is available, 2009-2019
manu: str
string for a manufacturing sector code
key: str
API key requested from US census.gov website, string format
state: str
string argument for state code
Returns
-------
dataframe
Pandas dataframe extracted with the inserted parameters from the census manufacturing survey
Examples
--------
>>> from us_census import us_census
>>> unemployed(2002, '54', MYKEY, '02')"""
assert isinstance(year, int), "Please only ask for available years and ensure the year entry is an integer"
assert isinstance(manu, str), "Ensure the manufacturing sector is viable and a string."
assert isinstance(state, str)
r= requests.get(f'http://api.census.gov/data/{year}/nonemp?get=NRCPTOT,NAME&for=county:*&in=state:{state}&NAICS{year}={manu}&key={key}')
if r.status_code== 200:
try:
df= pd.DataFrame(r.json())
return df
except (NameError):
print("This state, year, or manufacturing sector code was not found. Please try valid inputs for the American Manufacturing survey .") | 33,173 |
def stack_bricks(top_brick, bottom_brick):
"""Stacks two Duplo bricks, returns the attachment frame of the top brick."""
arena = composer.Arena()
# Bottom brick is fixed in place, top brick has a freejoint.
arena.attach(bottom_brick)
attachment_frame = arena.add_free_entity(top_brick)
# Attachment frame is positioned such that the top brick is on top of the
# bottom brick.
attachment_frame.pos = (0, 0, 0.0192)
return arena, attachment_frame | 33,174 |
def trigger(name):
"""
@trigger decorator allow to register a function as a trigger with a given name
Parameters
----------
name : str
Name of the trigger
"""
_app = get_app_instance()
return _app.trigger(name) | 33,175 |
def test_group_deduplication():
"""Make sure groups are being deduplicated based on group name."""
e = Elements(owner=OWNER)
e.create_group('Threat', 'Test threat')
e.process()
original_threat_count = len(e.get_items_by_type('threat'))
# try to create an threat with the same name and make sure it is not created
e.create_group('Threat', 'Test threat')
e.process(dont_create_duplicate_groups=True)
new_threat_count = len(e.get_items_by_type('threat'))
assert new_threat_count == original_threat_count | 33,176 |
def test_list_my_groups_as_support_user_with_ignore_access_true(list_my_groups_context):
"""
Test that we can get all the groups as a support user
"""
results = list_my_groups_context.support_user_client.list_my_groups(ignore_access=True, status=200)
assert_that(len(results["groups"]), greater_than(50))
assert_that(results["maxItems"], is_(200))
assert_that(results["ignoreAccess"], is_(True)) | 33,177 |
def test_inputs():
"""Test input validation"""
# Valid data
model_eval = ModelEvaluation(
y_true=np.random.randint(2, size=100),
y_pred=np.random.randint(2, size=100),
model_name='foo',
)
model_eval = ModelEvaluation(
y_true=list(range(100)),
y_pred=list(range(100)),
model_name='goo',
)
model_eval = ModelEvaluation(
y_true=np.ones(shape=(10, 10)),
y_pred=np.random.normal(size=(10, 10)),
model_name='zoo',
)
with pytest.raises(InvalidArgument):
model_eval = ModelEvaluation(
y_true=np.ones(shape=(10, 1)),
y_pred=np.ones(shape=(10, 10)),
model_name='boo',
)
with pytest.raises(InvalidArgument):
y_pred = np.random.normal(size=(10, 10))
y_pred[0, 0] = np.nan
model_eval = ModelEvaluation(
y_true=np.ones(shape=(10, 1)),
y_pred=y_pred,
model_name='boo',
) | 33,178 |
def get_components_to_remove(component_dict: Dict[str, ComponentImport]) -> List[str]:
"""Gets a list of components to remove from the dictionary using console input.
Args:
component_dict (Dict[str, ComponentImport]): The custom component dictionary.
Returns:
List[str]: The keys to remove from the dictionary.
"""
components = []
if component_dict:
name = get_str("Enter a component name to remove(blank to skip): ")
else:
name = ""
while name != "":
if name.startswith("custom/"):
name = name.removeprefix("custom/")
if f"custom/{name}" not in component_dict:
error(f"No component import with name: {name}")
elif f"custom/{name}" in components:
error(f"Already removing component import with name: {name}")
else:
components.append(f"custom/{name}")
if len(component_dict) <= len(components):
break
name = get_str("Enter a component name to remove(blank to skip): ")
return components | 33,179 |
def list_data_objects():
"""
This endpoint translates DOS List requests into requests against indexd
and converts the responses into GA4GH messages.
:return:
"""
req_body = app.current_request.json_body
if req_body:
page_token = req_body.get('page_token', None)
page_size = req_body.get('page_size', None)
else:
page_token = "0"
page_size = 100
if req_body and (page_token or page_size):
gdc_req = dos_list_request_to_indexd(req_body)
else:
gdc_req = {}
response = requests.get("{}/index/".format(INDEXD_URL), params=gdc_req)
if response.status_code != 200:
return Response(
{'msg': 'The request was malformed {}'.format(
response.json().get('message', ""))})
list_response = response.json()
return gdc_to_dos_list_response(list_response) | 33,180 |
def get_include_file_start_line(block: Block) -> Union[int, None]:
"""
>>> block = lib_test.get_test_block_ok()
>>> # test start-line set to 10
>>> get_include_file_start_line(block)
10
>>> assert block.include_file_start_line == 10
>>> # test start-line not set
>>> block = lib_test.get_test_block_start_line_not_set()
>>> get_include_file_start_line(block)
>>> assert block.include_file_start_line is None
>>> # test start-line invalid
>>> block = lib_test.get_test_block_start_line_invalid()
>>> get_include_file_start_line(block) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Traceback (most recent call last):
...
ValueError: Error in File ".../README.template.rst", Line 47103: option "start-line" has no value
>>> # test start-line not integer
>>> block = lib_test.get_test_block_start_line_not_integer()
>>> get_include_file_start_line(block) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
Traceback (most recent call last):
...
TypeError: Error in File ".../README.template.rst", Line 47103: option "start-line" has to be integer
"""
include_file_start_line = block.include_file_start_line
if lib_block_options.is_option_in_block('start-line', block):
include_file_start_line = int(lib_block_options.get_option_value_from_block_or_raise_if_empty_or_invalid('start-line', block, value_must_be_int=True))
block.include_file_start_line = include_file_start_line
return include_file_start_line | 33,181 |
def get_wcets(utils, periods):
""" Returns WCET """
return [ui * ti for ui, ti in zip(utils, periods)]
# return [math.ceil(ui * ti) for ui, ti in zip(utils, periods)] | 33,182 |
def aws_get_dynamodb_table_names(profile_name: str) -> list:
"""
get all DynamoDB tables
:param profile_name: AWS IAM profile name
:return: a list of DynamoDB table names
"""
dynamodb_client = aws_get_client("dynamodb", profile_name)
table_names = []
more_to_evaluate = True
last_evaluated_table_name = None
while more_to_evaluate:
if last_evaluated_table_name is None:
response = dynamodb_client.list_tables()
else:
response = dynamodb_client.list_tables(ExclusiveStartTableName=last_evaluated_table_name)
partial_table_names = response.get("TableNames")
last_evaluated_table_name = response.get("LastEvaluatedTableName")
if partial_table_names is not None and len(partial_table_names) > 0:
table_names.extend(partial_table_names)
if last_evaluated_table_name is None:
more_to_evaluate = False
table_names.sort()
return table_names | 33,183 |
def stack_images_vertical(
image_0: NDArray[(Any, ...), Any], image_1: NDArray[(Any, ...), Any]
) -> NDArray[(Any, ...), Any]:
"""
Stack two images vertically.
Args:
image_0: The image to place on the top.
image_1: The image to place on the bottom.
Returns:
An image with the original two images on top of eachother.
Note:
The images must have the same width.
Example::
color_image = rc.camera.get_color_image()
depth_image = rc.camera.get_depth_image()
depth_image_colormap = rc_utils.colormap_depth_image(depth_image)
# Create a new image with the color on the top and depth on the bottom
new_image = rc_utils.stack_images_vertically(color_image, depth_image_colormap)
"""
assert (
image_0.shape[1] == image_1.shape[1]
), f"image_0 width ({image_0.shape[1]}) must be the same as image_1 width ({image_1.shape[1]})."
return np.vstack((image_0, image_1)) | 33,184 |
def documents(*sources):
"""fooo"""
# ipdb.set_trace()
docs = []
q = DocumentModel.objects.timeout(500).allow_filtering().all().limit(1000)
querysets = (q.filter(source=source) for source in sources) if sources else [q]
for query in querysets:
page = try_forever(list, query)
while len(page) > 0:
for doc in page:
docs.append(doc)
# yield doc
page = try_forever(next_page, query, page) | 33,185 |
def simulate_ids(num):
"""
模拟生成一定数量的身份证号
"""
ids = []
if num > 0:
for i in range(1, num+1):
id_raw = digit_1to6() + digit_7to10() + digit_11to14() + digit_15to17()
id = id_raw + digit_18(id_raw)
ids.append(id)
else:
return False
return ids | 33,186 |
def geomean(x):
"""computes geometric mean
"""
return exp(sum(log(i) for i in x) / len(x)) | 33,187 |
def _get_mean_traces_for_iteration_line_plot(
scenario_df: pd.DataFrame,
) -> Tuple[go.Scatter, go.Scatter, go.Scatter]:
"""Returns the traces for the mean of the success rate.
Parameters
----------
scenario_df : pd.DataFrame
DataFrame containing the columns "n_iterations", "mean_success_rate", "std_success_rate"
Returns
-------
Tuple[go.Scatter, go.Scatter, go.Scatter]
tuple of traces. Contains:
- main_trace: mean
- upper_trace: upper bound using the standard deviation
- lower_trace: lower bound using the standard deviation
"""
# standard colors used by Plotly
colors = px.colors.qualitative.Plotly
# mean of success rate
mean_trace = go.Scatter(
name="Mean",
x=scenario_df["n_iterations"],
y=scenario_df["mean_success_rate"],
# line=dict(color="rgb(0,100,80)"),
mode="lines+markers",
marker=dict(size=15),
line=dict(width=4),
# legendgroup="group",
visible=False,
)
# upper std bound of success rate
y = scenario_df["mean_success_rate"] + 2 * scenario_df["std_success_rate"]
y = np.minimum(y, 1)
upper_trace = go.Scatter(
name="Upper bound",
x=scenario_df["n_iterations"],
y=y,
mode="lines",
# make the line invisible
line=dict(color="rgba(255,255,255,0)"),
showlegend=False,
# legendgroup="group",
visible=False,
)
# lower std bound of success rate
y = scenario_df["mean_success_rate"] - 2 * scenario_df["std_success_rate"]
y = np.maximum(y, 0)
lower_trace = go.Scatter(
name="Lower bound",
x=scenario_df["n_iterations"],
y=y,
mode="lines",
# make the line invisible
line=dict(color="rgba(255,255,255,0)"),
fill="tonexty",
fillcolor=f"rgba{(*_hex_to_rgb(colors[0]), 0.3)}",
showlegend=False,
# legendgroup="group",
visible=False,
)
return mean_trace, upper_trace, lower_trace | 33,188 |
def create_graph_of_words(words, database, filename, window_size = 4):
"""
Function that creates a Graph of Words that contains all nodes from each document for easy comparison,
inside the neo4j database, using the appropriate cypher queries.
"""
# Files that have word length < window size, are skipped.
# Window size ranges from 2 to 6.
length = len(words)
if (length < window_size):
# Early exit, we return the skipped filename
return filename
# We are using a global set of edges to avoid creating duplicate edges between different graph of words.
# Basically the co-occurences will be merged.
global edges
# We are using a global set of edges to avoid creating duplicate nodes between different graph of words.
# A list is being used to respect the order of appearance.
global nodes
# We are getting the unique terms for the current graph of words.
terms = []
for word in words:
if word not in terms:
terms.append(word)
# Remove end-of-sentence token, so it doesn't get created.
if 'e5c' in terms:
terms.remove('e5c')
# If the word doesn't exist as a node, then create it.
for word in terms:
if word not in nodes:
database.execute(f'CREATE (w:Word {{key: "{word}"}})', 'w')
# Append word to the global node graph, to avoid duplicate creation.
nodes.append(word)
# Create unique connections between existing nodes of the graph.
for i, current in enumerate(words):
# If there are leftover items smaller than the window size, reduce it.
if i + window_size > length:
window_size = window_size - 1
# If the current word is the end of sentence string,
# we need to skip it, in order to go to the words of the next sentence,
# without connecting words of different sentences, in the database.
if current == 'e5c':
continue
# Connect the current element with the next elements of the window size.
for j in range(1, window_size):
next = words[i + j]
# Reached the end of sentence string.
# We can't connect words of different sentences,
# therefore we need to pick a new current word,
# by going back out to the outer loop.
if next == 'e5c':
break
edge = (current, next)
if edge in edges:
# If the edge, exists just update its weight.
edges[edge] = edges[edge] + 1
query = (f'MATCH (w1:Word {{key: "{current}"}})-[r:connects]-(w2:Word {{key: "{next}"}}) '
f'SET r.weight = {edges[edge]}')
else:
# Else, create it, with a starting weight of 1 meaning first co-occurence.
edges[edge] = 1
query = (f'MATCH (w1:Word {{key: "{current}"}}) '
f'MATCH (w2:Word {{key: "{next}"}}) '
f'MERGE (w1)-[r:connects {{weight: {edges[edge]}}}]-(w2)')
# This line of code, is meant to be executed, in both cases of the if...else statement.
database.execute(query, 'w')
# Create a parent node that represents the document itself.
# This node is connected to all words of its own graph,
# and will be used for similarity/comparison queries.
database.execute(f'CREATE (d:Document {{filename: "{filename}"}})', 'w')
# Create a word list with comma separated, quoted strings for use in the Cypher query below.
#word_list = ', '.join(f'"{word}"' for word in terms)
query = (f'MATCH (w:Word) WHERE w.key IN {terms} '
'WITH collect(w) as words '
f'MATCH (d:Document {{filename: "{filename}"}}) '
'UNWIND words as word '
'CREATE (d)-[:includes]->(word)')
database.execute(query, 'w')
return | 33,189 |
def get_dir(path):
"""
Функция возвращает директорию файла, если он является файлом, иначе
возвращает объект Path из указанного пути
"""
if not isinstance(path, Path):
path = Path(path)
return path.parent if path.is_file() else path | 33,190 |
def test_downloads_correct_zipfile(
bite_number: int,
bites_repo_dir: Path,
testing_config,
) -> None:
"""Download a ZIP archive file for a specific bite with correct credentials.
Credentials are obtained either from the environment or the the .env
located in the directory pytest was launched in.
Checks for ZIP file existence before and after the download.
"""
expected = Path(f"cache/pybites_bite{bite_number}.zip").resolve()
assert not expected.exists()
download_bite(
bite_number,
testing_config["PYBITES_USERNAME"],
testing_config["PYBITES_PASSWORD"],
dest_path=bites_repo_dir,
cache_path="cache",
)
assert expected.exists()
assert is_zipfile(expected) | 33,191 |
def get_file_sha(fname):
"""
Calculates the SHA1 of a given file.
`fname`: the file path
return: the calculated SHA1 as hex
"""
result = ''
if isfile(fname):
sha1 = hashlib.sha1()
with open(fname, 'rb') as f:
while True:
data = f.read(BUF_SIZE)
if not data:
break
sha1.update(data)
result = sha1.hexdigest()
return result | 33,192 |
def graphtool_to_gjgf(graph):
"""Convert a graph-tool graph object to gJGF.
Parameters
----------
graph : graph object from graph-tool
Returns
-------
gjgf : dict
Dictionary adhering to
:doc:`gravis JSON Graph Format (gJGF) <../../format_specification>`
Caution
-------
0 and 0.0 values are ignored because they represent missing values in graph-tool.
This can cause problems when such values have the usual meaning of a quantity being zero.
"""
data, data_graph, data_nodes, data_edges = _internal.prepare_gjgf_dict()
# 1) Graph properties
graph_directed = graph.is_directed()
graph_metadata_dict = {key: graph.graph_properties[key] # key syntax is necessary
for key in graph.graph_properties.keys()}
_internal.insert_graph_data(data_graph, graph_directed, graph_metadata_dict)
# 2) Nodes and their properties
for node_object in graph.vertices():
node_id = str(node_object)
node_metadata_dict = {}
for key, value_array in graph.vertex_properties.items():
val = value_array[node_object]
if isinstance(val, (str, int, float)) and val not in ('', 0, 0.0):
node_metadata_dict[key] = val
_internal.insert_node_data(data_nodes, node_id, node_metadata_dict)
# 3) Edges and their properties
for edge_object in graph.edges():
edge_source_id = str(edge_object.source())
edge_target_id = str(edge_object.target())
edge_metadata_dict = {}
for key, value_array in graph.edge_properties.items():
val = value_array[edge_object]
if val not in ('', 0, 0.0):
edge_metadata_dict[key] = val
_internal.insert_edge_data(data_edges, edge_source_id, edge_target_id, edge_metadata_dict)
return data | 33,193 |
def forbidden_error(error):
""" 418 I'm a teapot """
return engine.get_template('errors/417.html').render({}), 418 | 33,194 |
def set(msg_or_dict, key, value):
"""Set a key's value on a protobuf Message or dictionary.
Args:
msg_or_dict (Union[~google.protobuf.message.Message, Mapping]): the
object.
key (str): The key to set.
value (Any): The value to set.
Raises:
TypeError: If ``msg_or_dict`` is not a Message or dictionary.
"""
# Sanity check: Is our target object valid?
if not isinstance(msg_or_dict, (collections_abc.MutableMapping, message.Message)):
raise TypeError(
"set() expected a dict or protobuf message, got {!r}.".format(
type(msg_or_dict)
)
)
# We may be setting a nested key. Resolve this.
basekey, subkey = _resolve_subkeys(key)
# If a subkey exists, then get that object and call this method
# recursively against it using the subkey.
if subkey is not None:
if isinstance(msg_or_dict, collections_abc.MutableMapping):
msg_or_dict.setdefault(basekey, {})
set(get(msg_or_dict, basekey), subkey, value)
return
if isinstance(msg_or_dict, collections_abc.MutableMapping):
msg_or_dict[key] = value
else:
_set_field_on_message(msg_or_dict, key, value) | 33,195 |
def green(s: str) -> str:
"""green(s) color s with green.
This function exists to encapsulate the coloring methods only in utils.py.
"""
return colorama.Fore.GREEN + s + colorama.Fore.RESET | 33,196 |
def show_failed_samples(grading_data_dir_name, subset_name, num_of_samples = 100, run_num = 'run_1'):
"""Predicted Samples Viewer"""
# Count all iamges
path = os.path.join('..', 'data', grading_data_dir_name)
ims = np.array(plotting_tools.get_im_files(path, subset_name))
print('All images: ', len(ims))
# Show samples
im_files, n_preds, n_false_pos, n_false_neg = get_failed_im_file_sample(
grading_data_dir_name, subset_name, run_num, n_file_names=num_of_samples)
print('number of validation samples intersection over the union evaulated on {}'.format(n_preds))
print('number false positives: {}(P={:.6}), number false negatives: {}(P={:.6})'. format(n_false_pos, n_false_pos/n_preds, n_false_neg, n_false_neg/n_preds))
print('number failed: {}(P={:.6})'. format(n_false_pos+n_false_neg, (n_false_pos+n_false_neg)/n_preds))
print()
print('Sample images: ', len(im_files))
for i in range(len(im_files[:num_of_samples])):
print(i)
im_tuple = plotting_tools.load_images(im_files[i])
plotting_tools.show_images(im_tuple) | 33,197 |
def plot_confusion_matrix(label_list, pred_list, classes,dir_out,
normalize=True,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
This function prints and saves the plot of the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
file_name = dir_out+"confusion_matrix"
for c in classes:
file_name= file_name+"_"+c
file_name = file_name.replace(" ","_")
file_name=file_name+".pdf"
pdf = PdfPages(file_name)
fig = plt.figure()
cm = confusion_matrix(label_list, pred_list)
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
print(cm)
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[i, j], fmt),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
pdf.savefig(fig)
plt.close(fig)
pdf.close() | 33,198 |
def get_files(self):
"""func to loop through all the files and buildings and add them to the table widget for selection"""
#
# function to reset the table IMPORTANT
#
resultsDict = {}
if os.path.isfile(self.inpPath):
# case for single file
resultsDict[os.path.basename(self.inpPath)] = get_lods(self.inpPath)
gf.progressLoD(self, 100)
pass
elif os.path.isdir(self.inpPath):
# case for multiple files
filenames = glob.glob(os.path.join(self.inpPath, "*.gml")) + glob.glob(os.path.join(self.inpPath, "*.xml"))
for i, filename in enumerate(filenames):
resultsDict[os.path.basename(filename)] = get_lods(filename)
gf.progressLoD(self, (i + 1) / len(filenames) * 100)
pass
else:
gf.messageBox(self, "ERROR!", "Input path is neither file or directory.\nPlease reselect input data.")
display_file_lod(self, resultsDict)
self.btn_next.setEnabled(True) | 33,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.