content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_basic_whitespace():
"""Tests that basic text maintains whitespace."""
soup = TexSoup("""
Here is some text
with a line break
and awko taco spacing
""")
assert len(str(soup).split('\n')) == 5, 'Line breaks not persisted.' | 76,100 |
def test_fattree_generator(size):
"""
Some basic test for FatTree generator. Ensure we return correct types
and correct number of nodes. Additionally, check that core has correct
number of switches and fatter links
"""
topo = fat_tree(size)
assert isinstance(topo, Topology)
assert isinst... | 76,101 |
def token_cleanup():
"""Removes revoked and expired tokens from database"""
from run4it.api.scripts import script_token_registry_purge as script_func
return script_func('token_cleanup') | 76,102 |
def test_cache_enterprises_creates_file(mocker):
"""Test update enterprise success."""
write_patch = mocker.patch(
'p360_contact_manager.common.WriteLocalFile.__call__',
)
write_patch.return_value = Success(True)
test_data = {'json': 'data'}
assert CacheEnterprises(
lambda: Succ... | 76,103 |
def get_vlans(ip, port, username, password) -> list:
"""Gets device components /restconf/data/openconfig-platform:components"""
data = []
uri = f"https://{ip}:{port}/restconf/data/Cisco-IOS-XE-vlan-oper:vlans"
response = requests.get(uri, headers=headers, verify=False, auth=(username, password))
v... | 76,104 |
def _run_work_order_fn(zap_id, work_order_i):
"""
Wrap the function to handle args, kwargs, capture exceptions, and re-seed RNG.
Note: This may run in the sub-process or thread and therefore should not use stdio.
"""
start_time = time.time()
try:
work_order = _get_zap(zap_id).work_orders... | 76,105 |
def head(path, lines=10):
"""
Get the first lines of a file.
Args:
path (str): Path to the file to read.
lines (int): Number of lines to read.
Returns:
:obj:`list` of :obj:`str`: The lines found.
"""
with open(path) as f:
return list(islice(f, lines)) | 76,106 |
def check_analyzed_packages_count_at_least(context, num=1):
"""Check number of analyzed packages."""
context_reponse_existence_check(context)
json_data = context.response.json()
check_attribute_presence(json_data, "result")
result = json_data["result"]
check_attribute_presence(result, "data")
... | 76,107 |
async def update_service_tokens(settings: Optional[str]) -> None:
"""Update service tokens stored in Kubernetes secrets."""
if settings:
config_dependency.set_settings_path(settings)
config = await config_dependency()
logger = structlog.get_logger(config.safir.logger_name)
async with Compone... | 76,108 |
def ntg_collate(data):
"""Creates mini-batch tensors from the list of tuples (src_seq, trg_seq)."""
# separate source and target sequences
src_sent,tgt_sent = list(zip(*data))
# t2i
_inputs = [batch_sentences(src_sent),
batch_sentences(tgt_sent),
]
return _inputs | 76,109 |
def FnutoFlambda(Fnu, wavelength):
"""
Converts F_nu to F_lambda.
:param Fnu: Fnu [ers/s/cm**2/Hz]
:type Fnu: float or ndarray
:param wavelength: wavelength [AA]
:type wavelength: float or ndarray
:return: Flambda [ergs/s/cm**2/AA]
"""
return Fnu / wavelength / wavelength * C | 76,110 |
def minor_ticks(nx=5,ny=5,x=True,y=True):
"""
Sets *n* minor tick marks per major tick for the x and y axes of the current figure.
*nx: integer number of minor ticks for x, DEFAULT: 5
*ny: integer number of minor ticks for y, DEFAULT: 5
*x: True/False, DEFAULT: True
*y: True/False, D... | 76,111 |
def PSNR(gt, img, drange):
"""
Computes the highest PSNR by affine rescaling of x,
such that the mean squared error to gt is minimal.
:param gt: ground truth
:param img: image
:param drange: data range
:return: PSNR
"""
img = normalize_minmse(img, gt)
mse = torch.mean(torch.squa... | 76,112 |
def find_symlinks_cmd():
"""
%prog [start-path]
Search the specified path (defaults to the current directory) for symlinks,
printing the source and target on each line.
"""
from optparse import OptionParser
from textwrap import dedent
parser = OptionParser(usage=dedent(find_symlinks_cmd... | 76,113 |
def test_write_time_precision(gain_data, tmp_path):
"""
Test that times are being written to appropriate precision (see issue 311).
"""
cal_in = gain_data
cal_out = UVCal()
write_file = str(tmp_path / "outtest_time_prec.fits")
# overwrite time array to break old code
dt = cal_in.integra... | 76,114 |
def test_fragments_consolidate_and_vacuum(runner, uri):
"""
Test for command
tiledb consolidate fragments [array_uri]
tiledb vacuum fragments [array_uri]
"""
fragments = tiledb.array_fragments(uri)
assert len(fragments) == 2
result = runner.invoke(root, ["consolidate", "fragmen... | 76,115 |
def get_postgres_connection_url() -> str:
""" Собирает ссылку для подключения к БД и возращает её.
"""
db = POSTGRES_DB
host = POSTGRES_HOST
port = POSTGRES_PORT
user = POSTGRES_USER
password = POSTGRES_PASSWORD
if not all([db, host, port, user, password]):
raise DatabaseSetting... | 76,116 |
def check_if_string_in_file(file_name, string_to_search): #string checker
""" Check if any line in the file contains given string """
# Open the file in read only mode
with open(file_name, 'r') as read_obj:
# Read all lines in the file one by one
for line in read_obj:
# For each ... | 76,117 |
def count_per_domain_statistics(
domain_idxs: torch.Tensor
) -> Tuple[np.ndarray, np.ndarray]:
"""
Args:
- domain_idxs: Pytorch tensor of shape (N,) showing assignment
of each example to each particular domain
Returns:
- examples_per_domain: Numpy array of s... | 76,118 |
def test_refpage_unknown_attrib(ckr):
"""Check the REFPAGE_UNKNOWN_ATTRIB message."""
ckr.enabled([MessageId.REFPAGE_UNKNOWN_ATTRIB])
# Should not error: these are known attribute names
assert(not ckr.check(
"[open,refpage='',desc='',type='',xrefs='']").messages)
# Should error: xref isn't ... | 76,119 |
def find_faces_rt(duration=30):
""" This function reads frames from the camera and marks faces, doing so
continuously for a set duration. Its goal is to help set all of the
relevant parameters.
"""
# Open capture device
cap = cv2.VideoCapture(0)
# Load cascade
front_cascade = cv2.Cascad... | 76,120 |
def handler500(request):
"""
This is a Django handler function for the 500 server error page. Because a server error can imply an serious issue
such as corrupted database, a nice render of the 500 page may be impossible. So the server first attemps to nicely
render the page with all the dynamic element,... | 76,121 |
def featurenet_backbone(input_tensor=None, input_shape=None,
n_filters=32, **kwargs):
"""Construct the deepcell backbone with five convolutional units
Args:
input_tensor (tensor): Input tensor to specify input size
n_filters (int): Defaults to 32. Number of filters for
... | 76,122 |
def call_somewhat_forgivingly(
func, args, kwargs, enforce_sig: Optional[SignatureAble] = None
):
"""Call function on given args and kwargs, but with controllable argument leniency.
By default, the function will only pick from args and kwargs what matches it's
signature, ignoring anything else in args a... | 76,123 |
def config_update(delete_objects=False):
"""sync configuration with data from YAML-formatted stdin"""
import yaml, sys
new_config=yaml.load(sys.stdin)
# print new_config
users=new_config['users']
tracked_users=set()
for user_config in users:
localpart=user_config['localpart']
... | 76,124 |
def warning(message):
"""
Show error using warnings module. Shows function from stack that called this function.
"""
warn(message, stacklevel=3) | 76,125 |
def assert_isomorphic(g1: Graph, g2: Graph) -> None:
"""Compares two graphs an asserts that they are isomorphic.
If not isomorpic a graph diff will be dumped.
Args:
g1 (Graph): a graph to compare
g2 (Graph): the graph to compare with
"""
_isomorphic = isomorphic(g1, g2)
if... | 76,126 |
def generate_formula_with_template() -> str:
"""Generate a brew formula by using a template"""
template_path = os.path.join(os.path.dirname(__file__), TEMPLATE_FILE_NAME)
with open(template_path, mode='r') as template:
template_content = template.read()
template = jinja2.Template(template_conte... | 76,127 |
def _get_list_of_layers(
input_dim: int, hidden_dim: int, output_dim: int, num_layers: int
) -> List[nn.Module]:
"""Utility function to get a list of layers. This assumes all the hidden
layers are using the same dimensionality.
Args:
input_dim (int): input dimension.
hidden_dim (int): d... | 76,128 |
def LagrangeMultiplierMethod(H, f):
"""
LEXMIN Solve the multi-objective minimization problem:
min {E1(x), E2(x), ... , Ek(x)}
x
where
Ei = 0.5 * x.T * H[i] * x + x.T * f[i]
and Ei is deemed "more important" than Ei+1 (lexicographical ordering):
https://en.wikipedia.org... | 76,129 |
def getcwdb(*args, **kwargs): # real signature unknown
""" Return a bytes string representing the current working directory. """
pass | 76,130 |
def test_crypto_lr(fit_intercept, hook, workers):
"""
Test EncryptedLinearRegression, i.e. distributed linear regression with MPC
"""
bob = workers["bob"]
alice = workers["alice"]
james = workers["james"]
crypto_prov = workers["james"]
hbc_worker = workers["charlie"]
###### Simulat... | 76,131 |
def test_overwrite_all():
"""Test overwriting the entire mapping."""
rm = RangeMap({1: 'a', 2: 'b'})
rm.set('z', start=0)
with pytest.raises(KeyError):
rm[-1]
assert rm[0] == 'z'
assert rm[1] == 'z'
assert rm[2] == 'z'
assert rm[3] == 'z' | 76,132 |
def rescale_to_11bits(im_float):
"""Rescale a float image in [0, 1] to integers in [0, 2047].
This operation makes rank filtering much faster.
Parameters
----------
im_float : array of float in [0, 1]
The float image. The range and type are *not* checked prior to
conversion!
R... | 76,133 |
def get_data(session_id, n_intervals):
"""Query Database and prepare data as DataFrame.
Parameters
----------
session_id : str
unique session id hex used for caching.
interval : int
update interval from counter used for updating data.
Returns
-------
df : pandas DataFra... | 76,134 |
def multi_dict_unpacking(lst):
"""
Receive a list of dictionaries, join them into one big dictionary
"""
result = {}
for d in lst:
for key, val in d.items():
result[key] = val
return result | 76,135 |
def test_session_sequence_repeating():
"""Test session sequence for a single object class, repeating."""
def run():
compare_sc = get_committed_sc_x(Product)
session_sc, committed_sc = session_sequence_x(Product)
# Assert Result #
assert compare_sc.sync_count + 1 == session_sc.... | 76,136 |
def test_list_int_max_length_3_nistxml_sv_iv_list_int_max_length_4_1(mode, save_output, output_format):
"""
Type list/int is restricted by facet maxLength with value 8.
"""
assert_bindings(
schema="nistData/list/int/Schema+Instance/NISTSchema-SV-IV-list-int-maxLength-4.xsd",
instance="ni... | 76,137 |
def test_insert_creates_head():
"""Inserting a node will create a head."""
from priority_queue import Priority_Q
q = Priority_Q()
q.insert('x')
assert q.head.data is 'x' | 76,138 |
def dist(a: list, b: list) -> float:
"""Calculate the distancie between 2 points
Args:
a (list): point a
b (list): point b
Returns:
float: Distance between a and b
"""
return math.sqrt((a[0]-b[0])**2+(a[1]-b[1])**2) | 76,139 |
def test_timesplit_repr():
"""Test TimeSplit __repr__ method."""
cases = [
(333, "<TimeSplit 00:05:33>"),
(3723, "<TimeSplit 01:02:03>"),
(93784, "<TimeSplit 1d02:03:04>"),
(1209600, "<TimeSplit 14d00:00:00>"),
(-93784, "<TimeSplit -1d02:03:04>"),
(-1209600, "<Tim... | 76,140 |
def is_array_like(item):
"""Check if item is an array-like object."""
return isinstance(item, (list, set, tuple, np.ndarray)) | 76,141 |
async def verifyGroupPath(h5path):
""" create any groups along the path that doesn't exist
"""
#print("current task: ", asyncio.Task.current_task())
client = globals["client"]
domain = globals["domain"]
h5path_cache = globals["h5path_cache"]
params = {"host": domain}
parent_group = h5pat... | 76,142 |
def run_thermo_estimator(input_file, library_flag):
"""
Estimate thermo for a list of species using RMG and the settings chosen inside a thermo input file.
"""
rmg = RMG()
rmg.load_thermo_input(input_file)
rmg.database = RMGDatabase()
path = os.path.join(settings['database.directory'])
... | 76,143 |
def start_args():
"""
Prepare the things required for Brick Start and Returns the Proc
object required to start Brick Process.
"""
brick_device = os.environ.get("BRICK_DEVICE", None)
brick_path = os.environ["BRICK_PATH"]
if brick_device is not None and brick_device != "":
brickfs = ... | 76,144 |
def getVIIRSfilesbygranule(basedir, scenelist=[]):
"""
Returns a dictionary that parses a list of scene directories where each
name YYYY_MM_DD_JJJ_hhmm refers to an overpass timestamp and contains
multiple granules and individual desaggregated band files. GINA (the
Geographic Information Network of ... | 76,145 |
def train(args):
"""Train a model.
"""
data_dir = args.data_dir
workspace = args.workspace
mini_data = args.mini_data
balance_type = args.balance_type
learning_rate = args.learning_rate
filename = args.filename
model_type = args.model_type
model = args.model
batch_size = arg... | 76,146 |
def test_run_command_with_kwargs(capsys: pytest.CaptureFixture[str]) -> None:
"""Keyword arguments to run_command must be used as environment variables.
"""
retcode = utils.run_command("env", dict(ZZZZZZZZZZ="ZZZZZZZZZZ"))
stdout, stderr = capsys.readouterr()
assert not stderr
assert not retcode... | 76,147 |
def coord(x, y, integer=False):
"""
Convert world coordinates to pixel coordinates. Setting 'integer' to
True will return integer coordinates.
"""
xs = (DRAW_OFFSET[0] + DRAW_SCALE*x)
ys = (DRAW_OFFSET[1] - DRAW_SCALE*y)
if integer:
return int(round(xs)), int(round(ys))
else:
... | 76,148 |
def handle_match(match, url):
"""Should there be a match, format a message and send a notification."""
if match:
message = "Match found at {}:\n{}".format(url, match)
return __send_notification(url, message)
else:
return 'Missing match at: {}'.format(url) | 76,149 |
def call_model(model_type="mosaic", file_path="tests/flowers.jpg"):
"""helper function"""
model_endpoint = 'http://localhost:5000/model/predict?model=' + model_type
with open(file_path, 'rb') as file:
file_form = {'image': (file_path, file, 'image/jpeg')}
r = requests.post(url=model_endpoi... | 76,150 |
async def post_iot_telemetry(devicetoken: str):
"""模拟物联网遥测数据推送接口,有物联网服务器,暂未实现"""
log.log(devicetoken)
pass | 76,151 |
def get_soup(url):
"""Gets BS object from the given URL"""
# - Get Data
html = get_data(url)
# - Get Soup
soup = BeautifulSoup(html, 'html.parser')
if soup is None:
raise Exception("No data from URL")
return soup | 76,152 |
def node_wise_2_sample(latent, node_ind):
"""Get dcorr t stat for a single node"""
node_latent_pop1 = np.squeeze(latent[:n_graphs, node_ind, :])
node_latent_pop2 = np.squeeze(latent[n_graphs:, node_ind, :])
t_stat = compute_t_stat(node_latent_pop1, node_latent_pop2)
return t_stat | 76,153 |
def upload_single_file(application, file_path, version, override,
stable, scope, force=False, initial_visibility=None, no_wait=False):
"""
:return: exit code
:rtype: int
"""
app_info = read_jar_file(file_path)
if not force and override and not (stable and SCOPE_DICT[scope]... | 76,154 |
def create_public_key(private_key):
"""Create a public key corresponding to the given private key.
To accomplish this, you only need to build and return `beta` as described in the handout.
beta = (b_1, b_2, ..., b_n) where b_i = r × w_i mod q
Hint: this can be written in one line using a list com... | 76,155 |
def create(sender, recipients=None, cc=None, bcc=None, subject='', message='',
html_message='', scheduled_time=None, headers=None,
template=None, priority=None, commit=True,
backend=''):
"""
Creates an email from supplied keyword arguments. If template is
specified, email su... | 76,156 |
def delete_user(user):
"""
Function to delete a user
"""
user.delete_user() | 76,157 |
def get_fields_eligible_for_pagination(
schema_info: QueryPlanningSchemaInfo,
types: Dict[VertexPath, Union[GraphQLObjectType, GraphQLInterfaceType]],
single_field_filters: Dict[PropertyPath, Set[FilterInfo]],
fold_scope_roots: Dict[VertexPath, VertexPath],
) -> Set[PropertyPath]:
"""Return all the ... | 76,158 |
def cleanup_session(session):
"""Clean-up the current session for a clean state."""
@ignore_exceptions
def _dismiss_user_prompts(session):
"""Dismiss any open user prompts in windows."""
current_window = session.window_handle
for window in _windows(session):
session.wind... | 76,159 |
def _parse_commit_position(commit_message):
"""Parses a commit message for the commit position.
Args:
commit_message: The commit message as a string.
Returns:
An int if there is a commit position, or None otherwise."""
match = re.search(
'^Cr-Commit-Position: [a-z/]+@{#([0-9]+)... | 76,160 |
def convert_simple_type(value: Any, json_definition: dict) -> Any:
"""
:param value: Can be of any JSON type except list or dict.
:param json_definition: OpenAPI definition of the value (format used to parse it).
"""
if isinstance(value, str):
field_format = json_definition.get("format") if ... | 76,161 |
def pprinttable(rows):
"""
Author: MattH
Here's a quick and dirty little function I
wrote for displaying the results from SQL
queries I can only make over a SOAP API.
It expects an input of a sequence of one or
more namedtuples as table rows. If there's
only one record, it prints it out diff... | 76,162 |
def block_diag(m):
"""
Make a block diagonal matrix along dim=-3
EXAMPLE:
block_diag(torch.ones(4,3,2))
should give a 12 x 8 matrix with blocks of 3 x 2 ones.
Prepend batch dimensions if needed.
You can also give a list of matrices.
:type m: torch.Tensor, list
:rtype: torch.Tensor
... | 76,163 |
def _twoByteStringToNum(bytestring, numberOfDecimals=0, signed=False):
"""Convert a two-byte string to a numerical value, possibly scaling it.
Args:
* bytestring (str): A string of length 2.
* numberOfDecimals (int): The number of decimals. Defaults to 0.
* signed (bol): Whether large p... | 76,164 |
def webots_controller_function():
""" webots动作控制器 """
# 初始化节点
rospy.init_node('gps_sensor_controller_node', anonymous=True)
# 使能传感器
serviceName = "/gps_rbt/my_gps/enable"
setEnableClient = rospy.ServiceProxy(serviceName,set_int)
resp = setEnableClient.call(1)
# 订阅传感器数据话题
Sub = ros... | 76,165 |
def smape(y_true, y_pred):
"""
Calculates the symmetric mean absolute percentage error of the predicted
values to the true values. `y_true`, `y_pred` should be of the same
type and shape.
The SMAPE is calculated as:
2 * mean(|y_pred - y_true| / (|y_pred| + |y_true|))
Therefore, it is ... | 76,166 |
def test_stem_method():
"""Check the _stem method."""
tokenizer = Tokenizer("test_data/stopwords.txt", None)
# test with no stemmer
tokens = ["foo", "bar", "me", "your", "6502"]
tokenizer._stem(tokens)
assert tokens == ["foo", "bar", "me", "your", "6502"]
# test with custom stemmer
tok... | 76,167 |
def _api_rss_now(name, output, kwargs):
""" API: accepts output """
# Run RSS scan async, because it can take a long time
scheduler.force_rss()
return report(output) | 76,168 |
def _print_operation_signal(op_list, run_time_prepare_data=0, operator=None, history_data=None):
"""打印实时信号生成模式的运行结果
"""
print(f'\n'
f' ====================================\n'
f' | |\n'
f' | OPERATION SIGNALS |\n'
... | 76,169 |
def get_middle_opt(string: str) -> str:
"""Get middle value of a string (efficient).
Examples:
>>> assert get_middle_opt('middle') == 'dd'
"""
return (
string[int(len(string) // 2) - 1 : int(len(string) // 2) + 1]
if not len(string) % 2
else string[int(len(string) // 2)]... | 76,170 |
def train_net(clf, out_path, epochs, inputs, targets, labels_train, labels_test, batch_size):
"""
Trains the neural network
"""
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
inputs = torch.tensor(inputs).type(torch.DoubleTensor).to(device)
targets = torch.tensor(targets... | 76,171 |
def test_complex_double_none_comparison():
"""For unknown reasons this can return a flex.bool() object on some builds."""
assert (flex.complex_double() == None) is False | 76,172 |
def group(iterable, N, fillvalue=None):
"""
>>> list(group((), 3, fillvalue=-1))
[]
>>> list(group(xrange(6), 3, fillvalue=-1))
[(0, 1, 2), (3, 4, 5)]
>>> list(group(xrange(7), 3, fillvalue=-1))
[(0, 1, 2), (3, 4, 5), (6, -1, -1)]
"""
iterable = iter(iterable)
try:
while ... | 76,173 |
def vmess_IO(class_):
"""
获取可用订阅链接并刷新存储池
class_: ssr ; v2ray
"""
def refresh_log(dataFlow):
with open(SYS_AIRPORT_INFO_PATH, 'w', encoding='utf-8', newline='') as fp:
writer = csv.writer(fp)
writer.writerows(dataFlow)
try:
with open(SYS_AIRPORT_INFO_PATH... | 76,174 |
def events_disconnect():
"""Route to notify that certain user has been disconnected."""
del current_app.clients[session["userid"]]
room = f"uid-{session['userid']}"
leave_room(room)
app.logger.info("Client %s disconnected.", session["userid"]) | 76,175 |
def dump(obj, file_name):
"""
将指定对象,以file_nam为名,保存到本地
"""
with open(file_name, 'wb') as f:
pickle.dump(obj, f)
return | 76,176 |
def assert_estimator_equal(left, right, exclude=None, **kwargs):
"""Check that two Estimators are equal
Parameters
----------
left, right : Estimators
exclude : str or sequence of str
attributes to skip in the check
kwargs : dict
Passed through to the dask `assert_eq` method.
... | 76,177 |
def get_anonymous_current_user(locale: Optional[str]) -> CurrentUser:
"""Return an anonymous current user object."""
return CurrentUser(
id=ANONYMOUS_USER_ID,
screen_name=None,
suspended=False,
deleted=False,
locale=locale,
avatar_url=None,
authenticated=F... | 76,178 |
def cut_sites_with_region(df_sites, df_region):
"""Find peak interval the crosslinks belong to."""
df_p = df_sites[df_sites['strand'] == '+'].copy()
df_m = df_sites[df_sites['strand'] == '-'].copy()
df_region_p = df_region[df_region['strand'] == '+'].copy()
df_region_m = df_region[df_region['stran... | 76,179 |
def check_inplane_vector(vector, normal):
"""
Determines if a vector is in plane with the current element
:param vector: Test vector
:param normal: Normal of element
:return:
"""
checkdot = np.dot(normal, vector)
err = 1e-9
if -err < checkdot < err:
return True
else:
... | 76,180 |
def parse_temp_data(json_graph):
"""Parse the temp data"""
temp_list = list(filter(lambda x: '100kHz' in x['label'], json_graph['graph_kind_1008']))
if len(temp_list) == 0:
return None
return clean_data(temp_list[0]['data']) | 76,181 |
def test_xdawn_covariances():
"""Test fit XdawnCovariances"""
x = np.random.randn(10, 3, 100)
labels = np.array([0, 1]).repeat(5)
cov = XdawnCovariances()
cov.fit_transform(x, labels)
assert cov.get_params() == dict(nfilter=4, applyfilters=True,
classes=None, ... | 76,182 |
def brl_out(offset: int, data: List[int]) -> bytes:
"""send data to braille display
@param offset: Must be positive.
"""
d2 = len(data)+7
ret = bytearray([
STX,
ord(b'S')
])
ret.extend(offset.to_bytes(2, "big", signed=False))
ret.extend(d2.to_bytes(2, "big", signed=False))
ret.extend(data)
re... | 76,183 |
def degree_as_dm7(degree):
"""
Given a degree, return the equivalent dm7. Does not perform range validation.
Performs integer conversion of the result.
"""
return int(round(_DM7_PER_DEGREE * degree)) | 76,184 |
def duration(duration):
"""Filter that converts a duration in seconds to something like 01:54:01
"""
if duration is None:
return ''
duration = int(duration)
seconds = duration % 60
minutes = (duration // 60) % 60
hours = (duration // 60) // 60
s = '%02d' % (seconds)
m = '%0... | 76,185 |
def test_log_dtypes(dtypes, capsys, test_df):
"""Test logging of dtypes can be switched on and off"""
@log_step(dtypes=dtypes)
def do_nothing(df, *args, **kwargs):
return df
test_df.pipe(do_nothing)
captured = capsys.readouterr()
assert ("dtypes=" in captured.out) == dtypes
if d... | 76,186 |
def guarda_objeto(archivo, objeto):
"""
Guarda un objeto de python en el archivo "archivo". Si el archivo existe, sera reemplazado sin
preguntas, al puro estilo mafioso.
Parámetros
----------
archivo: string con el nombre de un archivo (aunque no exista)
objeto: Un objeto de python par... | 76,187 |
def timer():
""" A simple timing function for routines """
try:
start = timer_func()
yield
except Exception as e:
print(e)
raise
finally:
end = timer_func()
print('Time spent=>', 1000.0 * (end - start), 'ms.') | 76,188 |
def lookup_embedding_func(
id_tensors, max_ids, embedding_dim,
):
"""
Args:
id_layers: dict, the key is a string and
the value is tf.keras.Input.
standardized_tensor:
input_tensors: dict, the key is a string and the value
is a tensor outputed by the transform ... | 76,189 |
def zbx_add_autoregistration(url, authid, templates=None):
"""
Creates a autoregistation action which adds incoming hosts and
links them to the specified templates.
:param url: URL to zabbix-server api
:param authid: valid auth-token
:param templates: to be added templates
"""
if templa... | 76,190 |
def upgrade(ctx, yes=False):
"""Update helm deployment
"""
raise NotImplementedError("Not implemented yet for helm") | 76,191 |
def test_load_pars_from_file(geometry) :
""" Test default image
"""
geometry.set_print_bits(32+64)
geometry.load_pars_from_file('./test.txt')
geometry.print_list_of_geos() | 76,192 |
def test_failure(database):
""" Tests that SF 133 amount sum for line 2004 does not match the calculation from Appropriation based on
the fields below for the specified fiscal year and period and TAS/DEFC combination.
"""
tas = "".join([_TAS, "_failure"])
sf = SF133(line=2004, tas=tas, period=1,... | 76,193 |
def diff(ctx):
"""Show stack resource drifts."""
assert isinstance(ctx.obj, ClickContext)
options = DriftDiffOptions(
)
command = DriftDiffCommand(
pretty_printer=ctx.obj.ppt,
options=options
)
ctx.obj.runner.run(command) | 76,194 |
def log_data(
key, # type: str
value=None, # type: Union[pd.DataFrame, spark.DataFrame, PostgresTable, SnowflakeTable]
path=None, # type: Optional[str]
operation_type=DbndTargetOperationType.read, # type: DbndTargetOperationType
with_preview=None, # type: Optional[bool]
with_size=None, # t... | 76,195 |
def test_set_entry_show_locked_buttons():
"""Given an Encyclopaedia with 10 unlocked entries and 5 locked entries,
And show_locked_buttons is true,
When I set the 10th unlocked entry to be the active entry,
Then the entry should be marked as viewed,
And the entry should be the active entry,
And ... | 76,196 |
def today(event):
""" show objects logged for today. """
if not event._parsed.rest:
event.reply("today <key>")
return
event._parsed.start = to_day(day())
event._parsed.end = time.time()
nr = 1
for obj in storage.selected(event):
event.display(obj, event._parsed.args, str(... | 76,197 |
def name(function):
"""
Retrieve a pretty name for the function
:param function: function to get name from
:return: pretty name
"""
if isinstance(function, types.FunctionType):
return function.__name__
else:
return str(function) | 76,198 |
def build_qso_catalog_from_healpix(redux='/global/cfs/cdirs/desi/spectro/redux/', release='fuji', survey='sv3', program='dark', dir_output='', npool=20, keep_qso_targets=True, keep_all=False):
"""
Build the QSO catalog from the healpix directory.
Warning: no retro compatibility for release <= everest (extn... | 76,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.