content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def map_header(values):
"""
Map the values generated with the hypothesis-ros header strategy to a rospy header type.
"""
if not isinstance(values, _Header):
raise TypeError('Wrong type. Use appropriate hypothesis-ros type.')
ros_header = Header()
ros_header.seq = values.seq
ros_heade... | 13c4ae25b0a00b6cbb3dda7b9540e0a7a30c073d | 3,604,420 |
def markov_order_tests(a, max_order=5, text_len=10000, verbose=False):
"""Tests of the Markov order inferrer using Markov chains of diff. orders.
"""
result = []
max_estimated_order = max_order + 2
for real_order in range(max_order):
print "Actual Markov order:", real_order
s = rando... | 33aa4eaf44eb182db843003c2596fcef238ec8b3 | 3,604,421 |
def getCurKlines(quote_ctx, stockCode, ktype, num):
""" 得到实时K线 """
# 订阅股票的各种K线种类
sub_type_list = ["K_1M", "K_5M", "K_15M", "K_30M", "K_60M", "K_DAY", "K_WEEK", "K_MON"]
for sub_type in sub_type_list:
ret_status, ret_data = quote_ctx.subscribe(stockCode, sub_type)
if ret_status != RET_OK:... | 11a1e548231d7653530cf6cc5501fda87bbe4570 | 3,604,422 |
def shell_wrap_command(command):
"""wraps the given command in a shell invocation.
default shell is /bin/bash (like Fabric)
no support for configurable shell at present"""
# '-l' is 'login' shell
# '-c' is 'run command'
shell_prefix = "/bin/bash -l -c"
escaped_command = _shell_escape(comma... | 4bf2a1bd553f9a1ff474c4d7894a3d32669c25a2 | 3,604,423 |
import time
def submit_onboarding():
"""
Parse onboarding as if it were a request sent from the
active agent, rather than coming as a request from the router.
"""
router_incoming_timestamp = time.time()
data = request.get_json()
provider_data = data["provider_data"]
agent_id = provider... | ee44b7b158402737ac39a19087ceffc252428da9 | 3,604,424 |
def spatial_overlap_conv_3x3_stride_1_dilate_2(p):
"""
This method computes the spatial overlap of dilated 3x3 convolutional layer with stride 1 and dialation rate of 2 in terms
of its input feature map's spatial overal value (p).
"""
denominator = 9 - 24 * max(p - 0.5, 0)
if p < 0.5:
r... | 91a6bd178e7dcad6e21ad7fa58df28aaf1ad279b | 3,604,425 |
def temporal_autocorrelation_multivariate(
x, d=0, mask=None, window="gaussian", window_radius=np.inf
):
"""
For a :math:`q`-variate time series
:math:`\mathbf{x}_1,\mathbf{x}_2,\dots,\mathbf{x}_n`, compute the lag-l
correlation matrices :math:`\mathbf{\Gamma}_l`, where
:math:`\Gamma_{l,i,j}=\ga... | 6f62025e2ea12ad52e0e8b60f3be6ee006dc0f6f | 3,604,426 |
def normalize_medical_kind(shape, properties, fid, zoom):
"""
Many medical practices, such as doctors and dentists, have a speciality,
which is indicated through the `healthcare:speciality` tag. This is a
semi-colon delimited list, so we expand it to an actual list.
"""
kind = properties.get('k... | dbf75799624cbe119c4c3a74c8814d0a979d828e | 3,604,427 |
def _get_tws(sel_cim_data):
"""Return terrestrial water storage."""
return sel_cim_data.TWS_tavg | 2b8405a245d39466ef2b47463d88518cc3b5bedf | 3,604,428 |
import warnings
def eq_wefli(wair,entr=None,wetf=None,wliq=None,wice=None,airf=None,
temp=None,pres=None,dhum=None,dliq=None,chkvals=False,
chktol=_CHKTOL,airf0=None,temp0=None,pres0=None,dhum0=None,
dliq0=None,chkbnd=False,mathargs=None):
"""Get equilibrium values at WEF or WLI.
Get the valu... | c005f3297c1609d6695cf01e9ecdc662a7ef0368 | 3,604,430 |
def get_project(connection, name, error_msg=None, throw_error=True,
whitelist=[('ERR001', 500), ('ERR014', 403)]):
"""Get a specific project that the authenticated user has access to.
Args:
connection: MicroStrategy REST API connection object
name (string): MicroStrategy project... | 0b7ff2c9ca1debe15bcc11a4f4c246c1ffee9f6f | 3,604,431 |
import torch
def load_graph(pt_file_path="./sample_graph.pt"):
"""
Parameters
----------
pt_file_path : file path
Returns
-------
graph : torch_geometric.data.Data
- data.n_node: number of nodes
- data.n_node_type: number of node types == (1 or 2)
- data.n_edge: nu... | a45304199c92527e4b3e48430c8ac0f9f59a74d5 | 3,604,432 |
def _is_number(data):
"""
Test whether input is numeric array rather than datetime or strings.
"""
return len(data) and np.issubdtype(_to_array(data).dtype, np.number) | 9cf05f4cb0e1fc64841f6fbeffa9834b11bc74fb | 3,604,433 |
def duffing(x, u, dt=0.05, delta=0.2):
"""Duffing's oscillator"""
dxdt = (x[1], x[0] - delta*x[1] - x[0]**3 + u)
return x[0] + dt*dxdt[0], x[1] + dt*dxdt[1] | ef193499ce213a1848a2482fdb13c53227e464d0 | 3,604,434 |
def yearly_aggregator(date: pd.Timestamp, end_of_year: pd.Timestamp):
"""Округляет дату вверх до месяца и числа конца года
Parameters
----------
date
Дата, для которой необходимо рассчитать годовую агрегацию
end_of_year
Пример даты окончания года - ее месяц и число используются для ... | 829363ef21aee394e6ed29db11f8af508bfcda1b | 3,604,435 |
from typing import Optional
def encode(hrp: str, witver: int, witprog: bytes) -> Optional[str]:
"""Encode a segwit address."""
spec = Encoding.BECH32 if witver == 0 else Encoding.BECH32M
ret = bech32_encode(hrp, [witver] + convertbits(witprog, 8, 5), spec)
if decode(hrp, ret) == (None, None):
... | 039d403d481ae9738146779832d8b02a9a587be1 | 3,604,436 |
def flac_read_s32(data: bytes) -> DecodedSoundFile:
"""Reads and decodes the whole flac audio data. Resulting sample format is 32 bits signed integer."""
with ffi.new("unsigned int *") as channels, \
ffi.new("unsigned int *") as sample_rate, \
ffi.new("drflac_uint64 *") as num_frames:
me... | f61029972b441e7c8a47d7ddb4aecbab78bbdbe9 | 3,604,437 |
def isEmptyIter(it):
"""Return True iff the iterator is empty or exhausted"""
return next(it, _nothing) is _nothing | 468c6825d77ebb47b05487e16dd3c9afc8beee6f | 3,604,438 |
def encode(lonlat, length=12):
"""Encode a (lon,lat) pair to a GeoHash."""
assert len(lonlat) == 2, "Invalid lon/lat: %s"%lonlat
# Half the length for each component.
length //= 2
lon = _float_to_bits(lonlat[0], lower=-180.0, upper=180.0, length=length*5)
lat = _float_to_bits(lonlat[1], lower=-90.0, upper=9... | 9ae3ce1cbac1c3c77726a565e211f5f3cc0521a9 | 3,604,439 |
def parse(data, template, prefix=''):
""" Parse json """
if isinstance(data, dict):
data = data.items()
elif isinstance(data, list):
data = enumerate(data)
else:
return data
for name, value in data:
name = (str(prefix) + '_' + str(name)).strip('_')
if isinstan... | 02e395af23c6eea2bbb9a5615501cd996af2732e | 3,604,440 |
def brownian_trajectories_generator(n_part=5,
n_times=100,
p_disapear=0,
sigma=1.,
init_dispersion=10.,
seed=None):
"""Build and return ... | 30ac33b403393da4f69261f3805c27295dcbcf76 | 3,604,441 |
def rpn_class_loss_graph(rpn_match, rpn_class_logits):
"""RPN anchor classifier loss.
rpn_match: [batch, anchors, 1]. Anchor match type. 1=positive,
-1=negative, 0=neutral anchor.
rpn_class_logits: [batch, anchors, 2]. RPN classifier logits for BG/FG.
"""
# Squeeze last dim to simpli... | 1c0b04381abeacecfc72c1475d8731d132660ce9 | 3,604,442 |
def merge_arrays(*lsts: list):
"""Merges all arrays into one flat list.
Examples:
>>> lst_abc = ['a','b','c']\n
>>> lst_123 = [1,2,3]\n
>>> lst_names = ['John','Alice','Bob']\n
>>> merge_arrays(lst_abc,lst_123,lst_names)\n
['a', 'b', 'c', 1, 2, 3, 'John', 'Alice', 'Bob']... | f2dd78a9e2d31347d72e1e904c0f2c6e30b37431 | 3,604,443 |
def rotTransMatrix(axis, s, c, t):
"""
build a rotate * translate matrix - MUCH faster for derivatives
since we know there are a ton of zeros and can act accordingly
:param axis: x y or z as a character
:param s: sin of theta
:param c: cos of theta
:param t: translation (a 3 tuple)
:retu... | bf9bdbcff086ef7be52a3742316d4883d3bf70a3 | 3,604,444 |
import hashlib
def sha256(msg):
"""Return the sha256 hash of the passed data. Non binary data is automatically converted
>>> hexlify(sha256("e hat eye pie plus one is O"))
b'c5b94099f454a3807377724eb99a33fbe9cb5813006cadc03e862a89d410eaf0'
"""
msg = anything2bytes(msg)
return hashlib.new('sh... | 49ffa2bd96eea5e98fdd030469e2a08a599a9357 | 3,604,445 |
def fast_pow(x, y):
"""Fast power x^y for x > 0. Reproduces `FastPow()` in the C library.
An approximation of x^y with about 0.5% relative error.
Limitations:
- Assumes x is positive and finite.
- Assumes 1e-37 <= |x^y| <= 1e37, i.e. that the exact result would be
neither very large nor very close to... | 282a88d510de89bc507e025812832365c0959699 | 3,604,446 |
def get_file_to_save(win, oms='', extension='', start=''):
"""toon een dialoog waarmee een file geopend kan worden om te schrijven
"""
what = shared.get_open_title(win, 'C_SELFIL', oms)
fname, ok = qtw.QFileDialog.getSaveFileName(win, what, filter=extension)
return fname | 57899b4c8d5c40f401178cd3d72c9bdb86522a9f | 3,604,447 |
def check_requirements(
filename=DEFAULT_FILE,
errors_only=False, spec_only=False, latest=False, location=False):
""" Check requirements against installed versions and print status lines
for all of them.
"""
reqs = Requirementz.from_file(filename=filename)
if len(reqs) == 0:
... | e7c3845d7978a3609918508b32cb9ac3b87f8874 | 3,604,448 |
def _sample_mean(values):
"""Mean over sample indices. In this module this is always [0]."""
return math_ops.reduce_mean(values, reduction_indices=[0]) | 2c42ebd2c6d3b97625436b9bbf2766825d804fbd | 3,604,449 |
import gzip
import bz2
def open_zipped(infile, mode='r'):
"""Open a regular, gzipped, or bz2 file.
If infile is a file handle or text device, it is returned without
changes.
Returns
-------
text mode file handle.
"""
mode = mode[0] + 't'
if hasattr(infile, 'write'):
ret... | 345ad46c2dc113961d74d29c44f88a6be7b74526 | 3,604,450 |
def get_Theta_ex_a_Ave(Theta_ex_d_t):
"""年平均外気温度[℃] (1)
Args:
Theta_ex_d_t(ndarray): 外気絶対温度[K]
Returns:
ndarray: 年平均外気温度[℃]
"""
return np.sum(Theta_ex_d_t) / 8760 | 125a12ed4586e9df90fdc23e9152b0a2f9a38938 | 3,604,451 |
def delete_entry(request, entry_id):
"""
Give the user the ability to delete a log entry, with a confirmation
beforehand. If this method is invoked via a GET request, a form asking
for a confirmation of intent will be presented to the user. If this method
is invoked via a POST request, the entry wi... | 34e423972b3965f9642e3ae23aefcc4ac96812f0 | 3,604,452 |
def build_full_multi_view_cnn_forward_pass_with_features(
model,
H,
W,
views,
depth_planes,
padding,
depth_range_min,
depth_range_max,
sampling_scheme
):
"""
Arguments
---------
model: the Keras model to be used for feature extraction
H: int, the height of... | 79c81aef4b0dcf4255b1a064fcc0e7bd2a225906 | 3,604,453 |
def conv3x3(in_channels: int, out_channels: int, stride: int = 1, padding: int = 1) -> nn.Conv2d:
"""3x3 convolution for resnet block."""
return nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=padding, bias=False) | d355bdec243787a34fa801eff9051cbb6645b796 | 3,604,454 |
from typing import Callable
def nlsvm_solve(X: np.ndarray, y: np.ndarray, classes: tuple[str, str], cost: float, kernel: Callable) -> Callable:
"""
训练一个SVM二分类器
:param X: 训练数据的特征矩阵,n行,dim列,dim为数据维数,每一行为一个训练样本,每一列为一个特征
:param y: 训练数据的标签矩阵,n行,1列,取值为-1或1
:param classes: 长度为2的字符串元组,表示当前用于训练的二分类
:pa... | cbb8fd656214508c7d83901508a06402a1b52c9a | 3,604,456 |
import logging
def hset_object(client, field, key, src_data):
"""Add value from configured redis under specified key of certain hashtable
:param client: redis client object
:param field: string
:param key: string
:param src_data: bytestream, int, string
:return: True if src_data was added to ... | cd7859b683cd18a6a4e314df22245991c6ebc36f | 3,604,459 |
def matrix_median_blur_fcn(matrix,size):
"""Function to apply median blur to the matrix that represents sarcomeres as voxels."""
matrix_blur = median_filter(matrix_blur, size=size)
return matrix_blur | b8e306d2af3007e07939a793e1a8e1f767e43c0f | 3,604,460 |
def get_pystache_parsed(mustache_file):
"""Return a ParsedTemplate instance based on the contents of
$mustache_file."""
with open(mustache_file, "r") as file_:
parsed = pystache.parse(file_.read())
return parsed | eb4f57bf8ffce628cf10470d61a6b0b850ff5621 | 3,604,461 |
def lngamma(x):
"""
lngamma(x) -> number
Return logarithm of gamma(x).
"""
res, x = _init_check_mpfr(x)
gmp.mpfr_lngamma(res, x, gmp.MPFR_RNDN)
return mpfr._from_c_mpfr(res) | e002190cbbd5ec9b31261eb2bf3bbd3d3cb2f740 | 3,604,462 |
def bytes2hex(byte_string: bytes) -> str:
"""Return a hex string representation of encoded bytes."""
s = b2a_hex(byte_string).decode()
return " ".join(s[i:i + 2] for i in range(0, len(s), 2)) | 35f1836f442234040a7fa47c8ee432bb7e429387 | 3,604,463 |
def sample_encoding(X, interaction_times, batch_size, k,
sequence_length,
first_indices,
second_indices,
gate_type='sum',
norm_type='l2'):
"""
input X: embedding inputs or max-pooling outputs
output: ... | 036e695355fcb1f51934298c34c7e9f2f790223b | 3,604,464 |
def is_method_request(topic: str, method_name: str = None) -> bool:
"""
Determine if a topic string is for a method request.
:param str topic: The topic to test
:returns: True if the topic is for a method request.
"""
if constants.EDGEHUB_TOPIC_RULES:
is_method = topic.startswith("$iot... | 78b7948e7a50dd0ec0d96884599288c30e5a89b7 | 3,604,465 |
def phone_setup_iwlan(log,
ad,
is_airplane_mode,
wfc_mode,
wifi_ssid=None,
wifi_pwd=None):
"""Phone setup function for epdg call test.
Set WFC mode according to wfc_mode.
Set airplane mode according... | 60f87427bf1d51185d1e1fe6339b083c445b6b37 | 3,604,466 |
from typing import OrderedDict
def join_values(x,column_types):
"""This function filters out the most likely sector and subsector codes assigned to a building
In an OSM dataset, based on a mapping of building attributes to macroeconomic sectors
Based on our mapping a building might be either ass... | 3767f6f8242def2e69cbd5b5c5311c923c2a9539 | 3,604,467 |
def is_within_range(num, lower_bound: int, upper_bound: int) -> bool:
"""
check if a number is within a range bounded by upper and lower bound
:param num: target number needs to be checked against
:param lower_bound: exclusive lower bound
:param upper_bound: exclusive upper bound
:return: True ... | 325f4084a88254ec2f29dd28749b8709de394078 | 3,604,468 |
from typing import Optional
from typing import Tuple
def _shape_param_to_id_str(shape_param: Optional[Tuple[Optional[int], ...]]) -> str:
"""Convert kernel input shape parameter used in `test_call.py` and `conftest.py`
into a human readable representation which is used in the pytest parameter id."""
if s... | ba73efa0693217a32ba42754af36204631c4200d | 3,604,469 |
def structural_holes(graph,includeOutLinks=True,includeInLinks=False,wholeNetwork=True):
"""
Calculate each node's contraint / structural holes value, as described by Ronal Burt
Parameters
----------
G : graph
a networkx Graph or DiGraph
includeInLinks : whether each ego network should include nodes which... | 89c469376475fd4ed9305819fc646b7181765b9d | 3,604,470 |
from typing import Optional
from typing import Sequence
def get_service_principals(application_ids: Optional[Sequence[str]] = None,
display_names: Optional[Sequence[str]] = None,
ignore_missing: Optional[bool] = None,
object_ids: Optiona... | 592aff76fef710e44d04dacf52f263b62e943773 | 3,604,471 |
import requests
from io import StringIO
import pandas
def send_request(**kwargs):
"""Return a data frame from a web service request to cBio portal.
Sends a web service requrest to the cBio portal with arguments given in
the dictionary data and returns a Pandas data frame on success.
More information... | 4526c46960c8ea3f30727a0e0e998c9d914e6021 | 3,604,472 |
from typing import Dict
from typing import List
def map_account_for_insert(file_id, gab_id, account_json) -> Dict[str, List[Dict]]:
"""
Takes JSON object for the gab user account, and the Gab ID of the Gab this user
account information was fetched with, and returns an SQL insert statement, ready
to be... | 7ff23a991faa3b1a60aaceba1371630e044a10b5 | 3,604,473 |
import time
def load_dataframe(db, code, filename=None):
"""
打印/加载* DataFrame by code, or save into filename
"""
begin_time = time.time()
sql = "select date, open, close, high, low, volume, turnover from sk_stock_daily_data where code='%s'" % code
with db.cursor(cursorclass=MySQLdb.cursors.Dic... | 56bd3c52dc432ef9217366acd78ba1c259671974 | 3,604,474 |
def restore_model(model_path):
"""
直接指定模型
:param model_path:
:return:
"""
print("恢复模型:",model_path)
# tf.reset_default_graph()
params={}
g = tf.get_default_graph()
with g.as_default():
#从pb模型直接恢复
sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=Tru... | 904fba4950b98198e42f93b24aa232c44260fe62 | 3,604,475 |
def graph_to_str(graph):
"""
Convert a NetworkX graph to a string. This one represents its adjacency matrix.
:graph: The NetworkX graph.
:return: The string of the graph.
"""
adjacency_matrix = np.array(to_adjacency_matrix(graph))
graph_row_str = []
for row in adjacency_matrix:
graph_row_str.append(''.join... | 1b33e240b3cc4b52f41911084d15bbdb005b5a1d | 3,604,476 |
def get_travel_time(catalog):
"""Find the time between origin and propagation"""
v_mean = FLAGS.v_mean
coordinates = [(lat, lon, depth)
for (lat, lon, depth) in zip(catalog.latitude,
catalog.longitude,
... | a14bf2461eac8dd688c27c55745f4261360b2d70 | 3,604,477 |
import pandas
def estimate_test_percentages_for_regions(df: pandas.DataFrame) -> pandas.Series:
""" Calculates the fraction of tests per region.
Uses the 7 days up to the last day for which daily new_test data is available for all regions.
WARNING: If any region has a gap _before_ the last day for which... | a422f4621cc76d8bb0819ab6a1f12996da962a46 | 3,604,478 |
def make_blueprint(db_connection_string=None):
"""Create blueprint.
"""
controllers = Controllers(db_connection_string)
# Create instance
blueprint = Blueprint('datarecords', 'datarecords')
# Controller Proxies
@check_permission([Permissions.datarecordListAll, Permissions.datarecordLi... | 71b29d2691401617942c6e91192f9cdb19ca79b4 | 3,604,479 |
def get_circulate_supply(endpoint=_default_endpoint, timeout=_default_timeout) -> int:
"""
Get current block number
Parameters
----------
endpoint: :obj:`str`, optional
Endpoint to send request to
timeout: :obj:`int`, optional
Timeout in seconds
Returns
-------
int
... | ad61a3ddc625f70fa0a956ba06587b772bef03a9 | 3,604,480 |
def get_atom_ids_sorted_type(species):
"""
Get a list of atom ids sorted by increasing atomic weight, useful for when
a molecular graph depends on the order
of atoms in what will be considered bonded
Arguments:
species (autode.species.Species):
Returns:
(list(int)):
"""
... | f825f9734d61b4850e907f949b4db4a403e55fff | 3,604,481 |
def get_install_soft_current():
"""
for line chart and radar
:return:
"""
soft_install_list = install_softgame_current("soft")
if soft_install_list != "no data":
return jsonify({"softtop5": soft_install_list[0: 5],
"softtop10": soft_install_list[5: 10]})
else:... | b8b47e19c6ba31d22a128b4496462c5492022e51 | 3,604,482 |
def Shuffle(pcoll):
"""Shuffles a PCollection. Collection should not contain duplicates."""
return (pcoll
| 'PairWithHash' >> beam.Map(lambda x: (hash(x), x))
| 'GroupByHash' >> beam.GroupByKey()
| 'DropHash' >> beam.FlatMap(
lambda hash_and_values: hash_and_values[1])) | 18750487675046d9330b1c54dd5ff4e27e4552d5 | 3,604,483 |
def init_rand(N, r, rng):
"""
Initialize N robots with radii r uniformly at random in a box centered at
(0,0) such that the robots occupy roughly 2% of the space.
"""
config = np.zeros((N, 3))
arena_side_len = sqrt(N * np.pi * r**2 / 0.02)
for i in range(N):
while True:
... | 4eb5fe10e68dd053bb1265203543e63a08d38016 | 3,604,484 |
def fit_predict(X, y, index):
"""Train and make in-sample prediction."""
clf = LinearRegression().fit(X, y)
daily = clf.predict(X)
daily_predicted = pd.Series(daily, index=index, name="predicted")
return [daily_predicted, clf] | ff016024e26f10acdda3145926b9c20d1bddf4fa | 3,604,485 |
async def job_edit(
job_id: int,
job: CreateAndUpdateJob,
db=Depends(get_db),
current_user=Depends(get_current_active_superuser),
):
"""
Update existing job
"""
return edit_job(db, job_id, job) | 2898c88aa2a00ff0d6c89aa2b680022b888baf06 | 3,604,486 |
def extract_EC_chunks(cq):
"""
Find EC chunks and replace their occurences with EC tags
"""
def _get_EC_span_reject_wh_starters(chunk):
"""
By default, SpaCy treats question words (wh- pronouns starting questions: where, what,...)
as nouns, so often if questions star... | 331ad919e436a46c89321c75cd975fcaf6eff7ac | 3,604,487 |
from scipy.spatial.distance import euclidean, cdist
def evaluate_clustering_DB(X, idx):
"""
Davies-Bouldin index a coefficient to evaluate the goodness of a
clustering solution. The more it approaches to zero, the better
the clustering solution is. -- Tested OK with comparison Matlab
"""
... | 9322139094850b4a529dd9b0f4b693c057fc70ca | 3,604,488 |
import json
def ratelimit():
"""untrusted id found"""
return json.dumps({
'success': False,
'error': 'signal api rate limit reached'
}), 413, {'ContentType': 'application/json'} | b8a2e917acdbe26850e950e62dadf419d64ecc02 | 3,604,490 |
def get_lr(optimizer):
"""Used for convenience when printing"""
for param_group in optimizer.param_groups:
return param_group['lr'] | c73d08f3cbac372b02c3ccce7e40526d7e686e63 | 3,604,491 |
def MobileNetV1_x0_5(pretrained=False, use_ssld=False, **kwargs):
"""
MobileNetV1_x0_5
Args:
pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise.
If str, means the path of the pretrained model.
use_ssld: bool=False. Whether using distill... | 851a78f5ef122cb8243cd79e0802a1dbb6690c8d | 3,604,492 |
def motion_T(input_line, cur, count):
"""Go to `count`'th occurence of char to the left and return position.
The position returned is the position of the character to the right of
char.
See Also:
`motion_base()`.
"""
return start_catching_keys(1, "cb_motion_T", input_line, cur, count) | cbf7d5535bd510e1c20d2a68d5e9aab8ae04181d | 3,604,493 |
from typing import Tuple
from typing import Dict
from typing import Any
import copy
import uuid
def create_occluder(wall_material: str, pole_material: str,
x_position: float, x_scale: float, sideways: bool = False) \
-> Tuple[Dict[str, Any]]:
"""Create an occluder pair of objects: (wal... | a79811340ab2c4b8b7ad1c464b6dac1ceee67311 | 3,604,495 |
from typing import List
import json
def build_workflow_blocks(
incident: Incident, workflows: List[Workflow], selected_workflow: Workflow = None
):
"""Builds all blocks required to run a workflow."""
modal_template = {
"type": "modal",
"title": {"type": "plain_text", "text": "Run workflow"... | cb5e334f699e3b02efebafeb59658a60cee0c819 | 3,604,496 |
def cmp_by_level_2_tag_code(left, right):
"""
tag按照第二列标签进行排序
:param left: tag1
:param right: tag2
:return:-1,1,0
"""
left = left["tag_code"]
right = right["tag_code"]
if left == "other":
return 1
elif right == "other":
return -1
else:
return 0 | 6ee210c54967dcad7673d4c130ecc0e5bc907bc5 | 3,604,497 |
def lcs(string_a, string_b):
"""
Calculate the length of the longest common subsequence of characters
between two strings.
The time complexity of this implementation is dominated by the two nested
loops, let the length of string_a and string_b is 'n' and 'm' respectively.
This would lead to ... | dc1183092928e1cb9bce5926207fbceb85b79e2e | 3,604,498 |
def getbox(xcenter, ycenter, size=500):
"""
A function to compute coordinates of a bounding box.
Arguments:
- xcenter: int, x position of the center of the box.
- ycenter: int, y position of the center of the box.
- size: int, size of the side of the box.
Returns:
- box... | 6e8030f113a13775365fcd715be46690849154f3 | 3,604,499 |
def _decode_and_center_crop(image_bytes, image_size):
"""Crops to center of image with padding then scales image_size."""
shape = tf.io.extract_jpeg_shape(image_bytes)
image_height = shape[0]
image_width = shape[1]
padded_center_crop_size = tf.cast(
((image_size / (image_size + CROP_PADDING)) *
tf.c... | e5bc7bf88912b4110d9de7fddcdfec6d1782fb40 | 3,604,500 |
from typing import List
def get_entity_attributes(entity: dict) -> List[str]:
"""Get a list with the attributes of the entity.
Args:
entity(:obj:`dict`): entity.
Returns:
list: containing the attributes.
"""
keys = entity.keys()
not_attributes = ["id", "type"]
attributes ... | a5482a679ff5060d2deb26d7af6f4dc7fe394bf5 | 3,604,501 |
from typing import Optional
def _shrink2(
xx: np.ndarray,
resampling: str = "nearest",
nodata: Optional[NodataType] = None,
axis: int = 0,
):
"""
:param xx: Image to shrink
:param resampling: Resampling strategy to use
:param nodata: nodata value for missing value fill
:param axis:... | 34e68be0fe63bf402acf78a696c5fec45f99185a | 3,604,502 |
def fahrenheitToRankie(fahrenheit:float, ndigits = 2)->float:
"""
Convert a given value from Fahrenheit to Rankine and round it to 2 decimal places.
Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit
Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale
"""
return round(flo... | feea06edfbc800fbb4da6a3a128b2a89f07966ed | 3,604,504 |
from typing import Callable
def _call_method_from_namespace(obj: Callable, method_name: str, namespace: Namespace):
"""Call the method, retrieved from obj, with the correct arguments via
the namespace
Args:
obj: any kind of object
method_name: method to be called
namespace: an arg... | 1810e48919eea30a50bb7406123e1a90c6a51233 | 3,604,505 |
def period2omega(period):
"""
Convert Period (days) to Omega (OmegaSun)
"""
period = period << u.d
OmegaSun = u.def_unit(r'\Omega_\odot', 2.6*1e-6*u.Hz)
return ((2.*np.pi/(period.to(u.s))) << OmegaSun).value | f029a57f6d2cc554423baf3561bf554bbe7278ef | 3,604,506 |
def _build_notehead_stem_pairs(noteheads, stems, flags8=None, flags16=None):
"""
Combines list of noteheads and a list of stems into a list of
canvas items. Handles flipping when stem points down.
"""
items = []
for i, h in enumerate(noteheads):
if len(stems[i].inlinks) > 1:
... | b31f193f0c65a264054c291f85b8e67b145c6903 | 3,604,507 |
def connect(H, G, Gout=None, Hin=None):
"""
Connect outputs Gout of G to inputs Hin of H. The outputs and inputs of
the connected system are arranged as follows:
- remaining outputs of G get lower, the outputs of H the higher indices
- inputs of G get the lower, remaining inputs of H the hi... | c5a6bbf86ec9da5daf006a5e1dc3de1f8140e45f | 3,604,508 |
def get_summary_link(layout, reduced_chain_link_dict, name):
"""
<Purpose>
Merges the materials of the first step (as mentioned in the layout)
and the products of the last step and returns a new link.
This link reports the materials and products and summarizes the
overall software supply chain.
... | 2cc688bedd915cc60d20aae4c58addf392409dc4 | 3,604,509 |
import fsspec
from typing import Mapping
def get_prefix_time_mapping(
fs: fsspec.AbstractFileSystem, url: str
) -> Mapping[str, cftime.DatetimeJulian]:
"""Return a dictionary mapping restart file prefixes to times
Args:
fs: fsspec filesystem object
url: url to the run-directory
Return... | 1ceb0946d62f3967664fb72498e07b09df56ca79 | 3,604,510 |
import uuid
def generate_event_uuid():
""" Generate the identifier of the event (FaaS)
Returns:
str: the event identifier
"""
return str(uuid.uuid4()).replace('-', '') | e982f3699b9a0ee78676a74ed31095534a4ca24b | 3,604,511 |
def X(qubit: QubitDesignator) -> Gate:
"""Produces the X ("NOT") gate::
X = [[0, 1],
[1, 0]]
This gate is a single qubit X-gate.
:param qubit: The qubit apply the gate to.
:returns: A Gate object.
"""
return Gate(name="X", params=[], qubits=[unpack_qubit(qubit)]) | 3765599becc4403971389539b920a17e1863885e | 3,604,513 |
def factorial(x):
"""Return the factorial of a given number."""
if x == 1:
return 1
else:
return factorial(x-1) * x | a1c3adacf122c1bec57bbbfd246f07bf627febcd | 3,604,514 |
def R313(a,b,c, degrees=False):
"""Returns a rotation matrix based on: Z(c)*X(b)*Z(a)"""
if degrees:
a *= deg2rad
b *= deg2rad
c *= deg2rad
s3 = np.sin(c); c3 = np.cos(c)
s2 = np.sin(b); c2 = np.cos(b)
s1 = np.sin(a); c1 = np.cos(a)
# return np.array(
# [
# ... | 9c8f1958c82c1bb02f75ce2647d47008deeb501f | 3,604,515 |
def roi_size(roi):
"""
returns number of cols and rows
"""
cols = roi[1][0] - roi[0][0] + 1
rows = roi[1][1] - roi[0][1] + 1
return cols, rows | caa9213399d9672aa9f23380c7f79db1b42cfa12 | 3,604,516 |
import re
def _remove_decorators(source_code: str, decorator_name: str = "to_document") -> str:
"""Function to remove all 'to_document' decorator
Parameters
----------
source_code : str
The source code
OPTIONAL[decorator_name] : str
The name of decorator to remove
Default: "to_document"
Returns
-----... | b8b59e18784a5d4c6c3fa0146c72fc68dd7b3343 | 3,604,517 |
def integration_checksums(
flight,
configuration,
sql = None,
engine = None,
df = None,
entity_set_names = None,
check_random_n_entity_sets = None
):
"""
For a given list of entity sets, checks the number of unique pk values in source data against those integrated
The list o... | 3541ac477de80f8c65224600a817436de847c198 | 3,604,518 |
import zlib
import pickle
import hashlib
def encode_data(data):
"""Turn `data` into a hash and an encoded string, suitable for use with `decode_data`."""
text = zlib.compress(pickle.dumps(data, 0)).encode('base64').replace('\n', '')
m = hashlib.md5(settings.SECRET_KEY + text).hexdigest()[:12]
return m... | 9a3b8abd04b9267b0d838ff50ba84142e7da6798 | 3,604,519 |
def _forecast_vars(steps, ma_coefs, sig_u):
"""_forecast_vars function used by VECMResults. Note that the definition
of the local variable covs is the same as in VARProcess and as such it
differs from the one in VARResults!
Parameters
----------
steps
ma_coefs
sig_u
Returns
---... | 14c838d5205fecbc4d23dcac2c9b4ab1e04e8a0e | 3,604,520 |
def jointImgTo3D(sample):
"""
Normalize sample to metric 3D
:param sample: joints in (x,y,z) with x,y in image coordinates and z in mm
:return: normalized joints in mm
"""
ret = np.zeros((3,), np.float32)
# convert to metric using f
ret[0] = (sample[0] - ux) * sample[2] / fx
ret[1] =... | ef91b87b9faf165e6d02811798034a495e8fe443 | 3,604,521 |
from pathlib import Path
def is_file_suffix(filename, suffixes, check_exist=True):
"""
is_file + check for suffix
:param filename: pathlike object
:param suffixes: tuple of possible suffixes
:param check_exist: whether to check the file's existence
:return: bool
"""
if check_exist and ... | e1e81eb0c39c991586097882c728535829acf415 | 3,604,522 |
from dask import array as da
from dask.base import tokenize
from typing import Any
from typing import Optional
from typing import Tuple
def to_rgba(
ds: Any,
bands: Optional[Tuple[str, str, str]] = None,
*,
vmin: Optional[float] = None,
vmax: Optional[float] = None,
) -> xr.DataArray:
"""
... | ebcc89505cff9b6778132c0b059e5258719397be | 3,604,523 |
def exu(x, weight, bias):
"""ExU hidden unit modification."""
return tf.exp(weight) * (x - bias) | 26fa33def7b4f78b1f141ebef85f47a242977b54 | 3,604,524 |
def cachefor(name):
"""Decorator to register a function as computing the cache for a set"""
def decorator(func):
assert name not in cachefuncs
cachefuncs[name] = func
return func
return decorator | de5a8419f3406069cdd0388d164e13b588f10f17 | 3,604,525 |
def build_vector_batch(vectors, dtype):
"""
Return batch of vectors.
>>> from nutsml.datautil import shapestr
>>> vectors = [np.array([1,2,3]), np.array([2, 3, 4])]
>>> batch = build_vector_batch(vectors, 'uint8')
>>> shapestr(batch)
'2x3'
>>> batch
array([[1, 2, 3],
[2,... | 14f130cfce6eede3f2ffb0f76616c168f0af082a | 3,604,527 |
from typing import Callable
import tqdm
import time
def experiment(method: str, step_size: float, num_steps: int, num_samples: int, proposal: Callable, randomize_steps: bool) -> np.ndarray:
"""Experiment to examine the use of different integrators for sampling from the
Fitzhugh-Nagumo posterior distribution. ... | 8e5f39c8f4d5fb0e6a3a0823c32e95c8a482f304 | 3,604,528 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.