content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_ammr_version(folder=None):
"""Return the AMMR version if possible.
The function will walk up a directory tree looking
for a ammr_verion.any file to parse.
"""
folder = folder or os.getcwd()
any_version_file = "AMMR.version.any"
xml_version_file = "AMMR.version.xml"
files = os.li... | 5,339,200 |
def env():
"""check local Environment"""
valid_icon = "\U00002714"
failed_icon = "\U0000274C"
click.echo(f"Current Environment:")
# viur-cli
if shutil.which("viur-cli"):
app_server_version = subprocess.check_output(['viur-cli', '-v']).decode("utf-8")
click.echo(f"{valid_icon} {... | 5,339,201 |
def to_vector(texto,model,idf):
""" Receives a sentence string along with a word embedding model and
returns the vector representation of the sentence"""
tokens = normalizer(texto).split() # splits the text by space and returns a list of words
vec = np.zeros(300) # creates an empty vector of 300 dimens... | 5,339,202 |
def evaluate_interval_detection(labels, predictions, event_val, def_val, seq_length, other_vals=[]):
"""Evaluate interval detection for sequences by calculating
tp, fp, and fn.
Extends the metric outlined by Kyritsis et al. (2019) in
Modeling wrist micromovements to measure in-meal eating behavior from
... | 5,339,203 |
def commit_datasource(ctx,
info,
datasource_id,
message,
schema,
orchestration_backend,
orchestration_args,
processing_backend,
processing_args,... | 5,339,204 |
def _div(v):
"""Pure spatial divergence"""
return _div_id(np.vstack((v, [np.zeros_like(v[0])])), l1_ratio=0.) | 5,339,205 |
async def delete_share_handler(request: aiohttp.web.Request) -> aiohttp.web.Response:
"""Handle unshare-container endpoint query."""
try:
await request.app["db_conn"].delete_share(
request.match_info["owner"],
request.match_info["container"],
request.query["user"].spl... | 5,339,206 |
def iterate_news(
session: requests.Session, page: int, categories_by_id: Dict[int, str],
categories_by_slug: Dict[str, str], api_url: str
) -> Iterable[NewsItem]:
"""Fetch news items using API and iterate over them."""
params = {
'offset': 1,
'page': page
}
r = session.get(api_u... | 5,339,207 |
def _always_run(*args, **kwargs) -> bool:
""" This returns False to indicate that the step is not already completed. """
return False | 5,339,208 |
def generate_urls(search):
"""Generates a URLS in the correct format that brings to Google Image seearch page"""
return [(BASE_URL+quote(word)+GOOGLE_PICTURE_ID) for word in search] | 5,339,209 |
def delete_record_from_index(person):
"""
Deletes person record from index.
Args:
person: Person who should be removed
Raises:
search.Error: An error occurred when the index name is unknown
or the query has a syntax error.
"""
doc_id = person.repo + ':' + pe... | 5,339,210 |
def _delete_sys_path_0():
"""Delete the first entry on `sys.path`, but only if this routine has not deleted it
already."""
global deleted_sys_path_0_value
if deleted_sys_path_0_value is None:
deleted_sys_path_0_value = sys.path[0]
del sys.path[0] | 5,339,211 |
def batch_provider(data, batch_size, processor=None, worker_count=1, queue_size=16, report_progress=True):
""" Return an object that produces a sequence of batches from input data
Input data is split into batches of size :attr:`batch_size` which are processed with function :attr:`processor`
Data is split a... | 5,339,212 |
def simplex(key, log_L_constraint, live_points_U,
loglikelihood_from_constrained,
prior_transform, sampler_state, replace_id):
"""
Samples from the prior restricted to the likelihood constraint.
This undoes the shrinkage at each step to approximate a bound on th... | 5,339,213 |
def has_anonymous_link(node, auth):
"""check if the node is anonymous to the user
:param Node node: Node which the user wants to visit
:param str link: any view-only link in the current url
:return bool anonymous: Whether the node is anonymous to the user or not
"""
if auth.private_link:
... | 5,339,214 |
def lstm(c_prev, x):
"""Long Short-Term Memory units as an activation function.
This function implements LSTM units with forget gates. Let the previous
cell state :math:`c_{\\text{prev}}` and the incoming signal :math:`x`.
First, the incoming signal :math:`x` is split into four arrays
:math:`a, i,... | 5,339,215 |
def hals(video,
video_factorization,
maxiter_hals=30,
nnt=False,
verbose=False,
indent='',
device='cuda',
**kwargs):
"""Perform maxiter HALS updates To Temporal & Spatial Components
Parameter:
video: LowRankVideo class object
video_... | 5,339,216 |
def test_patch_array_operations_order(sut: SystemUnderTest):
"""Perform tests for Assertion.REQ_PATCH_ARRAY_OPERATIONS_ORDER."""
# TODO(bdodd): Need more thought on how to test this | 5,339,217 |
def generate_random_sd(error, seq = None):
""" generates random sd with error% error rate
If seq is specified, random sd is generated from a substring of it."""
if seq == None:
seq1 = randSeq(rand(minLen, maxLen))
else:
length = rand(minLen, maxLen)
start = rand(0, len(se... | 5,339,218 |
def is_successful(gsm_log):
"""
Success is defined as having converged to a transition state.
"""
with open(gsm_log) as f:
for line in reversed(f.readlines()):
if '-XTS-' in line or '-TS-' in line:
return True
return False | 5,339,219 |
def indicator(function_array_to_be_indicated, its_domain, barrier):
"""the indicator influences the function argument, not value. So here it iterates through x-domain and cuts any
values of function with an argument less than H"""
indicated = []
for index in range(len(its_domain)):
if its_domain... | 5,339,220 |
def test_elemwise_collapse():
""" Test when all inputs have one(and the same) broadcastable dimension """
shape = (4,5,60)
a = cuda_ndarray.CudaNdarray(theano._asarray(numpy.random.rand(*shape),dtype='float32'))
a = theano._asarray(numpy.random.rand(*shape),dtype='float32')
a2 = tcn.shared_construc... | 5,339,221 |
def list_calendars(service):
"""
Given a google 'service' object, return a list of
calendars. Each calendar is represented by a dict, so that
it can be stored in the session object and converted to
json for cookies. The returned list is sorted to have
the primary calendar first, and selected (t... | 5,339,222 |
def _causes_name_clash(candidate, path_list, allowed_occurences=1):
"""Determine if candidate leads to a name clash.
Args:
candidate (tuple): Tuple with parts of a path.
path_list (list): List of pathlib.Paths.
allowed_occurences (int): How often a name can occur before we call it a cla... | 5,339,223 |
def run_eqm(results: Results, options: Options, state: PromisedObject) -> dict:
"""Run the eqm jobs."""
# set user-defined valuess
results['job_opts_eqm'] = edit_calculator_options(
options, ['eqm', 'xtpdft', 'esp2multipole'])
cmd_eqm_write = create_promise_command(
"xtp_parallel -e eqm... | 5,339,224 |
def main():
"""Main
"""
logging.basicConfig(level=logging.INFO)
session_pool = ph.HSessionManager.get_or_create_session_pool()
# run producer and consumer forever
session_pool.run_on_task_producer(producer) | 5,339,225 |
def is_within_boundary(boundary_right_most_x, boundary_top_most_y,
boundary_left_most_x, boundary_bottom_most_y,
cursor):
"""
Checks if cursor is within given boundary
:param boundary_right_most_x:
:param boundary_top_most_y:
:param boundary_left_most_x... | 5,339,226 |
def clean_novel(id_or_url: str, content_only: bool):
"""Remove accessory fields from novel
Removes all except vital information related to novel, this includes chapters, metadata, and assets.
If content_only flag is specified, only the chapter content is deleted, keeping the chapter entries as is.
"""... | 5,339,227 |
def mixrng(numbytes, port='COM4'):
"""Returns bitwise xor of an inbuilt and hardware CSRNG"""
internal = os.urandom(numbytes)
external = extrng(numbytes, port)
return xorbytes(internal, external) | 5,339,228 |
def show_quantization(X, X_c):
"""
Visualise a vector quantization.
show_quantization(X, X_c)
Inputs:
- X: numpy.ndarray containing the instances (p x 2)
- X_c: numpy.ndarray containing the centroids (q x 2)
A figure is created and the p instances are shown as dots,
whereas the... | 5,339,229 |
async def hello(ctx: discord.ApplicationContext):
"""Say hello to the bot""" # The command description can be supplied as the docstring
await ctx.respond(f"Hello {ctx.author}!")
# Please note that you MUST respond with ctx.respond(), ctx.defer(), or any other
# interaction response within 3 seconds... | 5,339,230 |
def write(df, filename):
"""Write a dataframe to the data directory."""
df.to_pickle(os.path.join(TEST_DATA_DIR, '{0}.pkl'.format(filename))) | 5,339,231 |
def save_dict_to_json(json_path, save_dict):
"""
将字典保存成JSON文件
"""
json_str = json.dumps(save_dict, indent=2, ensure_ascii=False)
with open(json_path, 'w', encoding='utf-8') as json_file:
json_file.write(json_str) | 5,339,232 |
def save_matchmaking_auth_key(auth_key: str) -> bool:
"""Register a new matchmaking auth key. !This will overwrite the existing matchmaking key for this chain!
Args:
auth_key: auth_key to add for matchmaking
Returns:
Boolean if successful
"""
try:
redis.set_sync(MATCHMAKING_K... | 5,339,233 |
def get_game_page(url):
"""
Get the HTML for a given URL, where the URL is a game's page in the Xbox
Store
"""
try:
response = requests.get(url)
except (requests.exceptions.MissingSchema, ConnectionError):
return None
game_page = BeautifulSoup(response.content, "html.parser... | 5,339,234 |
async def generate_spam_round_tx_xdrs(pool, prioritizers: List[Keypair], prioritized_builders, unprioritized_builders, rnd):
"""Generate transaction XDRs for a single spam round (ledger) according to given builders.
Some of the generated transactions are prioritized using given prioritizer seeds,
and some ... | 5,339,235 |
async def cleanup_device_registry(
hass: HomeAssistant, device_manager: TuyaDeviceManager
) -> None:
"""Remove deleted device registry entry if there are no remaining entities."""
device_registry = dr.async_get(hass)
for dev_id, device_entry in list(device_registry.devices.items()):
for item in ... | 5,339,236 |
def test_unsupported_upstream_entity_type():
"""
Checks to see how invalid types work in the upstream node.
If validation is working correctly, it should raise a ConfigurationError
"""
with pytest.raises(ConfigurationError):
unsupported_upstream_entity_type_mcp() | 5,339,237 |
def test_decode_open_order_account_layout():
"""Test decode event queue."""
with open(OPEN_ORDER_ACCOUNT_BIN_PATH, "r") as input_file:
base64_res = input_file.read()
data = base64.decodebytes(base64_res.encode("ascii"))
open_order_account = OPEN_ORDERS_LAYOUT.parse(data)
assert o... | 5,339,238 |
def json_custom_parser(obj):
"""
A custom json parser to handle json.dumps calls properly for Decimal and Datetime data types.
"""
if isinstance(obj, Decimal):
return float(obj)
elif not isinstance(obj, basestring) and isinstance(obj, collections.Iterable):
return list(obj)
e... | 5,339,239 |
def _renew_re_entrant_lock(conn: Redis, lock_name: str, identifier: str, lock_timeout: int):
"""
为锁续约
:param conn:redis链接
:param lock_name:lock_key
:param identifier:lock_唯一id
:param lock_timeout: 上锁超时时间ms
:return:
"""
while _renew_re_entrant_lock_lua(conn, [lock_name], [lock_timeout... | 5,339,240 |
def process(arguments: list = None) -> str:
"""
Run the process
Parameters
----------
arguments : list
Injectable arguments to execute
Returns
-------
str
The name of the library command to execute
"""
if not arguments:
arguments = []
__prepare()
... | 5,339,241 |
def fs_open(path, flag, mode=default_file_mode):
"""
Open a file, potentially creating it. Return the new fd's id or else -1 if
file can not be opened (or potentially created)
"""
# Check if file should be created if it doesn't exist
O_CREAT = 64
create = flag & 64
# If requested, try to create the fi... | 5,339,242 |
def printMat(inMat, thresh=0.8):
"""
打印矩阵
"""
for i in range(32):
for k in range(32):
if float(inMat[i, k]) > thresh:
print(1,end='')
else:
print(0,end='')
print('') | 5,339,243 |
def new_user():
"""
Create Instance of User class to be used by the module
"""
user_details = ['Daudi', 'Jesee', 'dj@mail.com', 'password']
user = Users(user_details)
return user | 5,339,244 |
def normalise_angle(angle: float) -> float:
"""Normalises the angle in the range (-pi, pi].
args:
angle (rad): The angle to normalise.
return:
angle (rad): The normalised angle.
"""
while angle > math.pi:
angle -= 2 * math.pi
while angle <= -math.pi:
angle += 2 ... | 5,339,245 |
def test_constraints1():
"""
simplest senario
"""
pm = ParameterHelper(
species=["O", "C", "H"],
kernels={
"twobody": [["*", "*"], ["O", "O"]],
"threebody": [["*", "*", "*"], ["O", "O", "O"]],
},
parameters={
"twobody0": [1, 0.5],
... | 5,339,246 |
def get_hdf_len(*path):
"""
Returns the number of rows in an hdf file as an int.
"""
path = construct_path(*path)
with pd.HDFStore(path) as store:
numrows = store.get_storer('data').nrows
return numrows | 5,339,247 |
def test_fastparcel_water_content_scalar():
"""Test FastParcel.water_content for scalar input."""
height = 2000*units.meter
z_init = 3000*units.meter
q_initial = 0.004751707262581661*units.dimensionless
l_initial = 2e-3*units.dimensionless
rate = 0.5/units.km
actual = sydneyfast.water_conte... | 5,339,248 |
def matmul(A, B, transpose_A=False, transpose_B=False, master='/gpu:0'):
"""
distributed matrix multiplication.
A: DistMat,
B: single tensor or a list of tensors.
Note: returns a single tensor or a list of tensors, Not a DistMat.
"""
if isinstance(A, tf.Tensor) or isinstance(A, tf.Variable)... | 5,339,249 |
def celerybeat_started():
"""
Returns true/false depending on whether the celerybeat service is started or not
"""
if is_systemd():
running = 'active' in fabric.api.sudo('systemctl is-active %s' % celerybeat_service_name())
return running
return fabtools.service.is_running(celerybea... | 5,339,250 |
def highest_greedy_score(board, disks):
"""
Compute the highest possible score that can be obtained by dropping each
of the given disks on the given board in a greedy way.
- The disks must be dropped in the order in which they appear in the
given list of disks. Eac... | 5,339,251 |
def normalize_and_discard(df: pd.DataFrame) -> pd.DataFrame:
"""
Normalize numeric values between 0 and 1 and discard records that are out of bounds.
"""
# ## 2. Discard values out of range of x and y
df_cleaned = df[(df.x >= 0) & (df.x <= 120) & (df.y >= 0) & (df.y <= (160 / 3))]
print(f'Shape ... | 5,339,252 |
def gravatar_url(email, size=16):
"""Return the gravatar image for the given email address."""
return 'http://www.gravatar.com/avatar/%s?d=identicon&s=%d' % \
(md5(email.strip().lower().encode('utf-8')).hexdigest(), size) | 5,339,253 |
def x2bin(v):
"""
convert a value into a binary string
v: int, bytes, bytearray
bytes, bytearray must be in *big* endian.
"""
if isinstance(v, int):
bits = bin(v)
size = 8
elif isinstance(v, (bytes,bytearray)):
bits = bin(int.from_bytes(v, "big"))
size = l... | 5,339,254 |
def run_server():
"""
This is the main runtime function of the server.
It creates a server socket and waits for a connection.
According to the received message, it will either send experiment values or receive experiment results.
In the case of experiment results retrieving, this function will downl... | 5,339,255 |
def test_ll3_access_clearing_manager(test_client,test_single_sample_request_nonadmin,test_single_sample_request_ahoag,test_login_ll3):
""" Test that Laura (ll3, a clearing admin) can access the clearing task manager
and see entries made by multiple users """
response = test_client.get(url_for('clearing.clearing_mana... | 5,339,256 |
def upload_to_remote(local_path):
"""upload data onto S3"""
remote_key_name = local_path.replace(root + '/./', '')
s3.meta.client.upload_file(Filename=local_path,
Bucket=BUCKETNAME,
Key=remote_key_name) | 5,339,257 |
def normalize_url(url):
"""Function to normalize the url. It will be used as document id value.
Returns:
the normalized url string.
"""
norm_url = re.sub(r'http://', '', url)
norm_url = re.sub(r'https://', '', norm_url)
norm_url = re.sub(r'/', '__', norm_url)
return norm_url | 5,339,258 |
def test_bubble_sort_empty_list():
"""Test that bbs properly handles an empty list."""
assert bubble_sort([]) == [] | 5,339,259 |
def is_remote_filesystem(fs: fsspec.AbstractFileSystem) -> bool:
"""
Validates if filesystem has remote protocol.
Args:
fs (``fsspec.spec.AbstractFileSystem``): An abstract super-class for pythonic file-systems, e.g. :code:`fsspec.filesystem(\'file\')` or :class:`datasets.filesystems.S3FileSystem`
... | 5,339,260 |
def remove_gate(gate: List[Block], screen: pygame.Surface) -> None:
"""
After the snake has passed the gate, remove it
Args:
gate (List[Block]): The gate
screen (pygame.Surface): The screen to remove the gate from
Returns:
None
"""
update_rects = []
for block in ga... | 5,339,261 |
def get_element_attribute_or_empty(element, attribute_name):
"""
Args:
element (element): The xib's element.
attribute_name (str): The desired attribute's name.
Returns:
The attribute's value, or an empty str if none exists.
"""
return element.attributes[attribute_name].va... | 5,339,262 |
def Matcher(y_true, y_pred_logits, y_pred_bbox):
"""
y_true: GT list of len batch with each element is an array of
shape (n_gt_objects, 5) ; n_gt_objects are number of
objects in that image sample and 5 -> (cx,cy,w,h,class_label)
where cordinates are in [0,1]... | 5,339,263 |
def diff_runs(ctx, args):
"""Diff two runs.
If `RUN1` and `RUN2` are omitted, the latest two filtered runs are
diffed. See FILTERING topics below for details on filtering runs
to diff.
If `RUN1` or `RUN2` is specified, both must be specified.
{{ runs_support.op_and_label_filters }}
{{ run... | 5,339,264 |
def set_test_variables():
"""
Sets up variables for the unit tests below.
:return: dictionary of test input variables for the unit tests.
"""
test_variables = {
"asl_valid_full": os.path.join(
SRC_ROOT, "resources/schemas/tests_jsons/asl_valid/test_asl_schema001.json"
),
... | 5,339,265 |
def _addBindInput(self, name, type = DEFAULT_TYPE_STRING):
"""(Deprecated) Add a BindInput to this shader reference."""
warnings.warn("This function is deprecated; shader references have been replaced with shader nodes in 1.38.", DeprecationWarning, stacklevel = 2)
return self.addInput(name, type) | 5,339,266 |
def process_days_step(message):
"""Update period field of film object with given data."""
chat_id = message.chat.id
film = film_dict[chat_id]
try:
if message.text == 'Сьогодні':
film.period = film.today
elif message.text == 'Завтра':
film.period = film.today + tim... | 5,339,267 |
def test_get_html_page_invalid_content_type(
mock_raise_for_status: mock.Mock,
caplog: pytest.LogCaptureFixture,
content_type: str,
) -> None:
"""`_get_html_page()` should warn if an invalid content-type is given.
Only text/html is allowed.
"""
caplog.set_level(logging.DEBUG)
url = "http... | 5,339,268 |
def sf(x, c, d, scale):
"""
Survival function of the Burr type XII distribution.
"""
_validate_params(c, d, scale)
with mpmath.extradps(5):
x = mpmath.mpf(x)
c = mpmath.mpf(c)
d = mpmath.mpf(d)
scale = mpmath.mpf(scale)
if x < 0:
return mpmath.mp.o... | 5,339,269 |
def substitute_word(text):
"""
word subsitution to make it consistent
"""
words = text.split(" ")
preprocessed = []
for w in words:
substitution = ""
if w == "mister":
substitution = "mr"
elif w == "missus":
substitution = "mrs"
else:
... | 5,339,270 |
def google_wiki(keyword, langid='en', js={}):
"""Google query targets, output if English wikipedia entry is found"""
targets = []
headers = {'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:32.0) Gecko/20100101 Firefox/32.0',}
googlerx = re.compile('(http[s]?[^\&]*)') # /url?q=https://fr.... | 5,339,271 |
def _get_test_words() -> WordDict:
"""
>>> _get_test_words()['?og']
['dog', 'log']
"""
from .compile_words import read_words
dir_path = os.path.dirname(os.path.realpath(__file__))
return read_words(os.path.join(dir_path, 'test_data.txt')) | 5,339,272 |
def escape(line, chars):
"""Escapes characters 'chars' with '\\' in 'line'."""
def esc_one_char(ch):
if ch in chars:
return "\\" + ch
else:
return ch
return u"".join([esc_one_char(ch) for ch in line]) | 5,339,273 |
def polinomsuzIntegralHesapla(veriler):
"""
Gelen verileri kullanarak integral hesaplar.
:param veriler: İntegrali hesaplanacak veriler. Liste tipinde olmalı.
"""
a,b=5,len(veriler)
deltax = 1
integral = 0
n = int((b - a) / deltax)
for i in range(n-1):
integral += deltax * (v... | 5,339,274 |
def _keep_extensions(files, extension):
""" Filters by file extension, this can be more than the extension!
E.g. .png is the extension, gray.png is a possible extension"""
if isinstance(extension, str):
extension = [extension]
def one_equal_extension(some_string, extension_list):
return... | 5,339,275 |
def make_all_rules(
schema: "BaseOpenAPISchema", bundles: Dict[str, CaseInsensitiveDict], connections: EndpointConnections
) -> Dict[str, Rule]:
"""Create rules for all endpoints, based on the provided connections."""
return {
f"rule {endpoint.verbose_name}": make_rule(
endpoint, bundles... | 5,339,276 |
async def test_duplicate_error(hass):
"""Test that errors are shown when duplicate entries are added."""
conf = {CONF_IP_ADDRESS: "192.168.1.100", CONF_PORT: 7777}
MockConfigEntry(domain=DOMAIN, unique_id="192.168.1.100", data=conf).add_to_hass(
hass
)
result = await hass.config_entries.fl... | 5,339,277 |
def audio_to_magnitude_db_and_phase(n_fft, hop_length_fft, audio):
"""This function takes an audio and convert into spectrogram,
it returns the magnitude in dB and the phase"""
stftaudio = librosa.stft(audio, n_fft=n_fft, hop_length=hop_length_fft)
stftaudio_magnitude, stftaudio_phase = librosa.magp... | 5,339,278 |
def check_racs_exists(base_dir: str) -> bool:
"""
Check if RACS directory exists
Args:
base_dir: Path to base directory
Returns:
True if exists, False otherwise.
"""
return os.path.isdir(os.path.join(base_dir, "EPOCH00")) | 5,339,279 |
def has_rc_object(rc_file, name):
"""
Read keys and values corresponding to one settings location
to the qutiprc file.
Parameters
----------
rc_file : str
String specifying file location.
section : str
Tags for the saved data.
"""
config = ConfigParser()
try:
... | 5,339,280 |
def apply_transform_test(batch_size, image_data_dir, tensor_data_dir, limited_num = None, shuffle_seed = 123, dataset = None):
"""
"""
std = [1.0, 1.0, 1.0]
mean = [0.0, 0.0, 0.0]
# if dataset is None:
# std = [1.0, 1.0, 1.0]
# mean = [0.0, 0.0, 0.0]
# elif dataset == "cifar10":
... | 5,339,281 |
def split_datasets(data_dir, word_dict, num_folds, fold_idx):
"""Split known words (including silence) and unknown words into training
and validation datasets respectively.
"""
modes = ['training', 'validation']
knowns = {m: [] for m in modes}
unknowns = {m: [] for m in modes}
word_excluded = set()
re... | 5,339,282 |
def take_t(n):
"""
Transformation for Sequence.take
:param n: number to take
:return: transformation
"""
return Transformation(
"take({0})".format(n), lambda sequence: islice(sequence, 0, n), None
) | 5,339,283 |
def metric_fn(loss):
"""Evaluation metric Fn which runs on CPU."""
perplexity = tf.exp(tf.reduce_mean(loss))
return {
"eval/loss": tf.metrics.mean(loss),
"eval/perplexity": tf.metrics.mean(perplexity),
} | 5,339,284 |
def gensig_choi(distsmat, minlength=1, maxlength=None, rank=0):
""" The two dimensional sigma function for the c99 splitting """
if rank:
distsmat = rankify(distsmat, rank)
def sigma(a, b):
length = (b - a)
beta = distsmat[a:b, a:b].sum()
alpha = (b - a)**2
if minlen... | 5,339,285 |
def check_ie_v3(base, add: Optional[str] = None) -> str:
"""Check country specific VAT-Id"""
s = sum((w * int(c) for w, c in zip(range(8, 1, -1), base)),
9 * (ord(add) - ord('@'))) # 'A' - 'I' -> 1 - 9
i = s % 23
return _IE_CC_MAP[i] | 5,339,286 |
def delete_missing_cgacs(models, new_data):
""" If the new file doesn't contain CGACs we had before, we should delete the non-existent ones.
Args:
models: all existing frec models in the database
new_data: All the entries gathered from the agency file
"""
to_delete = set(mod... | 5,339,287 |
def filter_experiment_model(faultgroup, faultmodel, interestlist=None):
"""
Filter for a specific fault model. If interestlist is given only experiments
in this list will be analysed.
0 set 0
1 set 1
2 Toggle
"""
if not isinstance(faultmodel, int):
if "set0" in faultmodel:
... | 5,339,288 |
def _str2bool(v):
"""Parser type utility function."""
if v.lower() in ('yes', 'true', 't', 'y', 'on', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', 'off', '0'):
return False
else:
raise argparse.ArgumentTypeError('Boolean type expected. '
... | 5,339,289 |
def _default_command(cmds, argv):
"""Evaluate the default command, handling ``**kwargs`` case.
`argparse` and `argh` do not understand ``**kwargs``, i.e. pass through command.
There's a case (`pykern.pkcli.pytest`) that requires pass through so we wrap
the command and clear `argv` in the case of ``defa... | 5,339,290 |
def keypair_to_file(keypair):
"""Looks for the SSH private key for keypair under ~/.ssh/
Prints an error if the file doesn't exist.
Args:
keypair (string) : AWS keypair to locate a private key for
Returns:
(string|None) : SSH private key file path or None is the private key doesn't ex... | 5,339,291 |
def animation(n, movie_file=None, writer=None, **kwargs):
"""Context for animations."""
fig, ax = plt.subplots(**kwargs)
fig.set_tight_layout(True)
ax.grid(linestyle='dotted')
ax.set_aspect(1.0, 'datalim')
ax.set_axisbelow(True)
context = {'fig': fig, 'ax': ax, 'update_function': None}
... | 5,339,292 |
def most_common_words(vocab_dir, visual_fld, num_visualize):
""" create a list of num_visualize most frequent words to visualize on TensorBoard.
saved to visualization/vocab_[num_visualize].tsv
"""
words = open(os.path.join(vocab_dir, 'vocab.tsv'), 'r').readlines()[:num_visualize]
words = [word for ... | 5,339,293 |
def test_pt_br_ulb_tn_en_ulb_wa_tn_wa_luk_language_book_order() -> None:
"""
Produce verse level interleaved document for Brazilian Portuguese
and English scripture and translation notes for the book of Luke.
"""
with TestClient(app=app, base_url=settings.api_test_url()) as client:
response:... | 5,339,294 |
def nameable_op(node_factory_function): # type: (Callable) -> Callable
"""Set the name to the ngraph operator returned by the wrapped function."""
@wraps(node_factory_function)
def wrapper(*args, **kwargs): # type: (*Any, **Any) -> Node
node = node_factory_function(*args, **kwargs)
node = ... | 5,339,295 |
def update_states():
"""
Called once per interact to walk the tree of displayables and find
the old and new live2d states.
"""
def visit(d):
if not isinstance(d, Live2D):
return
if d.name is None:
return
state = states[d.name]
if state.mark... | 5,339,296 |
def load_mlflow(output):
"""Load the mlflow run id.
Args:
output (str): Output directory
"""
with open(os.path.join(output, STAT_FILE_NAME), 'r') as stream:
stats = load(stream, Loader=yaml.FullLoader)
return stats['mlflow_run_id'] | 5,339,297 |
def by_pattern(finding: finding.Entry, ignore: ignore_list.Entry) -> bool:
"""Process a regex ignore list entry."""
# Short circuit if no pattern is set.
if not ignore.pattern:
return False
# If there's a match on the path, check whether the ignore is for the same module.
if re.search(ignor... | 5,339,298 |
def object_radius():
"""
Check for Radius:
"""
error_msg = "INCORRECT Object(s) Selection:\n\nYou Must Select One Arc!"
Selection = Gui.Selection.getSelectionEx()
try:
result = "Radius:"
m_found = False
for m_sel in Selection:
m_name = m_sel.ObjectName
... | 5,339,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.