content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from typing import Tuple
from typing import List
from typing import Optional
def loc_siblings(
parent_key: Tuple[str], keys: List[Tuple[str]], is_array: Optional[bool] = None
) -> List[Tuple[str]]:
"""Locate Field keys which share a parent key."""
if is_array is not None:
if is_array:
... | fb658ed59ac87dc20424ccd791e2d3e7bce05f71 | 686,431 |
import os
def _collectPythonExecutableDetails(settings):
"""Extracts details of all python executables specified in
context_details.
Verifies that those executables exist. Prepares the corresponding
virtualenv names and returns all those details.
Args:
settings (dict) : diction... | caaf0b4e4e65b59d52efa4112459f4167a3c1892 | 686,432 |
import time
def to_timestamp(time_val):
"""Generate a unix timestamp for the given datetime instance"""
return time.mktime(time_val.timetuple()) | 076e0584cdc4a85fe4d98b2511915ac5bdae98ea | 686,433 |
import warnings
def capture_warnings(function, *func_args, **func_kwargs):
"""Capture function result and warnings.
"""
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
result = function(*func_args, **func_kwargs)
all_warnings = w
return result, [... | 26cf4f5d32cf0eff1d5b511ee3aa277c0c2117fe | 686,434 |
def dump_feature(feature):
"""
Gets a single feature as a dictionary, and returns it rendered as a string
"""
s = "|f "
for _key in sorted(feature.keys()):
s += "{}:{} ".format(_key, feature[_key])
return s | b20dff368943aecbe485778b3cded552db56ffb0 | 686,435 |
def remove_padding(im, pad):
"""
Function for removing padding from an image.
:param im: image to remove padding from
:param pad: number of pixels of padding to remove
:return:
"""
return im[pad:-pad, pad:-pad] | 58d822dc9ab587f63d1a98eb19e17268d75b2ab4 | 686,436 |
def about_view(request):
"""Return about page."""
return {} | 70a2324c5e7d578c83f6603f8fe81bbb6c258a97 | 686,437 |
import torch
def split_with_shape(tensor_flatten, mask_flatten, tensor_shape):
"""
Params:
:tensor_flatten: (B, L, C)
:mask_flatten: (B, L)
:tensor_shape: (N, 2)
Return:
:tensor_list: [(B, H1 * W1, C), ..., (B, HN * WN, C)]
:mask_list: [(B, H1 * W1), ..., (B, HN * WN)]
"""
chu... | 9fd537ac1261ce13e7faef2078fa4c2960699169 | 686,438 |
def uniqueArrayName(dataset, name0):
""" Generate a unique name for a DataArray in a dataset """
ii = 0
name = name0
while name in dataset.arrays:
name = name0 + '_%d' % ii
ii = ii + 1
if ii > 1000:
raise Exception('too many arrays in DataSet')
return name | d7da95a9e3a9d959012c101bbc40495a1e085dfd | 686,439 |
def get_mail_orders(): # noqa: E501
"""displays a list of mail service orders
# noqa: E501
:rtype: MailOrders
"""
return 'do some magic!' | e516895a396853c0a6f1a41ad837c4dd23cad009 | 686,440 |
import re
def print_file(file, number):
"""Print content of the file
Input: File handler
Returns: nothing
"""
entry_counter = 0
regex = r"[ ]" + str(number)
for line in file:
if re.search(regex, line):
print(line, end='')
entry_counter += 1
return entry_counter | 9c63ba18bb242109a7cd3e61b780df85c58e628b | 686,441 |
import importlib
def _import_module(mocker):
"""Fixture providing import_module mock."""
return mocker.Mock(spec_set=importlib.import_module) | 67db797fdfe5602134b2ef0feaa6efded8865938 | 686,442 |
def bin2int(bin):
"""convert the binary (as string) to integer"""
#print('bin conversion', bin, int(bin, 2))
return int(bin, 2) | def903c6015c13629b6c1778c69e747a82bb32be | 686,443 |
def _ci_to_hgvs_coord(s, e):
""" Convert continuous interbase (right-open) coordinates (..,-2,-1,0,1,..) to
discontinuous HGVS coordinates (..,-2,-1,1,2,..)
"""
def _ci_to_hgvs(c):
return c + 1 if c >= 0 else c
return (None if s is None else _ci_to_hgvs(s),
None if e is None else... | a25cee5f587b59fd52779f6eeba363f3ddda77b0 | 686,444 |
def num_sevens(n):
"""Returns the number of times 7 appears as a digit of n.
>>> num_sevens(3)
0
>>> num_sevens(7)
1
>>> num_sevens(7777777)
7
>>> num_sevens(2637)
1
>>> num_sevens(76370)
2
>>> num_sevens(12345)
0
>>> from construct_check import check
>>> # b... | 67e3da342208fa130cd0d1400acfbe3d27585d0b | 686,445 |
def svg_ellipse_to_path(cx, cy, rx, ry):
"""Convert ellipse SVG element to path"""
if rx is None or ry is None:
if rx is not None:
rx, ry = rx, rx
elif ry is not None:
rx, ry = ry, ry
else:
return ""
ops = []
ops.append(f"M{cx + rx:g},{cy:g}")... | 9ff88f1bddb6b53e2be3dcd86adc4ce98f0fe4cd | 686,446 |
def _recurse_on_subclasses(klass):
"""Return as a set all subclasses in a classes' subclass
hierarchy."""
return set(klass.__subclasses__()).union(
[
sub
for cls in klass.__subclasses__()
for sub in _recurse_on_subclasses(cls)
]
) | 4fb399c5362ab0019e07c76e71cf16139c0be49a | 686,447 |
import torch
def rel_to_abs(x):
"""
x: [B, Nh * H, L, 2L - 1]
Convert relative position between the key and query to their absolute position respectively.
Tensowflow source code in the appendix of: https://arxiv.org/pdf/1904.09925.pdf
"""
B, Nh, L, _ = x.shape
# pad to shift from relative ... | 547d0884bbcc7a5971e52f1e328caf26badf57de | 686,448 |
def average_word_length(tweet):
"""
Return the average length of the tweet
:param tweet: raw text tweet
:return: the float number of character count divided by the word count
"""
character_count = 0
word_count = 0
for c in tweet:
character_count += 1
word_count = len(twee... | 4077e531c69b51f6df74546b0e84fc41720ffbe5 | 686,449 |
import cProfile
import pstats
import os
def profile(fn, *args, **kw):
"""
Profile a function called with the given arguments.
"""
result = [None]
def call():
result[0] = fn(*args, **kw)
datafile = 'profile.out'
cProfile.runctx('call()', dict(call=call), {}, datafile)
stats = p... | 205c4d2f280570bc036caed840c9ea9f82c51d54 | 686,451 |
def flatten_dataframe_for_JSON(df):
"""Flatten a pandas dataframe to a plain list, suitable for JSON serialisation"""
return df.values.flatten().tolist() | ef4ad28904f083f1d86daefab25ce13faf36a344 | 686,452 |
def convert_time_to_milli_seconds(days=0, hours=0, minutes=0, seconds=0, milli_second=0):
"""
Author : Prudvi Mangadu (prudvi.mangadu@broadcom.com)
Common function to converting time in milli seconds
:param days:
:param hours:
:param minutes:
:param seconds:
:param milli_second:
:ret... | ce113b4422275e92286c30319622f525d9f6269a | 686,453 |
def percents(x, y):
"""what percentage of x is y"""
one_percent = x / 100
result = y / one_percent
# print(str(y) + " is " + str(result) + " percents of " + str(x))
return result | b7e879d6b3fdf6da05ff79b4837420b0b458468d | 686,454 |
def _indent(text, amount):
"""Indent a multiline string by some number of spaces.
Parameters
----------
text: str
The text to be indented
amount: int
The number of spaces to indent the text
Returns
-------
indented_text
"""
indentation = amount * ' '
return... | cf571a3d616e99547757c8ec7d69307985362280 | 686,455 |
def normalize(x, xmin, xmax):
"""Normalize `x` given explicit min/max values. """
return (x - xmin) / (xmax - xmin) | 92d9e0d7e5aad9ee9ff83f3adb042161a3702aec | 686,456 |
def _translate_snapshot_summary_view(context, vol):
"""Maps keys for snapshots summary view."""
d = {}
d['id'] = vol['id']
d['volumeId'] = vol['volume_id']
d['status'] = vol['status']
# NOTE(gagupta): We map volume_size as the snapshot size
d['size'] = vol['volume_size']
d['createdAt'] ... | 9e0fd90e7c6cd702b8309fae3f8122032e1ec854 | 686,457 |
from typing import List
from typing import Dict
import csv
def read_csv(path: str) -> List[Dict[str, str]]:
"""Reads a csv file, and returns the content inside a list of dictionaries.
Args:
path: The path to the csv file.
Returns:
A list of dictionaries. Each row in the csv file will be a list entry. ... | 4051c851fc8919e5c6cb2c6bfd52793e6ab7f639 | 686,458 |
def correct_date(date):
"""
Converts the date format to one accepted by SWA
SWA form cannot accept slashes for dates and is in the format YYYY-MM-DD
:param date: Date string to correct
:return: Corrected date string
"""
if date is None:
return ""
else:
a, b, c = date.s... | 6b17124b4b5e4a3740b56210fc88ea79ca816434 | 686,459 |
import os
def get_dataset_path(dataset: str = "MVTec") -> str:
"""Selects path based on tests in local system or docker image.
Local install assumes datasets are located in anomaly/datasets/.
In either case, if the location is empty, the dataset is downloaded again.
This speeds up tests in docker ima... | 39dc50846a027100ddc4972d84fd40cfea628639 | 686,460 |
def dns_name_encode(name):
"""
DNS domain name encoder (string to bytes)
name -- example: "www.example.com"
return -- example: b'\x03www\x07example\x03com\x00'
"""
name_encoded = [b""]
# "www" -> b"www"
labels = [part.encode() for part in name.split(".") if len(part) != 0]
for label in labels:
# b"www" -> ... | 48b298ade17d232caf533d462ea5ef125ce78622 | 686,461 |
def fib(x):
"""
# 输入测试样例
>>> fib(1)
0
>>> fib(2)
1
>>> fib(3)
1
>>> fib(4)
2
>>> fib(8)
13
"""
if x == 1:
return 0
pred, cur = 0, 1 # init start num
cnt = 1 # position of num in sequence
while cnt < x:
pred, cur = cur, pred + cur
... | 6046f6299f4ec251b797bd6aed1d7957b11c2f0b | 686,462 |
from typing import List
from typing import Tuple
from typing import Any
def construct(keys: List[str], all_values: List[Tuple[Any, ...]]):
"""pass"""
return [dict(zip(keys, values)) for values in all_values] | 70860ffee758daa06d3839106684cd8673e7a823 | 686,463 |
def TestingResources(network_ref, subnet_ref, region, zones):
"""Get the resources necessary to test an internal load balancer.
This creates a test service, and a standalone client.
Args:
network_ref: A reference to a GCE network for resources to act in.
subnet_ref: A reference to a GCE subnetwork for r... | 80545f5c4b842bee788a9b03aa9f975ba073d251 | 686,464 |
import subprocess
def run_cmd(cmd, is_ok=False):
"""
Run cmd
"""
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE,
shell=True, executable='/bin/bash')
output, err = p.communicate()
if is_ok:
if p.returncode == 0:
... | 8eafdb42bedba8afda271ca1da41b547ed9009e8 | 686,465 |
import contextlib
import tempfile
import os
def _read_output(commandstring):
"""Output from successful command execution or None"""
# Similar to os.popen(commandstring, "r").read(),
# but without actually using os.popen because that
# function is not usable during python bootstrap.
# tempfile is a... | 753680c364470f186e7261fcf577298c88a8019d | 686,466 |
import six
def _req_environ_property(environ_field, is_wsgi_string_field=True):
"""
Set and retrieve value of the environ_field entry in self.environ.
(Used by Request)
"""
def getter(self):
return self.environ.get(environ_field, None)
def setter(self, value):
if six.PY2:
... | dce81243f773af103218579991954870eb0edf14 | 686,467 |
def header_to_reftypes(header, context="hst-operational"):
"""Based on `header` return the default list of appropriate reference type names."""
return [] | 4e193854b6a6ed4c30252a24e4db4f159a394cc7 | 686,468 |
def compute_bigram(input, unigram_count, bigram_count):
"""
compute_bigram - function to compute bigram probability
Inputs:
input : tuple
bigram
unigram_count : defaultdict(int)
Occurence hashmap of single words/tokens
bigram_count : defaultdict(int)
Occurence hasmap of bi-words/tokens
Outputs:
out... | 0e8efd792171ae48b3627779e7cf51a6d60d774f | 686,469 |
import sys
def beststr(*strings):
""" Test if the output device can handle the desired strings. The options
should be sorted by preference. Eg. beststr(unicode, ascii). """
for x in strings:
try:
x.encode(sys.stdout.encoding)
except UnicodeEncodeError:
pass
... | 4fd04acc4757c9c7f81dbb46246135297f682c17 | 686,470 |
import textwrap
def clean_description(desc):
"""Cleans a description.
Normally a plugin generates these descriptions with a lot of
spaces at the begining of each line; this function tries to
eliminate all these spaces.
Also trims more than one space between words.
:param desc: the descripti... | 632bd81b2a572ca9bc8f1090d659af2d3116cb8f | 686,471 |
def make_json_serialisable(found_entries, include_abstract):
"""
Used by the getsearch view to create a JSON output.
Given a list of search results (Entry objects), creates a dictionary
that will be formatted to JSON
"""
optionals = ['imgurl', 'html', 'downloadurl']
out = {}
for e in found_entries:
item = ... | 57fd1480337eef5cdced562922fcd4573df78264 | 686,472 |
def filter_output(output, filtered):
""" Filters out characters from output """
for char in filtered:
output = output.replace(char, '')
return output | fc011b1ed5009eadf7b45f3ad76bdb80b9b2b748 | 686,473 |
import re
def get_example_content(item):
"""
For a list item on the vocab example page, beautify it.
:param item: li tag
:return: example sentence string
"""
if item:
try:
result = re.sub('\n', '', item)
# Split examples into their language category
... | cbd3a25ef18714e0c151aa582a943b4395d9e415 | 686,474 |
def addQuotes(s):
"""wrap a strings with quotes"""
return "\"" + s + "\"" | b7895bb9ef872585bfcf9bab2103803dab5b676a | 686,476 |
import pkg_resources
def get_installed_parallelcluster_version():
"""Get the version of the installed aws-parallelcluster package."""
return pkg_resources.get_distribution("aws-parallelcluster").version | 44ac211ec661966bd3bbf3a376bdb6db2cc55ff0 | 686,477 |
def add_number_of_cars(df):
"""df - train or test"""
df['numcars'] = [int((x.count(' ')+1)/7) for x in df['PredictionString']]
return df | f63c43beffb3ab20986b56b0dc3979a799e04419 | 686,478 |
def remove_matching_braces(latex):
"""
If `latex` is surrounded by matching braces, remove them. They are not
necessary.
Parameters
----------
latex : string
Returns
-------
string
Examples
--------
>>> remove_matching_braces('{2+2}')
'2+2'
>>> remove_matching_... | 67adfaa0962c94515cea43b6f393a910443e32f8 | 686,479 |
def point_avg(points):
"""
Accepts a list of points, each with the same number of dimensions.
NB. points can have more dimensions than 2
Returns a new point which is the center of all the points.
"""
dimensions = len(points[0])
new_center = []
for dimension in range(dimensions):
dim_sum = 0 # dimension ... | ac82a036ce5b6fdea0e8c842fba065acd16160a4 | 686,480 |
def _check_errors(results):
"""
<SEMI-PRIVATE> Checks whether the results from the Azure API contain errors or not.
_check_errors(results)
results: [str]
The results from the Azure translation API call
Returns: bool; True if the API results contain errors.
"""
errors = False
for result in result... | 4e35ede6f5146b91022e9a799ed1954897200eab | 686,482 |
from typing import List
def join_sublist_element(input_list: List[List[str]]) -> List[str]:
"""Join each sublist of chars into string.
This function joins all the element(chars) in each sub-lists together, and
turns every sub-lists to one element in the overall list.
The sublist will turned into a st... | 0594b85d264db84faf39b4b4de3e438dd90d4c11 | 686,483 |
def get_attribute(attribute):
"""Reimplementation of operator.attrgetter that can be used with `signature`."""
def _get_attr(obj):
return getattr(obj, attribute)
return _get_attr | 98e7078067e6b7a15cdb6ce925b10087f8019a0c | 686,484 |
def get_airlines():
"""Returns a list of all possible airline codes that can be later passed
as arguments to extract_data_to_json or extract_data_to_csv. Must be called
from Flight-Forecast top-level directory.
"""
airlines = ['All', 'AS', 'G4', 'AA', '5Y', 'DL', 'MQ', 'EV', 'F9', 'H... | cb97d94a19398ffead60f3a1f9f395ba699bea7a | 686,485 |
import json
def make_split_change_event(change_number):
"""Make a split change event."""
return {
'event': 'message',
'data': json.dumps({
'id':'TVUsxaabHs:0:0',
'clientId':'pri:MzM0ODI1MTkxMw==',
'timestamp': change_number-1,
'encoding':'json',
... | 38c79f7b53fd63b83255deea987ebe1c9f4359ed | 686,486 |
import itertools
def minimize_class_set_by_least_generic(schema, classes):
"""Minimize the given Object set by filtering out all superclasses."""
classes = list(classes)
mros = [set(p.compute_mro(schema)) for p in classes]
count = len(classes)
smap = itertools.starmap
# Return only those ent... | 95e6a05d499ddb5a8a488f70a27d2385b4f2aae0 | 686,487 |
def func_1(mol,bits):
""" *Internal Use Only*
Calculate PubChem Fingerprints (116-263)
"""
ringSize=[]
temp={3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0, 10:0}
AllRingsAtom = mol.GetRingInfo().AtomRings()
for ring in AllRingsAtom:
ringSize.append(len(ring))
for k,v in list(temp.items... | c23737242aa8d790bf61aeebb5f13a8ebce83f39 | 686,488 |
import json
def load_data(filename):
"""加载数据
返回:[(texts, labels, summary)]
"""
D = []
with open(filename, encoding='utf-8') as f:
for l in f:
D.append(json.loads(l))
return D | 49d09c13cc71cee3a388f9d914f110c85d5d4936 | 686,489 |
import logging
def _get_logger(fp, enabled=True, log_level="INFO"):
"""Create a logger that outputs to supplied filepath
Args:
enabled (bool): Whether logging is enabled. This function is called
in scripts that call it with suppied arguments, and allows the
scripts this utility... | 1fbbca246b9b235e74ee3d0ee5e1d591c165d322 | 686,490 |
import torch
def lstm_collate_fn(data):
"""Need custom a collate_fn for LSTM DataLoader
Batch images will be transformed to a long sequence.
"""
data.sort(key=lambda x:x[0].shape[0], reverse=True)
images, names, offsets, set_ids, labels, is_compat = zip(*data)
lengths = [i.shape[0] for i in i... | a41b5eb55307cb413a6e8965a287773312e2d0f2 | 686,491 |
def assemble(current_lst):
"""
:param current_lst: list of index for the string list
:return: str, assemble list as string
"""
string = ''
for alphabet in current_lst:
string += alphabet
return string | 86f7b4fc9a72f2cd2ea17600d1bc0e31fcd03c97 | 686,492 |
def merge_sort(alist):
"""归并排序"""
n = len(alist)
if n <= 1:
return alist
mid = n // 2
# left 采用归并排序后形成的有序的新的列表
left_li = merge_sort(alist[:mid])
# right 采用归并排序后形成的有序的新的列表
right_li = merge_sort(alist[mid:])
# 将两个有序的子序列合并为一个新的整体
# merge(left, right)
left_pointer, rig... | 388aa46a0dd6cd99b64f0a0d1fe17e91234ae6a0 | 686,494 |
import random
def dataset_creation(labeled_data):
"""Split labeled data into train and test"""
one_class = []
zero_class = []
for data_point in labeled_data:
if data_point[2] == 0:
zero_class.append(data_point)
else:
one_class.append(data_point)
random.shuff... | e94a6b289d133866b2a4f2a48ded626aeb6228e5 | 686,495 |
import os
def getdir():
"""
:return:
"""
print(os.getcwd())
return os.getcwd() | 8e15010396c0f0aafdec20749339c91aa3cbf0d8 | 686,496 |
import random
def get_random_person():
"""
Получить 1 го случайного человека
:return:
"""
FAMOUS_PEOPLE = {'Александр Сергеевич Пушнин': '26.06.1799', 'Михаил Юрьевич Лермонтов': '15.10.1814',
'Сергей Александрович Есенин': '03.10.1895', 'Владимир Семенович Высоцкий': '25.01.1... | 013477ab07071d9e0d3dc2e9303e713d2fea3e6a | 686,497 |
def get_alpha(start, end, current, iteration):
"""Get alpha value for interpolations.
"""
if start == end:
return 0.
numerator = abs(current - start)
denominator = abs(end - start)
return numerator / denominator | 7e0b272bd0bfb19defdfc9f4512b97b1bbdc41cb | 686,498 |
def is_power_of_two(value: int) -> bool:
"""
Determine if the given value is a power of 2.
Negative numbers and 0 cannot be a power of 2 and will thus return `False`.
:param value: The value to check.
:return: `True` if the value is a power of two, 0 otherwise.
"""
if valu... | 306702ee4291fdcc2a7d4871e7ec4f2e24c8ffd6 | 686,499 |
def add_clusters_to_df(df, clusters):
"""Add the found clusters to the data."""
df_with_clusters = df.copy()
df_with_clusters["cluster"] = -1
for i, row in df_with_clusters.iterrows():
df_with_clusters.iat[i, -1] = clusters[i]
return df_with_clusters | 902bb9db96d17af5d99ad19a58016a52ab2b9156 | 686,500 |
import click
def validate(dic, option_list):
"""
images command validation
"""
for key in dic.viewkeys():
if key in option_list:
for option in option_list:
if option != key:
if dic[option] and dic[key]:
raise click.UsageError('Invalid option combination --%s \
cannot be used with --%s' ... | 9b66c39648383979b605231c374391f6d46de98d | 686,501 |
def reselect (total, surplus, df):
""" Models uniform reselection on a password probability distribution.
Args:
total (float): The total probability (should be approximately equal to 1).
surplus (float): The surplus probability (should be less than or equal to `total`).
df (DataFrame): ... | abb18df33adc8fbf79bde5366d08173e40a3b8f1 | 686,503 |
def version_to_sortkey(v):
"""
Version limits:
'a.b.c.d' , where a < 2^5
"""
MAX_SIZE = 4
MAX_VERSION_SIZE_2_POW = 5
v = v.split('.')
res = 0
for (ind, val) in enumerate(v):
res += int(val) << ((MAX_SIZE - ind) * MAX_VERSION_SIZE_2_POW)
return res | f4cc1e478377f43cce48072676e852b292a3fe82 | 686,504 |
def get_ctx_result(result):
""" This function get's called for every result object. The result object represents every ActionResult object that
you've added in the action handler. Usually this is one per action. This function converts the result object into a
context dictionary.
:param result: ActionR... | ac6f0a4d4e4632a69703f036fbb6e5ffc3444df9 | 686,505 |
def precatenated(element, lst):
"""
pre-catenates `element` to `lst` and
returns lst
"""
lst.insert(0, element)
return lst | 2499759e6a743b6ad24c0518bd348a72a3ef719a | 686,506 |
def value_shape(shape):
"""
"""
return [shape[0], shape[1], 1] | 99d244a5211e39bd0ea7e392f6d611578ddffd7b | 686,507 |
def cry(l, b, i):
"""ಥ_ಥ"""
b.l_say(cry.__doc__, i)
return True | c9f727d1281905c9d467e284896ba78c30309fc7 | 686,508 |
def pintensity(policies, weights):
"""Get the total intensity of a given bin of policies"""
total = 0
for p in policies:
if p == "nan":
continue
if p not in weights.keys():
raise ValueError(f"Missing intensity group: {p}")
else:
total += weights[... | 86b305f75a8027aedacc52709e83b316c3233e88 | 686,509 |
import argparse
import os
import sys
def parse_and_validate(args):
"""
Parse input args
"""
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--input_file",
help="input fast file",
type=str,
required=True,
... | 6e52a03d5817d8c158b767e7f14b09ea647e9285 | 686,510 |
import numpy
def get_basin_details(basin_cube):
"""Extract details from a basin cube created by calc_basin.py."""
basin_values = numpy.array([int(num) for num in basin_cube.attributes['flag_values'].split(' ')])
basin_edges = basin_values - 0.5
basin_edges = numpy.append(basin_edges, basin_values[-1]... | 8637e775263d5de47907df29482178c80bf555bc | 686,511 |
import numpy as np
def Rotate( element, theta):
"""Applies a rotation operation on any polarizing element given
its Jones matrix representation and a angle of rotation.
The angle is to be given in radians.
"""
assert isinstance(element, np.matrix)
assert element.shape == (2,2... | b6110a21135341d3f59e2c0d79fd9159402179e8 | 686,512 |
def barchart_data(image_pipeline_msg_sets):
"""Converts a tracing message list into its corresponding
relative (to the previous tracepoint) latency list in
millisecond units.
Args:
image_pipeline_msg_sets ([type]): [description]
Returns:
list: list of relative latencies, in ms
... | f9ad6854995b49f341158b2174fbc99aa3e71da2 | 686,513 |
import re
def extract_and_change_atomnames(molecule, selected_resname, core_resname, rename=False):
"""
Given a ProDy molecule and a Resname this function will rename the PDB atom names for the selected residue following
the next pattern: G1, G2, G3...
:param molecule: ProDy molecule.
:param selec... | 5ec4499d34087fc1c271789f1283f18212a82a2d | 686,514 |
def mask_number(not_masked_number: str):
"""
Public function: convert numbers into similar looks letters
"""
not_masked_number = str(not_masked_number)
return not_masked_number \
.replace("0","o") \
.replace("1","i") \
.replace("2","Z") \
... | 6bc0ecbd1f2e04221c47643db69ff7b1beca93b3 | 686,515 |
from typing import Set
import warnings
def _aggregate_n_repetitions(next_chunk_repetitions: Set[int]) -> int:
"""In the future, we will allow each accumulator to request a different number
of repetitions for the next chunk. For batching efficiency, we take the
max and issue a warning in this case."""
... | 368a56cb3c16398606e94e0818eaf39d53003e4e | 686,516 |
def user_to_json(user):
"""Convert SQL queries to actual dictionaries."""
result = {
"id": user.id,
"first_name": user.first_name,
"last_name": user.last_name,
"email": user.email,
"role_id": user.role_id,
"date_created": user.date_created
}
return result | d2d62499582dbe706b9ab1caa5ff0d8a0d9d01a2 | 686,517 |
import random
def partition_train_eval(*args):
"""
Partitions the data set into a train
:param args: Nothing happens with this.
:return: 1 or 0: whether the record will be
"""
# pylint: disable=unused-argument
return int(random.uniform(0, 1) >= .8) | 60eb87c11de2bac2139d5ea9d9f2353b34ef7038 | 686,518 |
def _decode_str(message):
""" Decode message to tuples to add to image pixels """
res = [] # list of tuples containing decoded numbers
for char in message:
c = ord(char) # ASCII code of this character
t_1 = c >> 5 # shift it to the right by 5 bits
t_2 = (c & 0x1F... | f0a3b302641d8da23cb1d62d9334254571a43e86 | 686,519 |
import imaplib
def connect(server, username, password):
""" connecting to the imap server """
connection = imaplib.IMAP4_SSL(server)
connection.login(username, password)
return connection | 8f5d77b135a2344767b568dc8a98a0e40db96ba9 | 686,520 |
import functools
import typing
def affix_type_hints(obj=None, *, globalns=None, localns=None, attrs: bool = True):
"""
Affixes an object's type hints to the object by materializing evaluated string type hints
into the type's __annotations__ attribute.
This function exists due to PEP 563, in which ann... | 508a10120a46340f6e40a6a89efa1a664c9f8e0d | 686,521 |
import os
def mFileListPNG(vPathOfFile):
"""This section is created in fetching only .png files """
vPath = vPathOfFile
vFilesNamesPNG = []
for vRootDir, vCurrentDir, vFile in os.walk(vPath):
del vCurrentDir[:]
for file in vFile:
if '.png' in file:
vFilesNam... | 06b52c20840af8b3edea87a2fd35f87d2d657e62 | 686,522 |
def _downsample_scans(obj_scan, blank_scan, dark_scan, downsample_factor=[1, 1]):
"""Down-sample given scans with given factor.
Args:
obj_scan (float): A stack of sinograms. 3D numpy array, (num_views, num_slices, num_channels).
blank_scan (float): A blank scan. 3D numpy array, (1, num_slices, ... | 195bce61d0d55a8106dd0355e358ae7b375a4063 | 686,523 |
def get(seq, ind, defVal=None):
"""Return seq[ind] if available, else defVal"""
try:
return seq[ind]
except LookupError:
return defVal | 9e9f64145fb1780b8c956737e080dcddb7e4e0d5 | 686,524 |
import os
def restore_state_file(state_file_name):
"""Read the state file if any and restore existing replacement tokens
that were established from a previous run.
"""
state = {}
if not os.path.exists(state_file_name):
return state
with open(state_file_name, "r") as file_:
fo... | afd790cd615acf5d3904163688005d7ca8c77a0c | 686,525 |
def get_bot_in_location(location, game):
"""Returns the bot in the given location."""
bots = game.get('robots')
if location in bots.keys():
return bots[location]
else:
return None | bcc4f909dc2fd936fe83a641d2966c475e58ffa6 | 686,526 |
def get_irregular_edge_by_vertex(graph, vertex):
"""
Loops over all edges that are incident to supplied vertex and return a first irregular edge
in "no repeat" scenario such irregular edge can be only one for any given supplied vertex
"""
for edge in graph.get_edges_by_vertex(vertex):
if... | d2ab29a2b78466614dfe0a94f7279a6ecd10e793 | 686,527 |
def is_mutable_s(text: str) -> bool:
"""
Checks if the word starts with a mutable 's'.
('s' is mutable when followed by a vowel, n, r, or l)
:param text: the string to check
:return: true if the input starts with a mutable s
"""
lc = text.lower()
return len(lc) >= 2 and lc[0] == 's' and... | e45ddd8b7cc060d39944fc6590f6aa2eb86bb379 | 686,528 |
def get_or_add_license_to_serializer_context(serializer, node):
"""
Returns license, and adds license to serializer context with format
serializer.context['licenses'] = {<node_id>: <NodeLicenseRecord object>}
Used for both node_license field and license relationship.
Prevents license from having to ... | f06813b5ae3b051b91cd2416431fc3c48f9ecfcc | 686,531 |
def NBR(ds):
"""
Computes the Normalized Burn Ratio for an `xarray.Dataset`.
The formula is (NIR - SWIR2) / (NIR + SWIR2).
Values should be in the range [-1,1] for valid LANDSAT data (nir and swir2 are positive).
Parameters
----------
ds: xarray.Dataset
An `xarray.Dataset` that must... | 2030cde88eaf8e4e2999d4db09ba4d3ea7e93260 | 686,533 |
def epsIndicator(frontOld, frontNew):
"""
This function computes the epsilon indicator
:param frontOld: Old Pareto front
:type frontOld: list
:param frontNew: New Pareto front
:type frontNew: list
:return: epsilon indicator between the old and new Pareto fronts
:rtype: float
"... | 8ec7b18b36a32b963c148aa7592557c2724bde0d | 686,534 |
def readable_timedelta(days):
# insert your docstring here
"""Returns a string of the number of week(s) and day(s) in the given days.
Args:
days (int): number of days to convert
"""
weeks = days // 7
remainder = days % 7
return "{} week(s) and {} day(s)".format(weeks, remainder) | 62672e2b6e7c16570d40586f59394cd76f0df05c | 686,535 |
import json
def msg_2_json(msg):
"""doc"""
data = msg.decode()
data = eval(data)
json_msg = json.dumps(data)
return json.loads(json_msg) | 4fe0c16a58264f796e55b50372d91c6c00804886 | 686,536 |
def _calculate_gratuity(no_of_years, days_per_year, gratuity_days, gross_salary):
"""
Indemnity calculation
Source: https://github.com/hafeesk/Hr/blob/master/hr_bahrain/hr_bahrain/hr_controllers.py
:param no_of_years:
:param days_per_year:
:param gratuity_days:
:param gross_salary:
:ret... | b00d748cf9eced65f2cfaf19f9ac59f8a3be3282 | 686,537 |
def _prepare_tabledata(fingerprint_df):
"""
Create interaction index dictionary for fingerprint table.
The keys of this dictionary are the interaction types and the values
for each interaction type are a list of the positions (indices) of
the fingerprint array that represent this interaction type.
... | 8b531ed7b568a18994f71796ae689909f9c307a9 | 686,538 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.