content
stringlengths 35
762k
| sha1
stringlengths 40
40
| id
int64 0
3.66M
|
---|---|---|
def same_datatypes(lst):
"""
Überprüft für eine Liste, ob sie nur Daten vom selben Typ enthält. Dabei spielen Keys, Länge der Objekte etc. eine Rolle
:param lst: Liste, die überprüft werden soll
:type lst: list
:return: Boolean, je nach Ausgang der Überprüfung
"""
datatype = type(lst[0]).__name__
for item in lst:
if type(item).__name__ != datatype: # return False, wenn die Liste verschiedene Datentypen enthält
return False
# Datentypen sind gleich, aber sind deren Strukturen auch gleich? (für komplexe Datentypen)
if datatype == "dict":
keys = lst[0].keys()
for item in lst:
if item.keys() != keys: # return False, wenn die Keys der Dictionaries verschieden sind
return False
elif datatype == "list":
if sum([len(x) for x in lst]) / len(lst) != len(lst[0]): # return False, falls die Listen in der Liste verschiedene Längen haben
return False
datatypes = list(map(lambda x: type(x).__name__, lst[0]))
for item in lst:
if list(map(lambda x: type(x).__name__, item)) != datatypes: # return False, falls die Elemente der inneren Listen verschiedene Datenytpen haben
return False
return True | 9c49376ec34ed0970171597f77de4c4c224350b4 | 12,600 |
def _show_stat_wrapper_Progress(count, last_count, start_time, max_count, speed_calc_cycles,
width, q, last_speed, prepend, show_stat_function, add_args,
i, lock):
"""
calculate
"""
count_value, max_count_value, speed, tet, ttg, = Progress._calc(count,
last_count,
start_time,
max_count,
speed_calc_cycles,
q,
last_speed,
lock)
return show_stat_function(count_value, max_count_value, prepend, speed, tet, ttg, width, i, **add_args) | 3c98f44acc8de94573ba37a7785df18fc8e72966 | 12,601 |
def _to_base58_string(prefixed_key: bytes):
"""
Convert prefixed_key bytes into Es/EC strings with a checksum
:param prefixed_key: the EC private key or EC address prefixed with the appropriate bytes
:return: a EC private key string or EC address
"""
prefix = prefixed_key[:PREFIX_LENGTH]
assert prefix == ECAddress.PREFIX or prefix == ECPrivateKey.PREFIX, 'Invalid key prefix.'
temp_hash = sha256(prefixed_key[:BODY_LENGTH]).digest()
checksum = sha256(temp_hash).digest()[:CHECKSUM_LENGTH]
return base58.encode(prefixed_key + checksum) | 326580e714d6489a193347498c68ef9d90f6f651 | 12,602 |
def round_int(n, d):
"""Round a number (float/int) to the closest multiple of a divisor (int)."""
return round(n / float(d)) * d | 372c0f8845994aaa03f99ebb2f65243e6490b341 | 12,603 |
def merge_array_list(arg):
"""
Merge multiple arrays into a single array
:param arg: lists
:type arg: list
:return: The final array
:rtype: list
"""
# Check if arg is a list
if type(arg) != list:
raise errors.AnsibleFilterError('Invalid value type, should be array')
final_list = []
for cur_list in arg:
final_list += cur_list
return final_list | 649412488655542f27a1e7d377252c060107b57e | 12,604 |
def load_callbacks(boot, bootstrap, jacknife,
out, keras_verbose, patience):
"""
Specifies Keras callbacks, including checkpoints, early stopping,
and reducing learning rate.
Parameters
----------
boot
bootstrap
jacknife
out
keras_verbose
patience
batch_size
Returns
-------
checkpointer
earlystop
reducelr
"""
if bootstrap or jacknife:
checkpointer = tf.keras.callbacks.ModelCheckpoint(
filepath=out + "_boot" + str(boot) + "_weights.hdf5",
verbose=keras_verbose,
save_best_only=True,
save_weights_only=True,
monitor="val_loss",
save_freq="epoch",
)
else:
checkpointer = tf.keras.callbacks.ModelCheckpoint(
filepath=out + "_weights.hdf5",
verbose=keras_verbose,
save_best_only=True,
save_weights_only=True,
monitor="val_loss",
save_freq="epoch",
)
earlystop = tf.keras.callbacks.EarlyStopping(
monitor="val_loss", min_delta=0, patience=patience
)
reducelr = tf.keras.callbacks.ReduceLROnPlateau(
monitor="val_loss",
factor=0.5,
patience=int(patience / 6),
verbose=keras_verbose,
mode="auto",
min_delta=0,
cooldown=0,
min_lr=0,
)
return checkpointer, earlystop, reducelr | 0ca09ccaca4424c1a546caade3d809b7f69cbb5e | 12,605 |
def build_sentence_model(cls, vocab_size, seq_length, tokens, transitions,
num_classes, training_mode, ground_truth_transitions_visible, vs,
initial_embeddings=None, project_embeddings=False, ss_mask_gen=None, ss_prob=0.0):
"""
Construct a classifier which makes use of some hard-stack model.
Args:
cls: Hard stack class to use (from e.g. `spinn.fat_stack`)
vocab_size:
seq_length: Length of each sequence provided to the stack model
tokens: Theano batch (integer matrix), `batch_size * seq_length`
transitions: Theano batch (integer matrix), `batch_size * seq_length`
num_classes: Number of output classes
training_mode: A Theano scalar indicating whether to act as a training model
with dropout (1.0) or to act as an eval model with rescaling (0.0).
ground_truth_transitions_visible: A Theano scalar. If set (1.0), allow the model access
to ground truth transitions. This can be disabled at evaluation time to force Model 1
(or 2S) to evaluate in the Model 2 style with predicted transitions. Has no effect on Model 0.
vs: Variable store.
"""
# Prepare layer which performs stack element composition.
if cls is spinn.plain_rnn.RNN:
if FLAGS.use_gru:
compose_network = partial(util.GRULayer,
initializer=util.HeKaimingInitializer())
else:
compose_network = partial(util.LSTMLayer,
initializer=util.HeKaimingInitializer())
embedding_projection_network = None
elif cls is spinn.cbow.CBOW:
compose_network = None
embedding_projection_network = None
else:
if FLAGS.lstm_composition:
if FLAGS.use_gru:
compose_network = partial(util.TreeGRULayer,
initializer=util.HeKaimingInitializer())
else:
compose_network = partial(util.TreeLSTMLayer,
initializer=util.HeKaimingInitializer())
else:
assert not FLAGS.connect_tracking_comp, "Can only connect tracking and composition unit while using TreeLSTM"
compose_network = partial(util.ReLULayer,
initializer=util.HeKaimingInitializer())
if project_embeddings:
embedding_projection_network = util.Linear
else:
assert FLAGS.word_embedding_dim == FLAGS.model_dim, \
"word_embedding_dim must equal model_dim unless a projection layer is used."
embedding_projection_network = util.IdentityLayer
# Build hard stack which scans over input sequence.
sentence_model = cls(
FLAGS.model_dim, FLAGS.word_embedding_dim, vocab_size, seq_length,
compose_network, embedding_projection_network, training_mode, ground_truth_transitions_visible, vs,
predict_use_cell=FLAGS.predict_use_cell,
use_tracking_lstm=FLAGS.use_tracking_lstm,
tracking_lstm_hidden_dim=FLAGS.tracking_lstm_hidden_dim,
X=tokens,
transitions=transitions,
initial_embeddings=initial_embeddings,
embedding_dropout_keep_rate=FLAGS.embedding_keep_rate,
ss_mask_gen=ss_mask_gen,
ss_prob=ss_prob,
connect_tracking_comp=FLAGS.connect_tracking_comp,
context_sensitive_shift=FLAGS.context_sensitive_shift,
context_sensitive_use_relu=FLAGS.context_sensitive_use_relu,
use_input_batch_norm=False)
# Extract top element of final stack timestep.
if FLAGS.lstm_composition or cls is spinn.plain_rnn.RNN:
sentence_vector = sentence_model.final_representations[:,:FLAGS.model_dim / 2].reshape((-1, FLAGS.model_dim / 2))
sentence_vector_dim = FLAGS.model_dim / 2
else:
sentence_vector = sentence_model.final_representations.reshape((-1, FLAGS.model_dim))
sentence_vector_dim = FLAGS.model_dim
sentence_vector = util.BatchNorm(sentence_vector, sentence_vector_dim, vs, "sentence_vector", training_mode)
sentence_vector = util.Dropout(sentence_vector, FLAGS.semantic_classifier_keep_rate, training_mode)
# Feed forward through a single output layer
logits = util.Linear(
sentence_vector, sentence_vector_dim, num_classes, vs,
name="semantic_classifier", use_bias=True)
return sentence_model.transitions_pred, logits | 085d6a0538bfa06a34c543c27efd651c4c46168a | 12,606 |
def read_xls_as_dict(filename, header="top"):
"""
Read a xls file as dictionary.
@param filename File name (*.xls or *.xlsx)
@param header Header position. Options: "top", "left"
@return Dictionary with header as key
"""
table = read_xls(filename)
if (header == "top"):
return read_table_header_top(table)
elif (header == "left"):
return read_table_header_left(table)
else:
return {} | 9ed410e42a11ee898466bb2f36b6d02e051b21ec | 12,607 |
def check_hostgroup(zapi, region_name, cluster_id):
"""check hostgroup from region name if exists
:region_name: region name of hostgroup
:returns: true or false
"""
return zapi.hostgroup.exists(name="Region [%s %s]" % (region_name, cluster_id)) | b237b544ac59331ce94dd1ac471187a60d527a1b | 12,608 |
import tempfile
def matlab_to_tt(ttemps, eng, is_orth=True, backend="numpy", mode="l"):
"""Load matlab.object representing TTeMPS into Python as TT"""
_, f = tempfile.mkstemp(suffix=".mat")
eng.TTeMPS_to_Py(f, ttemps, nargout=0)
tt = load_matlab_tt(f, is_orth=is_orth, mode=mode, backend=backend)
return tt | e21087e2587368a55ece7a50f576573c5284373a | 12,609 |
def encode_mecab(tagger, string):
"""
string을 mecab을 이용해서 형태소 분석
:param tagger: 형태소 분석기 객체
:param string: input text
:return tokens: 형태소 분석 결과
:return indexs: 띄어쓰기 위치
"""
string = string.strip()
if len(string) == 0:
return [], []
words = string.split()
nodes = tagger.pos(" ".join(words))
tokens = []
for node in nodes:
surface = node[0].strip()
if 0 < len(surface):
for s in surface.split(): # mecab 출력 중 '영치기 영차' 처리
tokens.append(s)
indexs = []
index, start, end = -1, 0, 100000
for i, token in enumerate(tokens): # 분류가 잘 되었는지 검증
if end < len(words[index]):
start = end
end += len(token)
else:
index += 1
start = 0
end = len(token)
indexs.append(i) # values 중 실제 시작 위치 기록
assert words[index][start:end] == token, f"{words[index][start:end]} != {token}"
return tokens, indexs | 847278728ebe7790d8aef2a125a420d5779adc6b | 12,610 |
def nutrient_limited_growth(X,idx_A,idx_B,growth_rate,half_saturation):
""" non-linear response with respect to *destination/predator* compartment
Similar to holling_type_II and is a reparameterization of holling II.
The response with respect to the origin compartment 'B' is approximately
linear for small 'B' and converges towards an upper limit governed by the
'growth_rate' for large 'B'.
For examples see:
`Examples <https://gist.github.com/465b/cce390f58d64d70613a593c8038d4dc6>`_
Parameters
----------
X : np.array
containing the current state of the contained quantity of each
compartment
idx_A : integer
index of the element representing the destination/predator compartment
idx_B : integer
index of the element representing the origin/pray compartment
growth_rate : float
first parameter of the interaction.
governs the upper limit of the response.
half_saturation : float
second parameter of the interaction.
governs the slope of the response.
Returns
-------
df : float
change in the origin and destitnation compartment. Calculated by
consumption_rate = ((hunting_rate * origin_compartment) / (1 +
hunting_rate * food_processing_time * origin_compartment)) *
destination_compartment
"""
A = X[idx_A] # quantity of compartment A (predator/consumer)
B = X[idx_B] # quantity of compartment B (prey/nutrient)
df = growth_rate*(B/(half_saturation+B))*A
return df | 05e66a0e426a404a5356f04f8568ab23548b6dbe | 12,611 |
def aes128_decrypt(AES_KEY, _data):
"""
AES 128 位解密
:param requestData:
:return:
"""
# 秘钥实例
newAes = getAesByKey(AES_KEY)
# 解密
data = newAes.decrypt(_data)
rawDataLength = len(data)
# 剔除掉数据后面的补齐位
paddingNum = ord(data[rawDataLength - 1])
if paddingNum > 0 and paddingNum <= 16:
data = data[0:(rawDataLength - paddingNum)]
return data | 520c03a509f63807a62ccb0385e99bc9b674fd67 | 12,612 |
def human_readable_size(size, decimals=1):
"""Transform size in bytes into human readable text."""
for unit in ["B", "KB", "MB", "GB", "TB"]:
if size < 1000:
break
size /= 1000
return f"{size:.{decimals}f} {unit}" | 5fb0dc79162d0bc0a945061aa0889735b24fff7b | 12,613 |
def generichash_blake2b_final(statebuf, digest_size):
"""Finalize the blake2b hash state and return the digest.
:param statebuf:
:type statebuf: bytes
:param digest_size:
:type digest_size: int
:return: the blake2 digest of the passed-in data stream
:rtype: bytes
"""
_digest = ffi.new("unsigned char[]", crypto_generichash_BYTES_MAX)
rc = lib.crypto_generichash_blake2b_final(statebuf, _digest, digest_size)
ensure(rc == 0, 'Unexpected failure',
raising=exc.RuntimeError)
return ffi.buffer(_digest, digest_size)[:] | a81da8346bafb2f7d8fd40b0d9ff204689d002f8 | 12,614 |
def walker_input_formatter(t, obs):
"""
This function formats the data to give as input to the controller
:param t:
:param obs:
:return: None
"""
return obs | 651038cd4dc0e8c8ccb89a10a5b20f6031e17ba8 | 12,615 |
def build_url_base(url):
"""Normalize and build the final url
:param url: The given url
:type url: str
:return: The final url
:rtype: str
"""
normalize = normalize_url(url=url)
final_url = "{url}/api".format(url=normalize)
return final_url | a500a6d96ab637182abab966817209324ddc670a | 12,616 |
from typing import Tuple
from typing import List
def build_decoder(
latent_dim: int,
input_shape: Tuple,
encoder_shape: Tuple,
filters: List[int],
kernels: List[Tuple[int, int]],
strides: List[int]
) -> Model:
"""Return decoder model.
Parameters
----------
latent_dim:int,
Size of the latent vector.
encoder_shape:Tuple,
Output shape of the last convolutional layer
of the encoder model.
filters:List[int],
List of filters for the convolutional layer.
kernels:List[Tuple[int, int]],
List of kernel sizes for the convolutional layer.
strides:List[int]
List of strides for the convolutional layer.
"""
decoder_input = Input(
shape=(latent_dim,),
name='decoder_input'
)
x = Dense(np.prod(encoder_shape))(decoder_input)
x = Reshape(encoder_shape)(x)
x = decoder_blocks(
x,
reversed(filters),
reversed(kernels),
reversed(strides)
)
decoder_output = Conv2DTranspose(
filters=1,
kernel_size=kernels[0],
activation=axis_softmax,
padding='same',
name='decoder_output'
)(x)
reshape = Reshape(input_shape)(decoder_output)
# Instantiate Decoder Model
return Model(
decoder_input,
reshape,
name='decoder'
) | efdac0fa9df81249e531b2568cd8f91816c209a6 | 12,617 |
def execute_with_python_values(executable, arguments=(), backend=None):
"""Execute on one replica with Python values as arguments and output."""
backend = backend or get_local_backend()
def put(arg):
return Buffer.from_pyval(
arg, device=executable.DeviceOrdinals()[0], backend=backend)
arguments = [put(arg) for arg in arguments]
return executable.Execute(arguments).to_py() | 26c9352feb2e5c7e6fb46702105245f582218e91 | 12,618 |
import subprocess
def run_cmd(cmd, cwd=None):
"""
Runs the given command and return the output decoded as UTF-8.
"""
return subprocess.check_output(cmd,
cwd=cwd, encoding="utf-8", errors="ignore") | 5d2f5b85878291efaa16dcb4bb8a8c72b3d22230 | 12,619 |
def _get_label_members(X, labels, cluster):
"""
Helper function to get samples of a specified cluster.
Args:
X (np.ndarray): ndarray with dimensions [n_samples, n_features]
data to check validity of clustering
labels (np.array): clustering assignments for data X
cluster (int): cluster of interest
Returns: members (np.ndarray)
array of dimensions (n_samples, n_features) of samples of the
specified cluster.
"""
indices = np.where(labels == cluster)[0]
members = X[indices]
return members | 18c213f88816108f93ddd38cdd2c934f431ea35a | 12,620 |
from typing import Tuple
def get_spectrum_by_close_values(
mz: list,
it: list,
left_border: float,
right_border: float,
*,
eps: float = 0.0
) -> Tuple[list, list, int, int]:
"""int
Function to get segment of spectrum by left and right
border
:param mz: m/z array
:param it: it intensities
:param left_border: left border
:param right_border: right border
:param eps: epsilon to provide regulation of borders
:return: closest to left and right border values of spectrum, left and right
"""
mz, it = mz.copy(), it.copy()
left = bisect_left(mz, left_border - eps)
right = bisect_right(mz, right_border + eps)
return mz[left:right].copy(), it[left:right].copy(), left, right | 0ec34b044b9105fe1c232baa9b51760cbb96b9d9 | 12,621 |
import subprocess
import os
def speak():
"""API call to have BiBli speak a phrase."""
subprocess.call("amixer sset Master 100%", shell=True)
data = request.get_json()
lang = data["lang"] if "lang" in data and len(data["lang"]) else "en"
#espeak.set_parameter(espeak.Parameter.Rate, 165)
#espeak.set_parameter(espeak.Parameter.Pitch, 70)
if lang == "es":
# espeak.set_voice("europe/es")
os.system("sudo espeak -v es '" + data["msg"] + "' -a 165 -p 70")
else:
os.system("sudo espeak -v en-us '" + data["msg"] + "' -a 165 -p 70")
# espeak.set_voice("en-us")
# espeak.synth(data["msg"])
# subprocess.call('espeak -v%s+f3 -a200 %s &' % (lang, "'\"%s\"'" % data["msg"]), shell=True)
return jsonify({}) | 81e75e88669ca90ff8f9dc6df8a7a8a08dcaf368 | 12,622 |
def refresh_wrapper(trynum, maxtries, *args, **kwargs):
"""A @retry argmod_func to refresh a Wrapper, which must be the first arg.
When using @retry to decorate a method which modifies a Wrapper, a common
cause of retry is etag mismatch. In this case, the retry should refresh
the wrapper before attempting the modifications again. This method may be
passed to @retry's argmod_func argument to effect such a refresh.
Note that the decorated method must be defined such that the wrapper is its
first argument.
"""
arglist = list(args)
# If we get here, we *usually* have an etag mismatch, so specifying
# use_etag=False *should* be redundant. However, for scenarios where we're
# retrying for some other reason, we want to guarantee a fresh fetch to
# obliterate any local changes we made to the wrapper (because the retry
# should be making those changes again).
arglist[0] = arglist[0].refresh(use_etag=False)
return arglist, kwargs | 089b859964e89d54def0058abc9cc7536f5d8877 | 12,623 |
def compute_frames_per_animation(
attacks_per_second: float,
base_animation_length: int,
speed_coefficient: float = 1.0,
engine_tick_rate: int = 60,
is_channeling: bool = False) -> int:
"""Calculates frames per animation needed to resolve a certain ability at attacks_per_second.
Args:
attacks_per_second: attacks per second of character
base_animation_length: animation length of ability
speed_coefficient: speed-up scalar of ability
engine_tick_rate: server tick rate
is_channeling: whether or not the ability is a channeling skill
Returns:
int: number of frames one casts needs to resolve for
"""
_coeff = engine_tick_rate / (attacks_per_second * speed_coefficient)
if is_channeling:
return np.floor(_coeff)
else:
return np.ceil((base_animation_length - 1) / base_animation_length * _coeff) | 44427cf28152de21de42f0220e75f87717235275 | 12,624 |
def pad_rect(rect, move):
"""Returns padded rectangles given specified padding"""
if rect['dx'] > 2:
rect['x'] += move[0]
rect['dx'] -= 1*move[0]
if rect['dy'] > 2:
rect['y'] += move[1]
rect['dy'] -= 1*move[1]
return rect | 48bdbdc9d4736e372afc983ab5966fc80a221d4d | 12,625 |
import asyncio
async def yes_no(ctx: commands.Context,
message: str="Are you sure? Type **yes** within 10 seconds to confirm. o.o"):
"""Yes no helper. Ask a confirmation message with a timeout of 10 seconds.
ctx - The context in which the question is being asked.
message - Optional messsage that the question should ask.
"""
await ctx.send(message)
try:
message = await ctx.bot.wait_for("message", timeout=10,
check=lambda message: message.author == ctx.message.author)
except asyncio.TimeoutError:
await ctx.send("Timed out waiting. :<")
return False
if message.clean_content.lower() not in ["yes", "y"]:
await ctx.send("Command cancelled. :<")
return False
return True | 2b8ab0bfc51d4be68a42507bad6dbb945465d2e4 | 12,626 |
def __validation(size: int, it1: int, it2: int, it3: int, it4: int) -> bool:
""" Проверка на корректность тура
size: размер маршрута
it1, it2, it3, it4: индексы городов: t1, t2i, t2i+1, t2i+2
return: корректен или нет
"""
return between(size, it1, it3, it4) and between(size, it4, it2, it1) | 5fcb29f45c456115e8b87f0313e05f327c702849 | 12,627 |
def get_type_associations(base_type, generic_base_type): # type: (t.Type[TType], t.Type[TValue]) -> t.List[t.Tuple[t.Type[TValue], t.Type[TType]]]
"""Create and return a list of tuples associating generic_base_type derived types with a corresponding base_type derived type."""
return [item for item in [(get_generic_type(sc_type, generic_base_type), sc_type) for sc_type in get_subclasses(base_type)] if item[1]] | fe18bf72a96d6dfa8fad2c625732e781d54cae4d | 12,628 |
import rpy2.robjects as robj
from rpy2.robjects.packages import importr
import anndata2ri
def identify_empty_droplets(data, min_cells=3, **kw):
"""Detect empty droplets using DropletUtils
"""
importr("DropletUtils")
adata = data.copy()
col_sum = adata.X.sum(0)
if hasattr(col_sum, 'A'):
col_sum = col_sum.A.squeeze()
keep = col_sum > min_cells
adata = adata[:,keep]
#adata.X = adata.X.tocsc()
anndata2ri.activate()
robj.globalenv["X"] = adata
res = robj.r('res <- emptyDrops(assay(X))')
anndata2ri.deactivate()
keep = res.loc[res.FDR<0.01,:]
data = data[keep.index,:]
data.obs['empty_FDR'] = keep['FDR']
return data | 9c2d532d75afb6044836249eb525e86c60511c9b | 12,629 |
def catalog_category_RSS(category_id):
"""
Return an RSS feed containing all items in the specified category_id
"""
items = session.query(Item).filter_by(
category_id=category_id).all()
doc = jaxml.XML_document()
doc.category(str(category_id))
for item in items:
doc._push()
doc.item()
doc.id(item.id)
doc.name(item.name)
doc.description(item.description)
doc.imagepath('"' + item.image + '"')
doc.category_id(item.category_id)
doc.user_id(item.user_id)
doc._pop()
return doc.__repr__() | 13554cf1eba3a83c0fb23a6f848751721579dfea | 12,630 |
def get_caller_name(N=0, allow_genexpr=True):
"""
get the name of the function that called you
Args:
N (int): (defaults to 0) number of levels up in the stack
allow_genexpr (bool): (default = True)
Returns:
str: a function name
CommandLine:
python -m utool.util_dbg get_caller_name
python -m utool get_caller_name
python ~/code/utool/utool/__main__.py get_caller_name
python ~/code/utool/utool/__init__.py get_caller_name
python ~/code/utool/utool/util_dbg.py get_caller_name
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dbg import * # NOQA
>>> import utool as ut
>>> N = list(range(0, 13))
>>> allow_genexpr = True
>>> caller_name = get_caller_name(N, allow_genexpr)
>>> print(caller_name)
"""
if isinstance(N, (list, tuple, range)):
name_list = []
for N_ in N:
try:
name_list.append(get_caller_name(N_))
except AssertionError:
name_list.append('X')
return '[' + ']['.join(name_list) + ']'
parent_frame = get_stack_frame(N=N + 2)
caller_name = parent_frame.f_code.co_name
co_filename = parent_frame.f_code.co_filename
if not allow_genexpr:
count = 0
while True:
count += 1
if caller_name == '<genexpr>':
parent_frame = get_stack_frame(N=N + 1 + count)
caller_name = parent_frame.f_code.co_name
else:
break
#try:
# if 'func' in parent_frame.f_locals:
# caller_name += '(' + meta_util_six.get_funcname(parent_frame.f_locals['func']) + ')'
#except Exception:
# pass
if caller_name == '<module>':
# Make the caller name the filename
caller_name = splitext(split(co_filename)[1])[0]
if caller_name in {'__init__', '__main__'}:
# Make the caller name the filename
caller_name = basename(dirname(co_filename)) + '.' + caller_name
return caller_name | 6c6ce7690d1bc4bd51037056e27f5dbd73085e29 | 12,631 |
import os
import tempfile
def make_build_dir(prefix=""):
"""Creates a temporary folder with given prefix to be used as a build dir.
Use this function instead of tempfile.mkdtemp to ensure any generated files
will survive on the host after the FINN Docker container exits."""
try:
inst_prefix = os.environ["FINN_INST_NAME"] + "/"
tempfile.tempdir = get_finn_root() + "/tmp/"
return tempfile.mkdtemp(prefix=inst_prefix + prefix)
except KeyError:
raise Exception(
"""Environment variable FINN_INST_NAME must be set
correctly. Please ensure you have launched the Docker contaier correctly.
"""
) | c298ed1446412b048f632daf8797670fc3b9095c | 12,632 |
from typing import Union
import json
def unblock_node_port_random(genesis_file: str,
transactions: Union[str,int] = None,
pause_before_synced_check: Union[str,int] = None, best_effort: bool = True,
did: str = DEFAULT_CHAOS_DID, seed: str = DEFAULT_CHAOS_SEED,
wallet_name: str = DEFAULT_CHAOS_WALLET_NAME,
wallet_key: str = DEFAULT_CHAOS_WALLET_KEY, pool: str = DEFAULT_CHAOS_POOL,
ssh_config_file: str = DEFAULT_CHAOS_SSH_CONFIG_FILE) -> bool:
"""
Unblock nodes randomly selected by calling block_node_port_random
State file "block_node_port_random" located in the chaos temp dir (see
get_chaos_temp_dir for details) is shared with the following functions
block_node_port_random
unblock_node_port_random
unblocked_nodes_are_caught_up
Because the aforementioned functions share a state file, they are intended
to be used together. The typical/suggested workflow would be:
1. Block the node port on some nodes (block_node_port_random)
2. Optionally do something while node ports are blocked (i.e. generate load)
3. Unblock node port on the set of nodes selected in step 1 above.
4. Optionally do something while nodes are catching up.
5. Check if nodes unblocked in step 3 above are caught up.
:param genesis_file: The relative or absolute path to a genesis file.
Required.
:type genesis_file: str
:param transactions: Expected number of transactions on the domain ledger
after catchup has completed.
Optional. (Default: None)
:type transactions: Union[str,int]
:param pause_before_synced_check: Seconds to pause before checking if a node
is synced.
Optional. (Default: None)
:type pause_before_synced_check: Union[str,int]
:param best_effort: Attempt to unblock ports blocked when calling
block_node_port_random. Do not fail if the block_node_port_random state
file does not exist, if an error/exception is encountered while
unblocking a node port on any of the nodes, or if fewer than expected
nodes were unblocked.
Optional. (Default: True)
:type best_effort: bool
:param did: A steward or trustee DID. A did OR a seed is required, but not
both. The did will be used if both are given. Needed to get validator
info.
Optional. (Default: chaosindy.common.DEFAULT_CHAOS_DID)
:type did: str
:param seed : A steward or trustee seed. A did OR a seed is required, but
not both. The did will be used if both are given. Needed to get
validator info.
Optional. (Default: chaosindy.common.DEFAULT_CHAOS_SEED)
:type seed: str
:param wallet_name: The name of the wallet to use when getting validator
info.
Optional. (Default: chaosindy.common.DEFAULT_CHAOS_WALLET_NAME)
:type wallet_name: str
:param wallet_key: The key to use when opening the wallet designated by
wallet_name.
Optional. (Default: chaosindy.common.DEFAULT_CHAOS_WALLET_KEY)
:type wallet_key: str
:param pool: The pool to connect to when getting validator info.
Optional. (Default: chaosindy.common.DEFAULT_CHAOS_POOL)
:type pool: str
:param ssh_config_file: The relative or absolute path to the SSH config
file.
Optional. (Default: chaosindy.common.DEFAULT_CHAOS_SSH_CONFIG_FILE)
:type ssh_config_file: str
:return: bool
"""
# TODO: Use the traffic shaper tool Kelly is using.
# http://www.uponmyshoulder.com/blog/2013/simulating-bad-network-conditions-on-linux/
#
# This function assumes that block_node_port_random has been called and a
# "block_node_port_random" file has been created in a temporary directory
# created using rules defined by get_chaos_temp_dir()
output_dir = get_chaos_temp_dir()
blocked_ports = {}
try:
with open(join(output_dir, "block_node_port_random"), "r") as f:
blocked_ports = json.load(f)
except Exception as e:
# Do not fail on exceptions like FileNotFoundError if best_effort is
# True
if best_effort:
return True
else:
raise e
selected = blocked_ports.keys()
unblocked = 0
tried_to_unblock = 0
# Keep track of nodes/ports that could not be unblocked either by the
# experiment's method or rollback segments and write it back to
# block_node_port_random in the experiement's temp directory
still_blocked_ports = {}
for node in selected:
logger.debug("node alias to unblock: %s", node)
try:
if unblock_port_by_node_name(node, str(blocked_ports[node]),
ssh_config_file):
unblocked += 1
else:
still_blocked_ports[node] = blocked_ports[node]
except Exception as e:
if best_effort:
pass
tried_to_unblock += 1
logger.debug("unblocked: %s -- tried_to_unblock: %s -- len-aliases: %s",
unblocked, tried_to_unblock, len(selected))
if not best_effort and unblocked < len(selected):
return False
# Only check if resurrected nodes are caught up if both a pause and number
# of transactions are given.
if pause_before_synced_check and transactions:
logger.debug("Pausing %s seconds before checking if unblocked nodes " \
"are synced...", pause_before_synced_check)
# TODO: Use a count down timer? May be nice for those who are running
# experiments manually.
sleep(int(pause_before_synced_check))
logger.debug("Checking if unblocked nodes are synced and report %s " \
"transactions...", transactions)
return unblocked_nodes_are_caught_up(genesis_file, transactions, did,
seed, wallet_name, wallet_key,
pool, ssh_config_file)
return True | bc15266faa6b6c78cc37fca18bfa43ac7dd752c3 | 12,633 |
from typing import Any
def create_user(
*,
db: Session = Depends(deps.get_db),
user_in: schema_in.UserCreateIn,
) -> Any:
"""
Create new user.
"""
new_user = User(**{k: v for k, v in user_in.dict().items() if k != 'password'})
new_user.hashed_password = get_password_hash(user_in.password)
new_user.gid = -1
try:
db.add(new_user)
db.commit()
except IntegrityError:
db.rollback()
raise HTTPException(
status_code=400,
detail="The user with this username already exists in the system.",
)
new_role = Role(uid=new_user.uid, nickname=new_user.nickname, avatar=new_user.avatar, gid=-1)
new_role.reset()
db.add(new_role)
db.commit()
return GameEnum.OK.digest() | cd8c3036026639d3e29e6dc030335f328d11c144 | 12,634 |
import math
def number_format(interp, num_args, number, decimals=0, dec_point='.',
thousands_sep=','):
"""Format a number with grouped thousands."""
if num_args == 3:
return interp.space.w_False
ino = int(number)
dec = abs(number - ino)
rest = ""
if decimals == 0 and dec >= 0.5:
if number > 0:
ino += 1
else:
ino -= 1
elif decimals > 0:
s_dec = str(dec)
if decimals + 2 < len(s_dec):
if ord(s_dec[decimals + 2]) >= ord('5'):
dec += math.pow(10, -decimals)
if dec >= 1:
if number > 0:
ino += 1
else:
ino -= 1
rest = "0" * decimals
else:
s_dec = str(dec)
if not rest:
rest = s_dec[2:decimals + 2]
else:
rest = s_dec[2:] + "0" * (decimals - len(s_dec) + 2)
s = str(ino)
res = []
i = 0
while i < len(s):
res.append(s[i])
if s[i] != '-' and i != len(s) - 1 and (len(s) - i - 1) % 3 == 0:
for item in thousands_sep:
res.append(item)
i += 1
if decimals > 0:
for item in dec_point:
res.append(item)
return interp.space.wrap("".join(res) + rest) | 9d5ab0b9ed5dd6054ce4f356e6811c1b155e2062 | 12,635 |
from typing import Optional
def _serialization_expr(value_expr: str, a_type: mapry.Type,
py: mapry.Py) -> Optional[str]:
"""
Generate the expression of the serialization of the given value.
If no serialization expression can be generated (e.g., in case of nested
structures such as arrays and maps), None is returned.
:param value_expr: Python expression of the value to be serialized
:param a_type: the mapry type of the value
:param py: Python settings
:return: generated expression, or None if not possible
"""
result = None # type: Optional[str]
if isinstance(a_type,
(mapry.Boolean, mapry.Integer, mapry.Float, mapry.String)):
result = value_expr
elif isinstance(a_type, mapry.Path):
if py.path_as == 'str':
result = value_expr
elif py.path_as == 'pathlib.Path':
result = 'str({})'.format(value_expr)
else:
raise NotImplementedError(
"Unhandled path_as: {}".format(py.path_as))
elif isinstance(a_type, (mapry.Date, mapry.Datetime, mapry.Time)):
result = '{value_expr}.strftime({dt_format!r})'.format(
value_expr=value_expr, dt_format=a_type.format)
elif isinstance(a_type, mapry.TimeZone):
if py.timezone_as == 'str':
result = value_expr
elif py.timezone_as == 'pytz.timezone':
result = 'str({})'.format(value_expr)
else:
raise NotImplementedError(
'Unhandled timezone_as: {}'.format(py.timezone_as))
elif isinstance(a_type, mapry.Duration):
result = '_duration_to_string({})'.format(value_expr)
elif isinstance(a_type, mapry.Array):
result = None
elif isinstance(a_type, mapry.Map):
result = None
elif isinstance(a_type, mapry.Class):
result = "{}.id".format(value_expr)
elif isinstance(a_type, mapry.Embed):
result = "serialize_{}({})".format(
mapry.py.naming.as_variable(a_type.name), value_expr)
else:
raise NotImplementedError(
"Unhandled serialization expression of type: {}".format(a_type))
return result | 5920a4c10dabe2ff061a1f141cd9c9f10faebafa | 12,636 |
def get_init_hash():
""" 获得一个初始、空哈希值 """
return imagehash.ImageHash(np.zeros([8, 8]).astype(bool)) | cd4665e6b5cdf232883093dab660aafcc2109a44 | 12,637 |
def get_vertex_between_points(point1, point2, at_distance):
"""Returns vertex between point1 and point2 at a distance from point1.
Args:
point1: First vertex having tuple (x,y) co-ordinates.
point2: Second vertex having tuple (x,y) co-ordinates.
at_distance: A distance at which to locate the vertex on the line joining point1 and point2.
Returns:
A Point object.
"""
line = LineString([point1, point2])
new_point = line.interpolate(at_distance)
return new_point | acb5cd76ef7dd3a16592c5fbaf74d6d777ab338c | 12,638 |
def disable_cache(response: Response) -> Response:
"""Prevents cached responses"""
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate, public, max-age=0"
response.headers["Expires"] = 0
response.headers["Pragma"] = "no-cache"
return response | 6f63c7e93a7c354c85171652dca51162e15b7137 | 12,639 |
def get_dir(src_point, rot_rad):
"""Rotate the point by `rot_rad` degree."""
sn, cs = np.sin(rot_rad), np.cos(rot_rad)
src_result = [0, 0]
src_result[0] = src_point[0] * cs - src_point[1] * sn
src_result[1] = src_point[0] * sn + src_point[1] * cs
return src_result | 40b36671c50a6b6b8905eca9915901cd613c2aaa | 12,640 |
def sparse_gauss_seidel(A,b,maxiters=100,tol=1e-8):
"""Returns the solution to the system Ax = b using the Gauss-Seidel method.
Inputs:
A (array) - 2D scipy.sparse matrix
b (array) - 1D NumPy array
maxiters (int, optional) - maximum iterations for algorithm to perform.
tol (float) - tolerance for convergence
Returns:
x (array) - solution to system Ax = b.
x_approx (list) - list of approximations at each iteration.
"""
if type(A) != spar.csr_matrix:
A = spar.csr_matrix(A)
n = A.shape[0]
x0 = np.zeros(n)
x = np.ones(n)
x_approx = []
for k in xrange(maxiters):
x = x0.copy()
diag = A.diagonal()
for i in xrange(n):
rowstart = A.indptr[i]
rowend = A.indptr[i+1]
Aix = np.dot(A.data[rowstart:rowend],
x[A.indices[rowstart:rowend]])
x[i] += (b[i] - Aix)/diag[i]
if np.max(np.abs(x0-x)) < tol:
return x, x_approx
x0 = x
x_approx.append(x)
print "Maxiters hit!"
return x, x_approx | 139fefa8e45d14f32ea9bb4dd25df03762737090 | 12,641 |
def delete_user(user_id):
"""Delete user from Users database and their permissions
from SurveyPermissions and ReportPermissions.
:Route: /api/user/<int:user_id>
:Methods: DELETE
:Roles: s
:param user_id: user id
:return dict: {"delete": user_id}
"""
user = database.get_user(user_id)
database.delete_user(user)
return {"delete": user.id} | c8f86dc20db67a5e3511e082f6308903b1acdaa2 | 12,642 |
def selectTopFive(sortedList):
"""
从sortedList中选出前五,返回对应的名字与commit数量列成的列表
:param sortedList:按值从大到小进行排序的authorDict
:return:size -- [commit数量]
labels -- [名字]
"""
size = []
labels = []
for i in range(5):
labels.append(sortedList[i][0])
size.append(sortedList[i][1])
return size, labels | 747ad379ed73aeb6ccb48487b48dc6150350204e | 12,643 |
def get_license(file):
"""Returns the license from the input file.
"""
# Collect the license
lic = ''
for line in file:
if line.startswith('#include') or line.startswith('#ifndef'):
break
else:
lic += line
return lic | 126fff2dd0464ef1987f3ab672f6b36b8fa962f7 | 12,644 |
def quote_query_string(chars):
"""
Multibyte charactor string is quoted by double quote.
Because english analyzer of Elasticsearch decomposes
multibyte character strings with OR expression.
e.g. 神保町 -> 神 OR 保 OR 町
"神保町"-> 神保町
"""
if not isinstance(chars, unicode):
chars = chars.decode('utf-8')
token = u''
qs = u''
in_escape = False
in_quote = False
in_token = False
for c in chars:
# backslash escape
if in_escape:
token += c
in_escape = False
continue
if c == u'\\':
token += c
in_escape = True
continue
# quote
if c != u'"' and in_quote:
token += c
continue
if c == u'"' and in_quote:
token += c
qs += token
token = u''
in_quote = False
continue
# otherwise: not in_quote
if _is_delimiter(c) or c == u'"':
if in_token:
qs += _quote_token(token)
token = u''
in_token = False
if c == u'"':
token += c
in_quote = True
else:
qs += c
continue
# otherwise: not _is_delimiter(c)
token += c
in_token = True
if token:
qs += _quote_token(token)
return qs | 8d1888df17a617d42e6a0d1b909e08e4f84fa4c9 | 12,645 |
def copy_params(params: ParamsDict) -> ParamsDict:
"""copy a parameter dictionary
Args:
params: the parameter dictionary to copy
Returns:
the copied parameter dictionary
Note:
this copy function works recursively on all subdictionaries of the params
dictionary but does NOT copy any non-dictionary values.
"""
validate_params(params)
params = {**params}
if all(isinstance(v, dict) for v in params.values()):
return {k: copy_params(params[k]) for k in params}
return params | 8248b31698f6b51103dc34bad7b13373591b10cd | 12,646 |
def watch_list(request):
"""
Get watchlist or create a watchlist, or delete from watchlist
:param request:
:return:
"""
if request.method == 'GET':
watchlist = WatchList.objects.filter(user=request.user)
serializer = WatchListSerializer(watchlist, many=True)
return Response(data=serializer.data, status=status.HTTP_200_OK)
elif request.method == 'POST':
movie_id = request.data.get('movie_id')
if movie_id is not None:
# check if movie is in db
try:
movie = Movie_Collected.objects.get(pk=movie_id)
watchlist = WatchList.objects.filter(user=request.user, movie=movie).exists()
if watchlist:
message = {"error": "Movie already in watchlist"}
return Response(data=message, status=status.HTTP_400_BAD_REQUEST)
else:
watchlist = WatchList.objects.create(user=request.user, movie=movie)
serializer = WatchListSerializer(watchlist)
return Response(data=serializer.data, status=status.HTTP_201_CREATED)
except Movie_Collected.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
else:
message = {'error': 'Movie id is required'}
return Response(data=message, status=status.HTTP_400_BAD_REQUEST)
elif request.method == 'DELETE':
movie_id = request.data.get('movie_id')
if movie_id is not None:
try:
movie = Movie_Collected.objects.get(pk=movie_id)
WatchList.objects.filter(user=request.user, movie=movie).delete()
return Response(status=status.HTTP_204_NO_CONTENT)
except Movie_Collected.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
else:
message = {'error': 'Movie id is required'}
return Response(data=message, status=status.HTTP_400_BAD_REQUEST) | c92d39da05546fea9330ffe44cea5dd0c30f6427 | 12,647 |
async def user_has_pl(api, room_id, mxid, pl=100):
"""
Determine if a user is admin in a given room.
"""
pls = await api.get_power_levels(room_id)
users = pls["users"]
user_pl = users.get(mxid, 0)
return user_pl == pl | 5678af17469202e0b0a0232e066e7ed5c8212ee6 | 12,648 |
import cgi
from typing import Optional
def get_cgi_parameter_bool_or_default(form: cgi.FieldStorage,
key: str,
default: bool = None) -> Optional[bool]:
"""
Extracts a boolean parameter from a CGI form (``"1"`` = ``True``,
other string = ``False``, absent/zero-length string = default value).
"""
s = get_cgi_parameter_str(form, key)
if s is None or len(s) == 0:
return default
return is_1(s) | 905dfa96628414e3b076fd3345113588f3f6ef08 | 12,649 |
def loss_function_1(y_true, y_pred):
""" Probabilistic output loss """
a = tf.clip_by_value(y_pred, 1e-20, 1)
b = tf.clip_by_value(tf.subtract(1.0, y_pred), 1e-20, 1)
cross_entropy = - tf.multiply(y_true, tf.log(a)) - tf.multiply(tf.subtract(1.0, y_true), tf.log(b))
cross_entropy = tf.reduce_mean(cross_entropy, 0)
loss = tf.reduce_mean(cross_entropy)
return loss | 8426ef13bd56fa3ff11226556d37bf738333a165 | 12,650 |
def sanitize_for_json(tag):
"""eugh the tags text is in comment strings"""
return tag.text.replace('<!--', '').replace('-->', '') | 211c07864af825ad29dfc806844927db977e6ce0 | 12,651 |
def load_data_and_labels(dataset_name):
"""
Loads MR polarity data from files, splits the data into words and generates labels.
Returns split sentences and labels.
"""
for i in [1]:
# Load data from files
positive_examples = list(open('data/'+str(dataset_name)+'/'+str(dataset_name)+'.pos',encoding="utf-8").readlines())
# positive_examples = positive_examples[0:1000]
positive_examples = [s.strip() for s in positive_examples]
negative_examples = list(open('data/'+str(dataset_name)+'/'+str(dataset_name)+'.neg',encoding="utf-8").readlines())
# negative_examples = negative_examples[0:1000]
negative_examples = [s.strip() for s in negative_examples]
# Split by words
x_text = positive_examples + negative_examples
x_text = [clean_str(sent) for sent in x_text]
x_text = [s.split(" ") for s in x_text]
# Generate labels
positive_labels = [[0, 1] for _ in positive_examples]
negative_labels = [[1, 0] for _ in negative_examples]
y = np.concatenate([positive_labels, negative_labels], 0)
return [x_text, y] | d753494f3a614850c07f40230c3373eab13b0c6b | 12,652 |
def tileswrap(ihtORsize, numtilings, floats, wrapwidths, ints=[], readonly=False):
"""Returns num-tilings tile indices corresponding to the floats and ints, wrapping some floats"""
qfloats = [floor(f * numtilings) for f in floats]
Tiles = []
for tiling in range(numtilings):
tilingX2 = tiling * 2
coords = [tiling]
b = tiling
for q, width in zip_longest(qfloats, wrapwidths):
c = (q + b % numtilings) // numtilings
coords.append(c % width if width else c)
b += tilingX2
coords.extend(ints)
Tiles.append(hashcoords(coords, ihtORsize, readonly))
return Tiles | e9a9dc439307fc114c9abc939f642ea411acd26e | 12,653 |
def coerce(data, egdata):
"""Coerce a python object to another type using the AE coercers"""
pdata = pack(data)
pegdata = pack(egdata)
pdata = pdata.AECoerceDesc(pegdata.type)
return unpack(pdata) | dc7499530b77a25c8b51537e2e21115d3ce3ccee | 12,654 |
import os
def distorted_inputs(data_dir, batch_size, num_train_files, train_num_examples, boardsize, num_channels):
"""Construct distorted input for training using the Reader ops.
Args:
data_dir: Path to the data directory.
batch_size: Number of images per batch.
Returns:
images: Images. 4D tensor of [batch_size, IMAGE_SIZE, IMAGE_SIZE, 3] size.
labels: Labels. 1D tensor of [batch_size] size.
"""
filenames = []
for fn in os.listdir(data_dir):
if 'test' not in fn and 'prop' not in fn:
filenames.append(os.path.join(data_dir, fn))
print('filenames:{} in cnn_input.distorded_inputs()'.format(filenames))
#filenames = [os.path.join(data_dir, +'_%d.bin' % i)
# for i in xrange(1, num_train_files + 1)]
for f in filenames:
if not tf.gfile.Exists(f):
raise ValueError('Failed to find file: ' + f)
# Create a queue that produces the filenames to read.
filename_queue = tf.train.string_input_producer(filenames)
# Read examples from files in the filename queue.
read_input = read_data(filename_queue, boardsize, num_channels)
reshaped_image = read_input.uint8image
height = boardsize
width = boardsize
# Image processing for training the network. Note the many random
# distortions applied to the image.
distorted_image = tf.cast(tf.reshape(reshaped_image, [height, width, num_channels]), tf.float32)
# Ensure that the random shuffling has good mixing properties.
min_fraction_of_examples_in_queue = 0.4
min_queue_examples = int(min(train_num_examples *
min_fraction_of_examples_in_queue, 20000))
#min_queue_examples=64
print('Filling queue with %d images before starting to train. '
'This will take a few minutes.' % min_queue_examples)
# Generate a batch of images and labels by building up a queue of examples.
return _generate_image_and_label_batch(distorted_image, read_input.label,
min_queue_examples, batch_size,
shuffle=True) | 5a46724c30c30ce5dd846f8fbf522605c27396cc | 12,655 |
from typing import Union
from typing import List
def _write_mkaero1(model: Union[BDF, OP2Geom], name: str,
mkaero1s: List[MKAERO1], ncards: int,
op2_file, op2_ascii, endian: bytes, nastran_format: str='nx') -> int:
"""writes the MKAERO1
data = (1.3, -1, -1, -1, -1, -1, -1, -1,
0.03, 0.04, 0.05, -1, -1, -1, -1, -1)
"""
key = (3802, 38, 271)
makero1s_temp = []
makero1s_final = []
for mkaero in mkaero1s:
nmachs = len(mkaero.machs)
nkfreqs = len(mkaero.reduced_freqs)
assert nmachs > 0, mkaero
assert nkfreqs > 0, mkaero
if nmachs <= 8 and nkfreqs <= 8:
# no splitting required
makero1s_final.append((mkaero.machs, mkaero.reduced_freqs))
elif nmachs <= 8 or nkfreqs <= 8:
# one of machs or kfreqs < 8
makero1s_temp.append((mkaero.machs, mkaero.reduced_freqs))
else:
# both machs and kfreqs > 8
nloops_mach = int(np.ceil(nmachs/8))
for i in range(nloops_mach):
machs_temp = _makero_temp(mkaero.machs, i, nloops_mach)
assert len(machs_temp) > 0, (i, nloops_mach, machs_temp)
makero1s_temp.append((machs_temp, mkaero.reduced_freqs))
for (machs, reduced_freqs) in makero1s_temp:
nmachs = len(machs)
nkfreqs = len(reduced_freqs)
assert nmachs > 0, nmachs
assert nkfreqs > 0, nkfreqs
if nmachs <= 8 and nkfreqs <= 8: # pragma: no cover
raise RuntimeError(f'this should never happen...nmachs={nmachs} knfreqs={nkfreqs}')
if nmachs <= 8:
# nkfreqs > 8
nloops = int(np.ceil(nkfreqs/8))
for i in range(nloops):
reduced_freqs_temp = _makero_temp(reduced_freqs, i, nloops)
makero1s_final.append((machs, reduced_freqs_temp))
elif nkfreqs <= 8:
# nmachs > 8
nloops = int(np.ceil(nmachs/8))
for i in range(nloops):
machs_temp = _makero_temp(machs, i, nloops)
assert len(machs_temp) > 0, (i, nloops_mach, machs_temp)
makero1s_final.append((machs_temp, reduced_freqs))
else: # pragma: no cover
raise RuntimeError(f'this should never happen...nmachs={nmachs} knfreqs={nkfreqs}')
#raise RuntimeError((nmachs, nkfreqs))
ncards = len(makero1s_final)
nfields = 16
nbytes = write_header(name, nfields, ncards, key, op2_file, op2_ascii)
for machs, reduced_freqs in makero1s_final:
data = []
nmachs = len(machs)
nkfreqs = len(reduced_freqs)
assert nmachs > 0, machs
assert nkfreqs > 0, reduced_freqs
nint_mach = 8 - nmachs
nint_kfreq = 8 - nkfreqs
fmt1 = b'%if' % nmachs + b'i' * nint_mach
fmt2 = b'%if' % nkfreqs + b'i' * nint_kfreq
spack = Struct(endian + fmt1 + fmt2)
data.extend(machs.tolist())
assert nint_mach < 8, nint_mach
if nint_mach:
data.extend([-1]*nint_mach)
data.extend(reduced_freqs.tolist())
if nint_kfreq:
data.extend([-1]*nint_kfreq)
op2_ascii.write(f' mkaero1 data={data}\n')
op2_file.write(spack.pack(*data))
return nbytes | ad45ec25989714685a6a2b2e61d6833a9ab56a6d | 12,656 |
def _mesh_obj_large():
"""build a large, random mesh model/dataset"""
n_tri, n_pts = 400, 1000
node = np.random.randn(n_pts, 2)
element = np.array([np.random.permutation(n_pts)[:3] for _ in range(n_tri)])
perm = np.random.randn(n_tri)
np.random.seed(0)
el_pos = np.random.permutation(n_pts)[:16]
return PyEITMesh(node=node, element=element, perm=perm, el_pos=el_pos, ref_node=0) | c2db6a3484dc4923d92519488d0b10d7a7cd75bb | 12,657 |
def cursor():
"""Return a database cursor."""
return util.get_dbconn("mesosite").cursor() | 516cf2a1716204487dd4cff4f063397365b21fa1 | 12,658 |
def custom_field_check(issue_in, attrib, name=None):
""" This method allows the user to get in the comments customfiled that are not common
to all the project, in case the customfiled does not existe the method returns an
empty string.
"""
if hasattr(issue_in.fields, attrib):
value = str(eval('issue_in.fields.%s'%str(attrib)))
if name != None:
return str("%s : %s"%(name,value))
else:
return str(value)
else:
return str("") | d9c051fa922f34242d3b5e94e8534b4dc8038f19 | 12,659 |
def header(text, color='black', gen_text=None):
"""Create an HTML header"""
if gen_text:
raw_html = f'<h1 style="margin-top:16px;color: {color};font-size:54px"><center>' + str(
text) + '<span style="color: red">' + str(gen_text) + '</center></h1>'
else:
raw_html = f'<h1 style="margin-top:12px;color: {color};font-size:54px"><center>' + str(
text) + '</center></h1>'
return raw_html | 646b0a16b35cd4350feadd75674eea6ab6da6404 | 12,660 |
def block_pose(detection, block_size=0.05):
# type: (AprilTagDetection, float) -> PoseStamped
"""Given a tag detection (id == 0), return the block's pose. The block pose
has the same orientation as the tag detection, but it's position is
translated to be at the cube's center.
Args:
detection: The AprilTagDetection.
block_size: The block's side length in meters.
"""
transform = tf.transformations.concatenate_matrices(
tf.transformations.translation_matrix(
[detection.pose.pose.position.x,
detection.pose.pose.position.y,
detection.pose.pose.position.z]
),
tf.transformations.quaternion_matrix(
[detection.pose.pose.orientation.x,
detection.pose.pose.orientation.y,
detection.pose.pose.orientation.z,
detection.pose.pose.orientation.w]
),
tf.transformations.translation_matrix(
[0, 0, -block_size / 2]
)
)
t = tf.transformations.translation_from_matrix(transform)
q = tf.transformations.quaternion_from_matrix(transform)
ps = PoseStamped()
ps.header.frame_id = detection.pose.header.frame_id
ps.header.stamp = detection.pose.header.stamp
ps.pose.position = Point(*t)
ps.pose.orientation = Quaternion(*q)
return ps | da6ee3bb1bf8a071ea5859d17dcad07ecd8781a3 | 12,661 |
async def batch_omim_similarity(
data: models.POST_OMIM_Batch,
method: str = 'graphic',
combine: str = 'funSimAvg',
kind: str = 'omim'
) -> dict:
"""
Similarity score between one HPOSet and several OMIM Diseases
"""
other_sets = []
for other in data.omim_diseases:
try:
disease = Omim.get(other)
hpos = ','.join([str(x) for x in disease.hpo])
except KeyError:
hpos = ''
other_sets.append(
models.POST_HPOSet(
set2=hpos,
name=other
)
)
res = await terms.batch_similarity(
data=models.POST_Batch(
set1=data.set1,
other_sets=other_sets
),
method=method,
combine=combine,
kind=kind
)
return res | 2da8dc25d867f132ec0f571b4d9dff3d7de38c21 | 12,662 |
def vector(*,
unit: _Union[_cpp.Unit, str, None] = default_unit,
value: _Union[_np.ndarray, list]):
"""Constructs a zero dimensional :class:`Variable` holding a single length-3
vector.
:param value: Initial value, a list or 1-D numpy array.
:param unit: Optional, unit. Default=dimensionless
:returns: A scalar (zero-dimensional) Variable.
:seealso: :py:func:`scipp.vectors`
"""
return _cpp.vectors(dims=[], unit=unit, values=value) | dda09f89ba00ffab789c7ed9f6f6713a45c9bd03 | 12,663 |
import laspy
def read_lidar(filename, **kwargs):
"""Read a LAS file.
Args:
filename (str): Path to a LAS file.
Returns:
LasData: The LasData object return by laspy.read.
"""
try:
except ImportError:
print(
"The laspy package is required for this function. Use pip install laspy to install it."
)
return
return laspy.read(filename, **kwargs) | 5336c34223216d4a1857cc5c858ccca704508e22 | 12,664 |
def get_gene_starting_with(gene_symbol: str, verbose: bool = True):
""" get the genes that start with the symbol given
Args:
- gene_symbol: str
- verbose: bool
Returns:
- list of str
- None
"""
gene_symbol = gene_symbol.strip().upper()
ext = "search/symbol/{}*".format(gene_symbol)
data = get_api_response("{}/{}".format(URL, ext))
res = data["response"]["docs"]
if res == []:
if verbose:
print("No gene found starting with {}".format(gene_symbol))
return
else:
gene_symbols = [res[i]["symbol"] for i in range(len(res))]
if verbose:
print("Found these genes starting with {}:".format(gene_symbol))
for symbol in gene_symbols:
print(symbol)
return gene_symbols | c0f092a93d44dd264f6b251ff3eba565b29abda0 | 12,665 |
import time
def gen_timestamp():
"""
Generates a unique (let's hope!), whole-number, unix-time timestamp.
"""
return int(time() * 1e6) | cb044e7428c062660eb998856245d4cd2c692a7e | 12,666 |
def learningCurve(X, y, Xval, yval, Lambda):
"""returns the train and
cross validation set errors for a learning curve. In particular,
it returns two vectors of the same length - error_train and
error_val. Then, error_train(i) contains the training error for
i examples (and similarly for error_val(i)).
In this function, you will compute the train and test errors for
dataset sizes from 1 up to m. In practice, when working with larger
datasets, you might want to do this in larger intervals.
"""
# Number of training examples
m, _ = X.shape
# You need to return these values correctly
error_train = np.zeros(m)
error_val = np.zeros(m)
for i in range(m):
theta = trainLinearReg(X[:i + 1], y[:i + 1], Lambda)
error_train[i], _ = linearRegCostFunction(X[:i + 1], y[:i + 1], theta, 0)
error_val[i], _ = linearRegCostFunction(Xval, yval, theta, 0)
return error_train, error_val | 8cdfdec694cbfadef92375c7cf8eba4da012be59 | 12,667 |
def decode_xml(text):
"""Parse an XML document into a dictionary. This assume that the
document is only 1 level, i.e.:
<top>
<child1>content</child1>
<child2>content</child2>
</top>
will be parsed as: child1=content, child2=content"""
xmldoc = minidom.parseString(text)
return dict([(x.tagName, x.firstChild.nodeValue)
for x in xmldoc.documentElement.childNodes
if x.childNodes.length == 1]) | 826bdc1ff0c4df503fdbc6f7e76b013d907b208b | 12,668 |
def _qcheminputfile(ccdata, templatefile, inpfile):
"""
Generate input file from geometry (list of lines) depending on job type
:ccdata: ccData object
:templatefile: templatefile - tells us which template file to use
:inpfile: OUTPUT - expects a path/to/inputfile to write inpfile
"""
string = ''
if hasattr(ccdata, 'charge'):
charge = ccdata.charge
else:
charge = 0
if hasattr(ccdata, 'mult'):
mult = ccdata.mult
else:
print('Multiplicity not found, set to 1 by default')
mult = 1
# $molecule
string += '$molecule\n'
string += '{0} {1}\n'.format(charge, mult)
# Geometry (Maybe a cleaner way to do this..)
atomnos = [pt.Element[x] for x in ccdata.atomnos]
atomcoords = ccdata.atomcoords[-1]
if not type(atomcoords) is list:
atomcoords = atomcoords.tolist()
for i in range(len(atomcoords)):
atomcoords[i].insert(0, atomnos[i])
for atom in atomcoords:
string += ' {0} {1:10.8f} {2:10.8f} {3:10.8f}\n'.format(*atom)
string += '$end\n\n'
# $end
# $rem
with open(templates.get(templatefile), 'r') as templatehandle:
templatelines = [x for x in templatehandle.readlines()]
for line in templatelines:
string += line
# $end
return string | 3ca565c4c599bccfd3916a0003126b3085cc7254 | 12,669 |
def arrangements(ns):
"""
prime factors of 19208 lead to the "tribonacci" dict;
only needed up to trib(4)
"""
trib = {0: 1, 1: 1, 2: 2, 3: 4, 4: 7}
count = 1
one_seq = 0
for n in ns:
if n == 1:
one_seq += 1
if n == 3:
count *= trib[one_seq]
one_seq = 0
return count
# # one-liner...
# return reduce(lambda c, n: (c[0]*trib[c[1]], 0) if n == 3 else (c[0], c[1]+1), ns, (1,0))[0] | 01f3defb25624d7a801be87c7336ddf72479e489 | 12,670 |
def vtpnt(x, y, z=0):
"""坐标点转化为浮点数"""
return win32com.client.VARIANT (pythoncom.VT_ARRAY | pythoncom.VT_R8, (x, y, z)) | 1e7c79353d010d4dd8daa4b7fa7c39b841ff8ffe | 12,671 |
from datetime import datetime
def get_time_delta(pre_date: datetime):
"""
获取给定时间与当前时间的差值
Args:
pre_date:
Returns:
"""
date_delta = datetime.datetime.now() - pre_date
return date_delta.days | 4f8894b06dc667b166ab0ee6d86b484e967501ac | 12,672 |
from bs4 import BeautifulSoup
def render_checkbox_list(soup_body: object) -> object:
"""As the chosen markdown processor does not support task lists (lists with checkboxes), this function post-processes
a bs4 object created from outputted HTML, replacing instances of '[ ]' (or '[]') at the beginning of a list item
with an unchecked box, and instances of '[x]' (or '[X]') at the beginning of a list item with a checked box.
Args:
soup_body: bs4 object input
Returns:
modified bs4 object
"""
if not isinstance(soup_body, BeautifulSoup):
raise TypeError('Input must be a bs4.BeautifulSoup object')
for ul in soup_body.find_all('ul'):
for li in ul.find_all('li', recursive=False):
if (li.contents[0].string[:2] == '[]') or (li.contents[0].string[:3] == '[ ]'):
unchecked = soup_body.new_tag("input", disabled="", type="checkbox")
li.contents[0].string.replace_with(li.contents[0].string.replace('[] ', u'\u2002'))
li.contents[0].string.replace_with(li.contents[0].string.replace('[ ] ', u'\u2002'))
li.contents[0].insert_before(unchecked)
li.find_parent('ul')['style'] = 'list-style-type: none; padding-left: 0.5em; margin-left: 0.25em;'
elif (li.contents[0].string[:3] == '[x]') or (li.contents[0].string[:3] == '[X]'):
checked = soup_body.new_tag("input", disabled="", checked="", type="checkbox")
li.contents[0].string.replace_with(li.contents[0].string.replace('[x] ', u'\u2002'))
li.contents[0].string.replace_with(li.contents[0].string.replace('[X] ', u'\u2002'))
li.contents[0].insert_before(checked)
li.find_parent('ul')['style'] = 'list-style-type: none; padding-left: 0.5em; margin-left: 0.25em;'
return soup_body | 640f00d726a1268eb71134e29dbde53ef0ec44f5 | 12,673 |
def slowness_to_velocity(slowness):
"""
Convert a slowness log in µs per unit depth, to velocity in unit depth
per second.
Args:
slowness (ndarray): A value or sequence of values.
Returns:
ndarray: The velocity.
"""
return 1e6 / np.array(slowness) | dbfc3b4206ddf615da634e328328c4b8588e5c7a | 12,674 |
def SingleDetectorLogLikelihoodModelViaArray(lookupNKDict,ctUArrayDict,ctVArrayDict, tref, RA,DEC, thS,phiS,psi, dist,det):
"""
DOCUMENT ME!!!
"""
global distMpcRef
# N.B.: The Ylms are a function of - phiref b/c we are passively rotating
# the source frame, rather than actively rotating the binary.
# Said another way, the m^th harmonic of the waveform should transform as
# e^{- i m phiref}, but the Ylms go as e^{+ i m phiref}, so we must give
# - phiref as an argument so Y_lm h_lm has the proper phiref dependence
U = ctUArrayDict[det]
V = ctVArrayDict[det]
Ylms = ComputeYlmsArray(lookupNKDict[det], thS,-phiS)
if (det == "Fake"):
F=np.exp(-2.*1j*psi) # psi is applied through *F* in our model
else:
F = ComplexAntennaFactor(det, RA,DEC,psi,tref)
distMpc = dist/(lal.PC_SI*1e6)
# Term 2 part 1 : conj(Ylms*F)*crossTermsU*F*Ylms
# Term 2 part 2: Ylms*F*crossTermsV*F*Ylms
term2 = 0.j
term2 += F*np.conj(F)*(np.dot(np.conj(Ylms), np.dot(U,Ylms)))
term2 += F*F*np.dot(Ylms,np.dot(V,Ylms))
term2 = np.sum(term2)
term2 = -np.real(term2) / 4. /(distMpc/distMpcRef)**2
return term2 | 35c27e53833cb54f856adde6815bf51c3feca019 | 12,675 |
import numpy as np
def manualcropping(I, pointsfile):
"""This function crops a copy of image I according to points stored
in a text file (pointsfile) and corresponding to aponeuroses (see
Args section).
Args:
I (array): 3-canal image
pointsfile (text file): contains points' coordinates. Pointsfile must be
organized such that:
- column 0 is the ID of each point
- column 1 is the X coordinate of each point, that is the corresponding
column in I
- column 2 is the Y coordinate, that is the row in I
- row 0 is for txt columns' names
- rows 1 and 2 are for two points of the scale
- rows 3 to 13 are aponeuroses' points in panoramic images // raws 3
to 10 in simple images
- following rows are for muscle fascicles (and are optional for this
function)
Other requirements: pointsfile's name must 1) include extension
2) indicates whether I is panoramic or simple by having 'p' or
's' just before the point of the extension.
Returns:
I2 (array) : array of same type than I. It is the cropped image of I according
to the aponeuroses' points manually picked and stored in pointsfile.
point_of_intersect (tuple) : point at right
of the image; should correspond to the point of intersection of deep
and upper aponeuroses.
min_raw, max_raw, min_col, max_col: indices of the location of the cropped image
in the input raw image
"""
data = open(pointsfile, 'r')
#finds whether the image is panoramic or simple
search_point = -1
while (pointsfile[search_point] != '.') and (search_point > (-len(pointsfile))):
search_point = search_point-1
if (search_point == -len(pointsfile)):
raise TypeError("Input pointsfile's name is not correct. Check extension.")
else:
imagetype = pointsfile[search_point-1]
#extract points from the input file
picked_points = []
for line in data:
line = line.strip('\n')
x = line.split('\t')
picked_points.append((x[1], x[2]))
#keep aponeuroses points according to image type
if imagetype == 'p': #keep points 3 to 13 included
apos = np.asarray(picked_points[3:14], dtype=np.float64, order='C')
elif imagetype == 's': #keep points 3 to 10 included
apos = np.asarray(picked_points[3:11], dtype=np.float64, order='C')
else:
raise ValueError("pointsfile's name does not fulfill conditions. See docstrings")
#find max and min indexes for columns and raws to crop image I
#with a margin of 10 pixels (5 pixels for min_raw).
#Coordinates are inverted in apos
min_raw = max(0, np.min(apos[:, 1])-10)
max_raw = min(I.shape[0], np.max(apos[:, 1])+20)
min_col = max(0, np.min(apos[:, 0])-10)
max_col = min(I.shape[1], np.max(apos[:, 0])+10)
i_cropped = np.copy(I[int(min_raw):int(max_raw), int(min_col):int(max_col), :])
index = np.argmax(apos[:, 0])
point_of_intersect = (apos[index][1] - min_raw, apos[index][0] - min_col)
#close file
data.close()
return i_cropped, point_of_intersect, int(min_raw), int(max_raw), int(min_col), int(max_col) | eb3f49b5b46d1966946fc3d00bcae113f51c60d1 | 12,676 |
from datetime import datetime
def prepare_time_micros(data, schema):
"""Convert datetime.time to int timestamp with microseconds"""
if isinstance(data, datetime.time):
return int(data.hour * MCS_PER_HOUR + data.minute * MCS_PER_MINUTE
+ data.second * MCS_PER_SECOND + data.microsecond)
else:
return data | bfdfe40065db66417bf2b641a24b195f4114687e | 12,677 |
def get_configs_path_mapping():
"""
Gets a dictionary mapping directories to back up to their destination path.
"""
return {
"Library/Application Support/Sublime Text 2/Packages/User/": "sublime_2",
"Library/Application Support/Sublime Text 3/Packages/User/": "sublime_3",
"Library/Preferences/IntelliJIdea2018.2/": "intellijidea_2018.2",
"Library/Preferences/PyCharm2018.2/": "pycharm_2018.2",
"Library/Preferences/CLion2018.2/": "clion_2018.2",
"Library/Preferences/PhpStorm2018.2": "phpstorm_2018.2",
} | d7617139a36ca2e1d4df57379d6af73e3b075c84 | 12,678 |
import os
def plot_sample_variation_polar(annots_df_group, **kwargs):
"""
Function: plot polar coordinate values of R3, R4, T3, T4, T3' positions of wild-type flies of a specific age. bundles from one sample are plotted together on the same subplot.
Inputs:
- annots_df_group: DataFrame group. Processed annotation information of a specific age, grouped by sample number.
- Additional inputs:
- is_save: Boolean. Save figures or not. Default = False.
- fig_format: extension figure format. Default = "svg".
- fig_res: figure resolution. Default = 300.
Output:
- Figure.
- sum_coords: summary of polar coordinates.
"""
### parameters
if('is_save' in kwargs.keys()):
is_save = kwargs['is_save']
else:
is_save = False
if('fig_format' in kwargs.keys()):
fig_format = kwargs['fig_format']
else:
fig_format = 'svg'
if('fig_res' in kwargs.keys()):
fig_res = kwargs['fig_res']
else:
fig_res = 300
### Params
paths = settings.paths
phi_unit = get_angle_unit_theory('phi_unit')
color_code = settings.matching_info.color_code
plot_color = {
'R3':color_code[3],
'R4':color_code[4],
'T4':color_code[4],
'T3':color_code[3],
'T7':color_code[7],
}
num_subplots = len(annots_df_group)
### Figure set-up
fig, axes = plt.subplots(num_subplots, 1, figsize = (30, 15), subplot_kw={'projection': 'polar'})
fig.tight_layout()
sum_coords = {}
coords = {}
for i in plot_color.keys():
sum_coords[i] = np.zeros((2, num_subplots))
for i_fig in range(num_subplots):
i_sample = i_fig
### calculating
sample_id = list(annots_df_group.groups.keys())[i_sample]
annots_df_current = annots_df_group.get_group(sample_id).reset_index(drop = True)
annots_df_current.set_index('bundle_no', drop = True, inplace = True)
### initialization
coords[i_fig] = {}
for i in plot_color.keys():
coords[i_fig][i] = np.zeros((2, len(annots_df_current)))
### loop through bundle
for ind, bundle_no in enumerate(annots_df_current.index):
pos_t3 = annots_df_current.loc[bundle_no, 'T3c']
pos_t4 = 1
pos_t7 = annots_df_current.loc[bundle_no, 'T7c']
dTiCs = {3:pos_t3, 7:pos_t7, 4: pos_t4}
target_grid_polar = get_target_grid_polar_summary(return_type = 'theory', dTiCs = dTiCs)
coords[i_fig]['R3'][0, ind] = target_grid_polar[2,0]
coords[i_fig]['R3'][1, ind] = annots_df_current.loc[bundle_no, 'R3']
coords[i_fig]['R4'][0, ind] = target_grid_polar[5,0]
coords[i_fig]['R4'][1, ind] = annots_df_current.loc[bundle_no, 'R4']
coords[i_fig]['T3'][0, ind] = target_grid_polar[2,0]
coords[i_fig]['T3'][1, ind] = annots_df_current.loc[bundle_no, 'T3c']
coords[i_fig]['T7'][0, ind] = target_grid_polar[5,0]
coords[i_fig]['T7'][1, ind] = annots_df_current.loc[bundle_no, 'T7c']
coords[i_fig]['T4'][0, ind] = 0
coords[i_fig]['T4'][1, ind] = 1
### get centroids
for t in coords[i_fig].keys():
sum_coords[t][:, i_sample] = np.mean(coords[i_fig][t], axis = 1)
### Plotting
ax = axes.ravel()[i_fig]
### references
ax.plot([0,0], [0,2.5], '--', color = "0.8", linewidth = 0.5)
ax.plot([0,target_grid_polar[2,0]], [0,2.5], '--', color = "0.8", linewidth = 0.5)
ax.plot([0,target_grid_polar[5,0]], [0,2.5], '--', color = "0.8", linewidth = 0.5)
### individual dots
for ind in range(len(annots_df_current)):
for t in ['R3', 'R4']:
ax.plot(coords[i_fig][t][0, ind], coords[i_fig][t][1, ind],
'o', color = plot_color[t], markersize = 10, alpha = 0.5)
for t in ['T3', 'T4', 'T7']:
ax.plot(coords[i_fig][t][0, ind], coords[i_fig][t][1, ind],
'o', mec = plot_color[t], markersize = 25, mew = 1.0, mfc = 'none', alpha = 0.8)
ax.plot(0, 0, 'o', color = 'k', markersize = 5)
ax.text(0.3, -1, "C")
### axis
ax.set_thetamin(-30)
ax.set_thetamax(30)
ax.set_rlim(0, 2.5)
ax.set_yticks([0, 0.5, 1.0, 1.5, 2.0])
ax.set_xticks([-phi_unit, 0, phi_unit])
ax.set_xticklabels([1, 0, -1])
ax.grid(axis = 'y', linestyle = '--', which = 'major', linewidth = 0.5)
ax.grid(axis = 'x', linestyle = '--', which = 'major', linewidth = 0.5)
ax.tick_params()
if(i_fig == num_subplots-1): ### last sub-figure
ax.set_xlabel('Relative Length (a.u.)')
if(i_fig == round(num_subplots/2)-1): ### middle sub-figure.
ax.set_ylabel("\nRelative Angle (a.u.)")
ax.yaxis.set_label_position("right")
### saving
fig_format = 'svg'
fig_name = f'S3C_Fig.{fig_format}'
fig_save_path = os.path.join(paths.output_prefix, fig_name)
if(is_save):
plt.savefig(fig_save_path, dpi=fig_res, bbox_inches='tight', format = fig_format)
plt.show()
return coords, sum_coords | 9fae03a8d588143745b6a971cd37ee5c1e071338 | 12,679 |
def num_from_bins(bins, cls, reg):
"""
:param bins: list
The bins
:param cls: int
Classification result
:param reg:
Regression result
:return: computed value
"""
bin_width = bins[0][1] - bins[0][0]
bin_center = float(bins[cls][0] + bins[cls][1]) / 2
return bin_center + reg * bin_width | 468e56075cf214f88d87298b259f7253d013a3f3 | 12,680 |
def rotate90(matrix: list) -> tuple:
"""return the matrix rotated by 90"""
return tuple(''.join(column)[::-1] for column in zip(*matrix)) | 770a8a69513c4f88c185778ad9203976d5ee6147 | 12,681 |
def get_aspect(jdate, body1, body2):
"""
Return the aspect and orb between two bodies for a certain date
Return None if there's no aspect
"""
if body1 > body2:
body1, body2 = body2, body1
dist = distance(long(jdate, body1),
long(jdate, body2))
for i_asp, aspect in enumerate(aspects['value']):
orb = get_orb(body1, body2, i_asp)
if i_asp == 0 and dist <= orb:
return body1, body2, i_asp, dist
elif aspect - orb <= dist <= aspect + orb:
return body1, body2, i_asp, aspect - dist
return None | 11a9b05fbc924290e390329395361da0c856541e | 12,682 |
def create_rollout_policy(domain: Simulator, rollout_descr: str) -> Policy:
"""returns, if available, a domain specific rollout policy
Currently only supported by grid-verse environment:
- "default" -- default "informed" rollout policy
- "gridverse-extra" -- straight if possible, otherwise turn
:param domain: environment
:param rollout_descr: "default" or "gridverse-extra"
"""
if isinstance(domain, gridverse_domain.GridverseDomain):
if rollout_descr == "default":
pol = partial(
gridverse_domain.default_rollout_policy,
encoding=domain._state_encoding, # pylint: disable=protected-access
)
elif rollout_descr == "gridverse-extra":
pol = partial(
gridverse_domain.straight_or_turn_policy,
encoding=domain._state_encoding, # pylint: disable=protected-access
)
else:
if rollout_descr:
raise ValueError(
f"{rollout_descr} not accepted as rollout policy for domain {domain}"
)
pol = partial(random_policy, action_space=domain.action_space)
def rollout(augmented_state: BADDr.AugmentedState) -> int:
"""
So normally PO-UCT expects states to be numpy arrays and everything is
dandy, but we are planning in augmented space here in secret. So the
typical rollout policy of the environment will not work: it does not
expect an `AugmentedState`. So here we gently provide it the underlying
state and all is well
:param augmented_state:
"""
return pol(augmented_state.domain_state)
return RolloutPolicyForPlanning(rollout) | 563363589b4ecc6c75306773a6de6320dd697c29 | 12,683 |
def get_event_details(event):
"""Extract event image and timestamp - image with no tag will be tagged as latest.
:param dict event: start container event dictionary.
:return tuple: (container image, last use timestamp).
"""
image = str(event['from'] if ":" in event['from'] else event['from'] + ":latest")
timestamp = event['time']
return image, timestamp | c9b4ded7f343f0d9486c298b9a6f2d96dde58b8c | 12,684 |
def add_extra_vars_rm_some_data(df=None, target='CHBr3',
restrict_data_max=False, restrict_min_salinity=False,
# use_median_value_for_chlor_when_NaN=False,
# median_4MLD_when_NaN_or_less_than_0=False,
# median_4depth_when_greater_than_0=False,
rm_LOD_filled_data=False,
# add_modulus_of_lat=False,
# rm_Skagerrak_data=False,
rm_outliers=False, verbose=True, debug=False):
"""
Add, process, or remove (requested) derivative variables for use with ML code
Parameters
-------
Returns
-------
(pd.DataFrame)
"""
# --- Apply choices & Make user aware of choices applied to data
Shape0 = str(df.shape)
N0 = df.shape[0]
# remove the outlier values
if rm_outliers:
Outlier = utils.get_outlier_value(
df, var2use=target, check_full_df_used=False)
bool = df[target] < Outlier
df_tmp = df.loc[bool]
prt_str = 'Removing outlier {} values. (df {}=>{},{})'
N = int(df_tmp.shape[0])
if verbose:
print(prt_str.format(target, Shape0, str(df_tmp.shape), N0-N))
df = df_tmp
return df | b86c49f6af0ddf144a5388b842240ddb44cf7236 | 12,685 |
def cvCreateMemStorage(*args):
"""cvCreateMemStorage(int block_size=0) -> CvMemStorage"""
return _cv.cvCreateMemStorage(*args) | b6ced2d030345b5500daa051601a20bd19e01825 | 12,686 |
import json
def copyJSONable(obj):
"""
Creates a copy of obj and ensures it is JSONable.
:return: copy of obj.
:raises:
TypeError: if the obj is not JSONable.
"""
return json.loads(json.dumps(obj)) | 1cc3c63893c7716a4c3a8333e725bb518b925923 | 12,687 |
from typing import List
def get_eez_and_land_union_shapes(iso2_codes: List[str]) -> pd.Series:
"""
Return Marineregions.org EEZ and land union geographical shapes for a list of countries.
Parameters
----------
iso2_codes: List[str]
List of ISO2 codes.
Returns
-------
shapes: pd.Series:
Shapes of the union of EEZ and land for each countries.
Notes
-----
Union shapes are divided based on their territorial ISO codes. For example, the shapes
for French Guyana and France are associated to different entries.
"""
shape_fn = f"{data_path}geographics/source/EEZ_land_union/EEZ_Land_v3_202030.shp"
shapes = gpd.read_file(shape_fn)
# Convert country ISO2 codes to ISO3
iso3_codes = convert_country_codes(iso2_codes, 'alpha_2', 'alpha_3', throw_error=True)
# Get 'union' polygons associated with each code
shapes = shapes.set_index("ISO_TER1")["geometry"]
missing_codes = set(iso3_codes) - set(shapes.index)
assert not missing_codes, f"Error: Shapes not available for codes {sorted(list(missing_codes))}"
shapes = shapes.loc[iso3_codes]
shapes.index = convert_country_codes(list(shapes.index), 'alpha_3', 'alpha_2', throw_error=True)
return shapes | 1cebbbbc4d8d962776bbd17e8d2053e1c3dcf5ef | 12,688 |
def putrowstride(a,s):
"""
Put the stride of a matrix view object
"""
t=getType(a)
f={'mview_f':vsip_mputrowstride_f,
'mview_d':vsip_mputrowstride_d,
'mview_i':vsip_mputrowstride_i,
'mview_si':vsip_mputrowstride_si,
'mview_uc':vsip_mputrowstride_uc,
'mview_bl':vsip_mputrowstride_bl,
'cmview_f':vsip_cmputrowstride_f,
'cmview_d':vsip_cmputrowstride_d }
assert t[0] and t[1] in f,'Type <:%s:> not a supported type for for putrowstride'%t[1]
return f[t[1]](a,s) | ad15cc8c0f3e7d88849aed6cfef5408013700a01 | 12,689 |
def list_tracked_stocks():
"""Returns a list of all stock symbols for the stocks being tracker"""
data = read_json("stockJSON/tracked_stocks.json")
return list(data.keys()) | 96c1eeb4fb728d447eb4e4ae055e0ae065df6466 | 12,690 |
def min_max_two(first, second):
"""Pomocna funkce, vrati dvojici:
(mensi ze zadanych prvku, vetsi ze zadanych prvku).
K tomu potrebuje pouze jedno porovnani."""
return (first, second) if first < second else (second, first) | 7ddda1ad69056c22d9ba890e19e62464f56c08e1 | 12,691 |
def expand_pin_groups_and_identify_pin_types(tsm: SMContext, pins_in):
"""
for the given pins expand all the pin groups and identifies the pin types
Args:
tsm (SMContext): semiconductor module context from teststand
pins_in (_type_): list of pins for which information needs to be expanded if it is pin group
Returns:
pins_info, pins_expanded: tuple of pins_info and pins_expanded.
"""
pins_temp, pin_types_temp = get_all_pins(tsm)
pins_info = []
pins_expanded = []
i = 0
for d_pin in pins_in:
if d_pin in pins_temp:
index_d = pins_temp.index(d_pin)
d_pin_type = pin_types_temp[index_d]
count = 1
pin_expanded = ExpandedPinInformation(d_pin, d_pin_type, i)
pins_expanded.append(pin_expanded)
else:
d_pin_type = PinType.PIN_GROUP
temp_exp_pins = tsm.get_pins_in_pin_groups(d_pin) # This works fine
count = len(temp_exp_pins)
for a_pin in temp_exp_pins:
index_a = pins_temp.index(a_pin)
a_pin_type = pin_types_temp[index_a]
pin_expanded = ExpandedPinInformation(
a_pin, a_pin_type, i
) # Found bug here due to class & fixed it.
pins_expanded.append(pin_expanded)
pin_info = PinInformation(d_pin, d_pin_type, count)
pins_info.append(pin_info)
i += 1
pins_expanded = remove_duplicates_from_tsm_pin_information_array(pins_info, pins_expanded)
return pins_info, pins_expanded | 141485a5cef061615afb58e514504dcbc89087ca | 12,692 |
def multi_ways_balance_merge_sort(a):
"""
多路平衡归并排序
- 多用于外部排序
- 使用多维数组模拟外部存储归并段
- 使用loser tree来实现多路归并
- 归并的趟数跟路数k成反比,增加路数k可以调高效率
:param a:
:return:
"""
SENTRY = float('inf') # 哨兵,作为归并段的结尾
leaves = [] # 每个归并段中的一个元素构成loser tree的原始序列
b = [] # 输出归并段,此实现中简化为以为数组。实际情况下也需要对输出分段。
for v in a:
merge_sort(v) # 归并段内排序,采用归并排序
v.append(SENTRY) # 每个归并段追加哨兵
leaves.append(v[0]) # 每个归并段的首元素构成初始化loser tree的原始序列
del v[0] # 删除各归并段的首元素
lt = LoserTree(leaves) # 构建loser tree
# 循环获取winner
while True:
i, v = lt.winner # winner
if v == SENTRY:
# 排序结束
break
b.append(v) # 将winner写入输出归并段
lt.modify_key(i, a[i][0]) # winner所在的归并段的下一个元素更新入loser tree
del a[i][0] # 删除已处理数据
return b | 4abeceb361f662e2ae8bba1a2cd94c9f598bdc9d | 12,693 |
def check_instance_of(value, types, message = None):
"""
Raises a #TypeError if *value* is not an instance of the specified *types*. If no message is
provided, it will be auto-generated for the given *types*.
"""
if not isinstance(value, types):
if message is None:
message = f'expected {_repr_types(types)}, got {type(value).__name__} instead'
raise TypeError(_get_message(message))
return value | 4d62fea56a3c33bf1a6bd5921ff982544e9fbe29 | 12,694 |
def create_input_metadatav1():
"""Factory pattern for the input to the marshmallow.json.MetadataSchemaV1.
"""
def _create_input_metadatav1(data={}):
data_to_use = {
'title': 'A title',
'authors': [
{
'first_name': 'An',
'last_name': 'author'
}
],
'description': 'A description',
'resource_type': {
'general': 'other',
'specific': 'other'
},
'license': 'mit-license',
'permissions': 'all_view',
}
data_to_use.update(data)
return data_to_use
return _create_input_metadatav1 | 3149876217b01864215d4de411acb18eb578f1a9 | 12,695 |
import logging
def create_job(title: str = Body(None, description='The title of the codingjob'),
codebook: dict = Body(None, description='The codebook'),
units: list = Body(None, description='The units'),
rules: dict = Body(None, description='The rules'),
debriefing: dict = Body(None, description='Debriefing information'),
jobsets: list = Body(None, description='A list of codingjob jobsets. An array of objects, with keys: name, codebook, unit_set'),
authorization: dict = Body(None, description='A dictionnary containing authorization settings'),
provenance: dict = Body(None, description='A dictionary containing any information about the units'),
user: User = Depends(auth_user),
db: Session = Depends(get_db)):
"""
Create a new codingjob. Body should be json structured as follows:
{
"title": <string>,
"codebook": {.. blob ..}, # required, but can be omitted if specified in every jobset
"units": [
{"id": <string> # An id string. Needs to be unique within a codingjob (not necessarily across codingjobs)
"unit": {.. blob ..},
"gold": {.. blob ..}, # optional, include correct answer here for gold questions
}
..
],
"rules": {
"ruleset": <string>,
"authorization": "open"|"restricted", # optional, default: open
.. additional ruleset parameters ..
},
"debriefing": {
"message": <string>,
"link": <string> (url)
}
"jobsets": [ # optional
{"name": <string>,
"codebook": <codebook>, ## optional
"unit_set": [<external_id>] ## optional
}
]
"authorization": { # optional, default: {'restricted': False}
restricted: boolean,
users: [emails]
},
"provenance": {.. blob ..}, # optional
}
Where ..blob.. indicates that this is not processed by the backend, so can be annotator specific.
See the annotator documentation for additional informations.
The rules distribute how units should be distributed, how to deal with quality control, etc.
The ruleset name specifies the class of rules to be used (currently "crowd" or "expert").
Depending on the ruleset, additional options can be given.
See the rules documentation for additional information
"""
check_admin(user)
if not title or not codebook or not units or not rules:
raise HTTPException(status_code=400, detail='Codingjob is missing keys')
try:
job = crud_codingjob.create_codingjob(db, title=title, codebook=codebook, jobsets=jobsets, provenance=provenance, rules=rules, debriefing=debriefing, creator=user, units=units, authorization=authorization)
except Exception as e:
logging.error(e)
raise HTTPException(status_code=400, detail='Could not create codingjob')
return dict(id=job.id) | 3b8fbeee052fc17c4490f7b51c57b9a83b878bf0 | 12,696 |
from typing import Dict
async def finalize(
db,
pg: AsyncEngine,
subtraction_id: str,
gc: Dict[str, float],
count: int,
) -> dict:
"""
Finalize a subtraction by setting `ready` to True and updating the `gc` and `files`
fields.
:param db: the application database client
:param pg: the PostgreSQL AsyncEngine object
:param subtraction_id: the id of the subtraction
:param gc: a dict contains gc data
:return: the updated subtraction document
"""
updated_document = await db.subtraction.find_one_and_update(
{"_id": subtraction_id},
{
"$set": {
"gc": gc,
"ready": True,
"count": count,
}
},
)
return updated_document | f9f0a498f5c4345bf9a61cb65ff64d05874caee7 | 12,697 |
def find_path(a, b, is_open):
"""
:param a: Start Point
:param b: Finish Point
:param is_open: Function returning True if the Point argument is an open square
:return: A list of Points containing the moves needed to get from a to b
"""
if a == b:
return []
if not is_open(b):
return None
moves = rectilinear_path(a, b, is_open) or direct_path(a, b, is_open) or find_path_using_a_star(a, b, is_open)
return moves | e42be77beb59ec9ef230c8f30abab33f4bfcd12b | 12,698 |
def view_skill_api():
""" General API for skills and posts """
dbsess = get_session()
action = request.form["action"]
kind = request.form["kind"]
if kind == "post":
if action == "read":
post = models.Post.get_by_id(dbsess, int(request.form["post-id"]))
if not post:
return "", 404
return jsonify({
"title": post.title,
"content": post.body,
})
if action == "create":
skills = request.form.getlist("skill-ids[]")
post = models.Post(title=request.form["title"],
body=request.form["content"])
dbsess.add(post)
dbsess.commit()
for skill_id in skills:
postskill = models.PostSkill(post_id=post.id, skill_id=skill_id)
dbsess.add(postskill)
dbsess.commit()
return jsonify({"new-id": post.id}), 201
if action == "modify":
skills = [int(_id) for _id in request.form.getlist("skill-ids[]")]
post = models.Post.get_by_id(dbsess, int(request.form["post-id"]))
post.title = request.form["title"]
post.body = request.form["content"]
dbsess.query(models.PostSkill).filter_by(post_id=post.id).delete()
for skill_id in skills:
postskill = models.PostSkill(post_id=post.id, skill_id=skill_id)
dbsess.add(postskill)
dbsess.commit()
dbsess.add(post)
dbsess.commit()
return "", 202
if action == "delete":
pass
if kind == "skill":
if action == "read":
send_skills = []
skills = dbsess.query(models.Skill).all()
post = models.Post.get_by_id(dbsess, int(request.form["post-id"]))
for skill in skills:
send_skills.append({
"name": skill.name,
"id": skill.id,
"selected": skill in [skl.skill for skl in post.skills] if post else False,
})
return jsonify({"skills": send_skills}), 200
return "", 400
return "", 400 | 622c4d7eadac7abf23f0706fc49389bd1453846c | 12,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.