content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def executeCmd(cmd,arg):
""" the meat: how we react to the SNI-based logic and execute the underlying command """
global currentPath
global currentDirList
global currentFileList
global currentFileSizeList
global agentName
commands = initCmd(cmd)
for testedCommand, alias in commands.ite... | 22,100 |
async def text2image(
text: str,
auto_parse: bool = True,
font_size: int = 20,
color: Union[str, Tuple[int, int, int], Tuple[int, int, int, int]] = "white",
font: str = "CJGaoDeGuo.otf",
font_color: Union[str, Tuple[int, int, int]] = "black",
padding: Union[int, Tuple[int, int, int, int]] = ... | 22,101 |
def get_dosage_ann():
""" Convenience function for getting the dosage and snp annotation
"""
dos = {}
s_ann = {}
dos_path =\
("/export/home/barnarj/CCF_1000G_Aug2013_DatABEL/CCF_1000G_Aug2013_Chr"
"{0}.dose.double.ATB.RNASeq_MEQTL.txt")
SNP_ANNOT =\
("/proj/ge... | 22,102 |
def function_arguments(function_name: str, services_module: types.ModuleType) -> typing.List[str]:
"""Get function arguments for stan::services `function_name`.
This function parses a function's docstring to get argument names. This is
an inferior method to using `inspect.Signature.from_callable(function)`... | 22,103 |
def cost_n_moves(prev_cost: int, weight: int = 1) -> int:
""" 'g(n)' cost function that adds a 'weight' to each move."""
return prev_cost + weight | 22,104 |
def get_email_dict(txt_dir):
"""
:param txt_dir: the input directory containing all text files.
:return: a dictionary where the key is the publication ID and the value is the list of authors' email addresses.
"""
def chunk(text_file, page_limit=2000):
fin = codecs.open(text_file, encoding='u... | 22,105 |
def get_gaussian_fundamentals(s, nfreq=None):
"""
Parses harmonic and anharmonic frequencies from gaussian
log file.
Input:
s: String containing the log file output.
nfreq : number of vibrational frequencies
Returns:
If successful:
Numpy 2D array of size: nfreq x 2
1st co... | 22,106 |
def dt_diff_file_reversions():
"""
Compute diffs checking for reversions: (invert file order to simulate reverse filename progression)
>>> old_state = test_config.setup()
>>> DiffScript("crds.diff data/hst_0002.pmap data/hst_0001.pmap --check-diffs")()
(('data/hst_0002.pmap', 'data/hst_0001.pmap')... | 22,107 |
def uniform_selection_tensor(tensor_data: np.ndarray,
p: int,
n_bits: int,
per_channel: bool = False,
channel_axis: int = 1,
n_iter: int = 10,
min... | 22,108 |
def writefile_latticemap(map_, file):
"""Writes a lattice map text file.
The structure of the lattice map file is as follows::
-----------------------------------------
| <nnodes_dim> |
| <nodes_x> |
| <nodes... | 22,109 |
def _get_mock_dataset(root_dir):
"""
root_dir: directory to the mocked dataset
"""
base_dir = os.path.join(root_dir, "PennTreebank")
os.makedirs(base_dir, exist_ok=True)
seed = 1
mocked_data = defaultdict(list)
for file_name in ("ptb.train.txt", "ptb.valid.txt", "ptb.test.txt"):
... | 22,110 |
def calculate_bin_P(P, x, cal_type='pes'):
""" Calculate the virtual, binary transition function.
That is, this function is to calculate the transition function which
a state and action pair may visit the virtual state $z$
"""
n, m = x.world_shape
# P_z is defined for the n*m states $s$ and a vi... | 22,111 |
def makeYbus(baseMVA, bus, branch):
"""Builds the bus admittance matrix and branch admittance matrices.
Returns the full bus admittance matrix (i.e. for all buses) and the
matrices C{Yf} and C{Yt} which, when multiplied by a complex voltage
vector, yield the vector currents injected into each line... | 22,112 |
def list_blob(math_engine, batch_len, batch_width, list_size, channels, dtype="float32"):
"""Creates a blob with one-dimensional Height * Width * Depth elements.
Parameters
---------
math_engine : object
The math engine that works with this blob.
batch_len : int, > 0
The BatchLe... | 22,113 |
def test_len(test_row):
"""Test len method."""
assert len(test_row) == 4
empty_row = py3odb.row.Row()
assert not empty_row | 22,114 |
def downgrade_data():
"""Data migration to retrieve the ids of old sensors.
Note that downgraded ids are not guaranteed to be the same as during upgrade."""
# To support data downgrade, cascade upon updating ids
recreate_sensor_fks(recreate_with_cascade_on_update=True)
# Declare ORM table views
... | 22,115 |
def p_command_create(p):
"""
command : CREATE ident asinputformat block
| CREATE ident asinputformat string
"""
p[0] = (p.lineno(1), Create(dialect=p[3], block=p[4]), p[2]) | 22,116 |
def skip_on_pypy_because_cache_next_works_differently(func):
"""Not sure what happens there but on PyPy CacheNext doesn't work like on
CPython.
"""
return _skipif_wrapper(func, IS_PYPY,
reason='PyPy works differently with __next__ cache.') | 22,117 |
def get_life_of_brian():
"""
Get lines from test_LifeOfBrian.
"""
count = 0
monty_list = ['coconut']
try:
with open(LIFE_OF_BRIAN_SCRIPT) as f:
lines = f.readlines()
for line in lines:
count += 1
#print(line)
monty_... | 22,118 |
def ackley_func(x):
"""Ackley's objective function.
Has a global minimum at :code:`f(0,0,...,0)` with a search
domain of [-32, 32]
Parameters
----------
x : numpy.ndarray
set of inputs of shape :code:`(n_particles, dimensions)`
Returns
-------
numpy.ndarray
compute... | 22,119 |
def validate_listable_type(*atype):
"""Validate a list of atype.
@validate_listable_type(str)
def example_func(a_list):
return a_list
@validate_listable_type(int)
def example_int_func(a_list):
return a_list
"""
if len(atype) != 1:
raise ValueError("Expected... | 22,120 |
def meh(captcha):
"""Returns the sum of the digits which match the next one in the captcha
input string.
>>> meh('1122')
3
>>> meh('1111')
4
>>> meh('1234')
0
>>> meh('91212129')
9
"""
result = 0
for n in range(len(captcha)):
if captcha[n] == captcha[(n + 1) ... | 22,121 |
def check_cli(module, cli):
"""
This method checks if vRouter exists on the target node.
This method also checks for idempotency using the vrouter-bgp-show command.
If the given vRouter exists, return VROUTER_EXISTS as True else False.
If the given neighbor exists on the given vRouter, return NEIGHB... | 22,122 |
def plot_stat(ratio=0.1, num=100, stat="test MSE", method="ols", n_boot=1000, k_fold=1000, ridge_lmb=122.0, lasso_lmb=112.2):
"""
Create heatmap for given statistical indicator and sampling method
:param ratio: ratio of the dataset to be used for testing
:param num: length of dataset
:param stat: st... | 22,123 |
def is_prime(n):
""" from
https://stackoverflow.com/questions/15285534/isprime-function-for-python-language
"""
if n == 2 or n == 3: return True
if n < 2 or n%2 == 0: return False
if n < 9: return True
if n%3 == 0: return False
r = int(n**0.5)
f = 5
while f <= r:
if ... | 22,124 |
def load(file, encoding=None):
"""load(file,encoding=None) -> object
This function reads a tnetstring from a file and parses it into a
python object. The file must support the read() method, and this
function promises not to read more data than necessary.
"""
# Read the length prefix one char... | 22,125 |
def enable(configuration_file, section="ispyb"):
"""Enable access to features that are currently under development."""
global _db, _db_cc, _db_config
if _db_config:
if _db_config == configuration_file:
# This database connection is already set up.
return
logging.get... | 22,126 |
def MakeMsgCmd(cmdName,argList):
"""
Take a command name and an argList of tuples consisting of
pairs of the form (argName, argValue), and return a string
representing the corresponding dibs command.
"""
body = MakeStartTag(dibs_constants.cmdTagName,{'id':cmdName}) + '\n'
for argPair in arg... | 22,127 |
def preprocess(tweet):
"""
Substitures urls with the string URL. Removes leading and trailing whitespaces
Removes non latin characters
:param tweet:
:return:
"""
# remove URL
line = remove_url(str(tweet.strip()))
# remove non Latin characters
stripped_text = ''
for c in line:... | 22,128 |
def read_xml_file(input_file, elem):
"""Reads xml data and extracts specified elements
Parameters
----------
input_file : str
The OTA xml file
elem : str
Specified elements to be extracted
Returns
-------
list
a list of xml seat data
"""
tree = ET.parse(... | 22,129 |
def _generate_supersize_archive(supersize_input_file, make_chromium_output_path,
make_staging_path):
"""Creates a .size file for the given .apk or .minimal.apks"""
subprocess.run([_CLANG_UPDATE_PATH, '--package=objdump'], check=True)
supersize_input_path = make_chromium_output_path... | 22,130 |
def report_mean_overall(nutrients_mean):
"""Report mean overall"""
overall_carb_trend.append(nutrients_mean[0])
overall_fiber_trend.append(nutrients_mean[1])
overall_fat_trend.append(nutrients_mean[2])
overall_prot_trend.append(nutrients_mean[3]) | 22,131 |
def env(pip_packages: Optional[Union[str, List[str]]] = None):
"""A decorator that adds an environment specification to either Operator or Application.
Args:
pip_packages Optional[Union[str, List[str]]]: A string that is a path to requirements.txt file
... | 22,132 |
def test_trace_propagation(
endpoint, transport, encoding, enabled, expect_spans, expect_baggage,
http_patchers, tracer, mock_server, thrift_service,
app, http_server, base_url, http_client):
"""
Main TChannel-OpenTracing integration test, using basictracer as
implementation of OpenT... | 22,133 |
def cost_stage_grads(x, u, target, lmbda):
"""
x: (n_states, )
u: (n_controls,)
target: (n_states, )
lmbda: penalty on controls
"""
dL = jacrev(cost_stage, (0,1)) #l_x, l_u
d2L = jacfwd(dL, (0,1)) # l_xx etc
l_x, l_u = dL(x, u, target, lmbda)
d2Ldx, d2Ldu = d2L(x, u, t... | 22,134 |
def slope_field(f: Function2d, range: list = None,
xlim: list = None, ylim: list = None,
normalize: bool = True, plot_type: str = 'quiver',
density: int = 20, color: bool = True,
show: bool = True, cmap: str = 'viridis'):
"""
Slope Field
======... | 22,135 |
def create_rotation_matrix(angles):
"""
Returns a rotation matrix that will produce the given Euler angles
:param angles: (roll, pitch, yaw)
"""
R_x = Matrix([[1, 0, 0],
[0, cos(q), -sin(q)],
[0, sin(q), cos(q)]]).evalf(subs={q: angles[0]})
R_y = Matrix([[cos... | 22,136 |
def goodput_for_range(endpoint, first_packet, last_packet):
"""Computes the goodput (in bps) achieved between observing two specific packets"""
if first_packet == last_packet or \
first_packet.timestamp_us == last_packet.timestamp_us:
return 0
byte_count = 0
seen_first = False
for pa... | 22,137 |
def validate_scopes(
required_scopes: Sequence[str], token_scopes: Sequence[str]
) -> bool:
"""Validates that all require scopes are present in the token scopes"""
missing_scopes = set(required_scopes) - set(token_scopes)
if missing_scopes:
raise SecurityException(f"Missing required scopes: {mis... | 22,138 |
def make_term_structure(rates, dt_obs):
"""
rates is a dictionary-like structure with labels as keys
and rates (decimal) as values.
TODO: Make it more generic
"""
settlement_date = pydate_to_qldate(dt_obs)
rate_helpers = []
for label in rates.keys():
r = rates[label]
h =... | 22,139 |
def mark_emails_as_sent(automatic_email, emails):
"""
Context manager to mark users who have the given emails as sent after successful sending of email
Args:
automatic_email (AutomaticEmail): An instance of AutomaticEmail
emails (iterable): An iterable of emails
Yields:
queryse... | 22,140 |
def region(x: float, n0: int, n1: int, func='cdf', exhaustive=False):
"""Region of integration for bbprop_cdf or bbprop_test
Parameters
----------
x : float
difference of proportions
n0, n1 : int
number of trials for the two samples
func : str
function to determine regio... | 22,141 |
def _validate_metadata(metadata_list):
"""
Make sure the metadata_list does not have data for the following
core metadata elements. Exception is raised if any of the following elements is present
in metadata_list:
title - (endpoint has a title parameter which should be used for specifying resource ... | 22,142 |
def skip_after_postgres(*ver):
"""Skip a test on PostgreSQL after (including) a certain version."""
ver = ver + (0,) * (3 - len(ver))
def skip_after_postgres_(f):
@wraps(f)
def skip_after_postgres__(self):
if self.conn.server_version >= int("%d%02d%02d" % ver):
re... | 22,143 |
def validateParameters(options):
"""
Who needs documentation
TODO: Add some...
"""
#options.identity should be a valid file
if os.path.isfile(options.identity):
try:
f = open(options.identity, "r")
except IOError as err:
print "Could not open the identity... | 22,144 |
def make_order_embeddings(max_word_length, order_arr):
"""
根据笔顺表生成具有最大字长约束的笔顺embeddings
:param max_word_length:
:param order_arr:
:return:
"""
order_arr = [
row + [0] * (max_word_length - len(row)) if len(row) <= max_word_length
else row[:max_word_length - 1] + [row[-1]]
... | 22,145 |
def test_repo_config_userpass() -> None:
"""Test using repo with username/password."""
password = "pa55word" # noqa: S105
repo = RepositoryConfiguration(
name="pypi",
base_url="https://private.repo.org/pypi",
username="fred",
password=password,
)
assert repo.get_acce... | 22,146 |
def test_too_new_solver_methods_raise_error(X_y_data, solver):
"""Test that highs solver raises for scipy<1.6.0."""
X, y = X_y_data
with pytest.raises(ValueError, match="scipy>=1.6.0"):
QuantileRegressor(solver=solver).fit(X, y) | 22,147 |
def agg_double_list(l):
"""
@param l:
@type l:
@return:
@rtype:
"""
# l: [ [...], [...], [...] ]
# l_i: result of each step in the i-th episode
s = [numpy.sum(numpy.array(l_i), 0) for l_i in l]
s_mu = numpy.mean(numpy.array(s), 0)
s_std = numpy.std(numpy.array(s), 0)
return s_mu, s_std | 22,148 |
def get_string_from_bytes(byte_data, encoding="ascii"):
"""Decodes a string from DAT file byte data.
Note that in byte form these strings are 0 terminated and this 0 is removed
Args:
byte_data (bytes) : the binary data to convert to a string
encoding (string) : optional, the encoding type to... | 22,149 |
def default_component():
"""Return a default component."""
return {
'host': '192.168.0.1',
'port': 8090,
'name': 'soundtouch'
} | 22,150 |
def check_series_duplicates(patches_dir, series_path=Path('series')):
"""
Checks if there are duplicate entries in the series file
series_path is a pathlib.Path to the series file relative to the patches_dir
returns True if there are duplicate entries; False otherwise.
"""
entries_seen = set()... | 22,151 |
def is_free(board: list, pos: int) -> bool:
"""checks if pos is free or filled"""
return board[pos] == " " | 22,152 |
def rc_from_blocks(blocks):
"""
Computes the x and y dimensions of each block
:param blocks:
:return:
"""
dc = np.array([np.diff(b[:, 0]).max() for b in blocks])
dr = np.array([np.diff(b[:, 1]).max() for b in blocks])
return dc, dr | 22,153 |
def _create_parser():
"""
Creates argparser for SISPO which can be used for CLI and options
"""
parser = argparse.ArgumentParser(usage="%(prog)s [OPTION] ...",
description=__file__.__doc__)
parser.add_argument("-i", "--inputdir",
action="s... | 22,154 |
def serialize_measurement(measurement):
"""Serializes a `openff.evaluator.unit.Measurement` into a dictionary of the form
`{'value', 'error'}`.
Parameters
----------
measurement : openff.evaluator.unit.Measurement
The measurement to serialize
Returns
-------
dict of str and str... | 22,155 |
def nikon_ev_bias(seq):
"""
http://tomtia.plala.jp/DigitalCamera/MakerNote/index.asp
First digit seems to be in steps of 1/6 EV.
Does the third value mean the step size? It is usually 6,
but it is 12 for the ExposureDifference.
Check for an error condition that could cause a crash.
Th... | 22,156 |
def process_message(schema, publisher, data):
"""
Method to process messsages for all the bases that uses
Google's Pub/Sub.
Args:
schema (:obj:`dict`, required): A JSON schema for contract
validation. JSON Schema is a vocabulary that allows you
to annotat... | 22,157 |
def rename_record_columns(records, columns_to_rename):
"""
Renames columns for better desc and to match Socrata column names
:param records: list - List of record dicts
:param columns_to_rename: dict - Dict of Hasura columns and matching Socrata columns
"""
for record in records:
for col... | 22,158 |
def request_similar_resource(token, data_):
"""If a similar resource to the data_ passed exists, this method gets and returns it """
headers = {'Authorization': 'Token {}'.format(token.token)}
# get the resource endpoint
url_check_res = URL.DB_URL + 'getSimilarResource/' # only res code if shadow id ... | 22,159 |
def retrieve_uniprot_data_for_acc_list_in_xlsx_file(excelfile_with_uniprot_accessions, input_uniprot_flatfile, selected_uniprot_records_flatfile, logging):
""" From a list of uniprot accessions in excel, select out desired records from a large UniProt flatfile.
Parameters
----------
excelfile_with_unip... | 22,160 |
def total (initial, *positionals, **keywords):
""" Simply sums up all the passed numbers. """
count = initial
for n in positionals:
count += n
for n in keywords:
count += keywords[n]
return count | 22,161 |
def login_required(f):
"""Ensures user is logged in before action
Checks of token is provided in header
decodes the token then returns current user info
"""
@wraps(f)
def wrap(*args, **kwargs):
token = None
if 'x-access-token' in request.headers:
token = request.heade... | 22,162 |
def loop_to_unixtime(looptime, timediff=None):
"""Convert event loop time to standard Unix time."""
if timediff is None:
timediff = _get_timediff()
return looptime + timediff | 22,163 |
def groups(column: str) -> "pli.Expr":
"""
Syntactic sugar for `pl.col("foo").agg_groups()`.
"""
return col(column).agg_groups() | 22,164 |
def create_app(testing=False, cli=False) -> Flask:
"""Application factory, used to create application
"""
from authentek.internal import app
app.config.from_object(os.getenv('APP_SETTINGS', 'authentek.server.config.DevelopmentConfig'))
if testing is True:
app.config["TESTING"] = True
ap... | 22,165 |
def validation_all(system='AuAu200'):
"""
Emulator validation: normalized residuals and RMS error for each
observable.
"""
fig, (ax_box, ax_rms) = plt.subplots(
nrows=2, figsize=figsize(1.25, aspect=.4),
gridspec_kw=dict(height_ratios=[1.5, 1])
)
index = 1
ticks = []
... | 22,166 |
def filter_roidb(roidb, config):
""" remove roidb entries without usable rois """
def is_valid(entry):
""" valid images have at least 1 fg or bg roi """
overlaps = entry['max_overlaps']
fg_inds = np.where(overlaps >= config.TRAIN.FG_THRESH)[0]
bg_inds = np.where((overlaps < conf... | 22,167 |
def get_res(url):
"""
使用requests获取结果
:param url:
:return:
"""
try:
requests.adapters.DEFAULT_RETRIES = 5
res = requests.get(url)
time.sleep(random.randint(0, 3))
if res.status_code == 200:
return res
return None
except Exception, e:
... | 22,168 |
def seebeck_thermometry(T_Kelvin):
"""
This function returns the Seebeck coefficient of the thermocouple
concerned (by default type "E") at a certain temperature. The input of the
function is a temperature in Kelvin, but the coefficient below are for a
polynomial function with T in Celsius. The output is S in [V... | 22,169 |
def correlation_permutation_test(
x, y, f, side, n=10000, confidence=0.99, plot=None, cores=1, seed=None
):
"""This function carries out Monte Carlo permutation tests comparing whether the correlation between two variables is statistically significant
:param x: An iterable of X values observed
:param y... | 22,170 |
def value_iteration(model, maxiter=100):
"""
Solves the supplied environment with value iteration.
Parameters
----------
model : python object
Holds information about the environment to solve
such as the reward structure and the transition dynamics.
maxiter : int
The ma... | 22,171 |
def node(function: Callable):
"""A decorator that registers a function to execute when a node runs"""
sig = inspect.signature(function)
args = []
for (name, param) in sig.parameters.items():
value = param.default
if value is inspect.Parameter.empty:
raise TypeError(f"{name}... | 22,172 |
def tick_bars_test(dataframe):
"""
This validates that the tick_bar() function works
"""
list0 = standard_bars.tick_bars(dataframe, 'close', 33)
if len(list0) > 0:
print('tick_bars_test() pass')
else:
print('error with tick_vars_test()') | 22,173 |
def animate_edge_vect(data, param, res, fig, ax, k, curvature=False):
"""Animate an image of the contour as generated by show_plots.show_edge_scatter().
Parameters
----------
data : data object
param : param object
res : result object
fig : matplotlib figure
ax : matplotlib axis
k :... | 22,174 |
def test_game():
"""Test function to validate functionality of TicTacToe class.
Plays a game of Tic-Tac-Toe by randomly selecting moves for both players.
"""
ttt = TicTacToe()
ttt.print_board()
while not ttt.done:
legal_next_states = ttt.get_legal_next_states(ttt.state)
move_idx ... | 22,175 |
def _change_agent_position(state: State):
"""changes agent position"""
state.agent.position = dataclasses.replace(
state.agent.position,
y=(state.agent.position.y + 1) % state.grid.shape.height,
x=(state.agent.position.x + 1) % state.grid.shape.width,
) | 22,176 |
def mg_refractive(m, mix):
"""Maxwell-Garnett EMA for the refractive index.
Args:
m: Tuple of the complex refractive indices of the media.
mix: Tuple of the volume fractions of the media, len(mix)==len(m)
(if sum(mix)!=1, these are taken relative to sum(mix))
Returns:
The ... | 22,177 |
def locateObjLocation(data, questionDict, questionIdict):
"""
Locate the object of where questions.
Very naive heuristic: take the noun immediately after "where".
"""
where = questionDict['where']
for t in range(data.shape[0] - 1):
if data[t, 0] == where:
for u in range(t + 1... | 22,178 |
def main(config, model, stid, forecast_date):
"""
Produce a Forecast object from bufkit data.
"""
# Get parameters from the config
try:
bufr = config['BUFKIT']['BUFR']
except KeyError:
raise KeyError('bufkit: missing BUFR executable path in config BUFKIT options')
try:
... | 22,179 |
def mkshex(shapes: Union[CSVShape, List[CSVShape]]) -> Schema:
"""Convert list of csv2shape Shapes to ShExJSG Schema object."""
# pylint: disable=invalid-name
# One- and two-letter variable names do not conform to snake-case naming style
if isinstance(shapes, CSVShape):
shapes = [shapes]
s... | 22,180 |
def get_unsigned_js_val(abs_val: int, max_unit: int, abs_limit: int) -> int:
"""Get unsigned remaped joystick value in reverse range
(For example if the limit is 2000, and the input valueis also 2000,
the value returned will be 1. And with the same limit, if the input value
is 1, the output value wwill ... | 22,181 |
def to_xyz(struct, extended_xyz: bool = True, print_stds: bool = False,
print_forces: bool = False, print_max_stds: bool = False,
print_energies: bool = False, predict_energy=None,
dft_forces=None, dft_energy=None, timestep=-1,
write_file: str = '', append: bool = False, labe... | 22,182 |
def load_file(filename: str):
"""Load the .xls file and return as a dataframe object."""
df = pd.read_csv(filename, delimiter='\t')
return df | 22,183 |
def loadRegexList(regexListFile):
"""Returns regexList, registries, internetSources"""
regexList = []
registries = set()
internetSourceTypes = set()
libLF.log('Loading regexes from {}'.format(regexListFile))
with open(regexListFile, 'r') as inStream:
for line in inStream:
line = line.strip()
... | 22,184 |
def _decode_and_center_crop(image_bytes, image_size, resize_method=None):
"""Crops to center of image with padding then scales image_size."""
shape = tf.shape(image_bytes)
image_height = shape[0]
image_width = shape[1]
padded_center_crop_size = tf.cast(
((image_size / (image_size + CROP_PADDING)... | 22,185 |
def match_beacons_translate_only(
sensor_a_beacons: typing.Set[typing.Tuple[int, int, int]],
sensor_b_beacons: numpy.ndarray,
min_matching: int,
) -> typing.Optional[numpy.ndarray]:
"""
Search for matching beacons between `sensor_a_beacons` and `sensor_b_beacons`,
assuming their orie... | 22,186 |
def txm_log():
"""
Return the logger.
"""
return __log__ | 22,187 |
def remove_list_by_name(listslist, name):
"""
Finds a list in a lists of lists by it's name, removes and returns it.
:param listslist: A list of Twitter lists.
:param name: The name of the list to be found.
:return: The list with the name, if it was found. None otherwise.
"""
for i in range(... | 22,188 |
def song_clicks_metric(ranking):
"""
Spotify p
:param ranking:
:return:
"""
if 1 in ranking:
first_idx = ranking.index(1)
return math.floor(first_idx / 10)
return 51
@staticmethod
def print_subtest_results(sub_test_names, metric_names, results):
(num_subt... | 22,189 |
def merge_reports(master: dict, report: dict):
"""
Merge classification reports into a master list
"""
keys = master.keys()
ret = copy.deepcopy(master)
for key in keys:
scores = report[key]
for score, value in scores.items():
ret[key][score] += [value]
return ret | 22,190 |
def compatible_tags(
python_version: Optional[PythonVersion] = None,
interpreter: Optional[str] = None,
platforms: Optional[Iterable[str]] = None,
) -> Iterator[Tag]:
"""
Yields the sequence of tags that are compatible with a specific version of Python.
The tags consist of:
- py*-none-<plat... | 22,191 |
def parse_xeasy_peaks(peak_file):
"""
Parse Xeasy3D peakfile to Peaks object
Xeasy file format stores a column labled 'unused'
to indicate rather the peak has been used in a
structure calculation procedure (0 or 1). This
column is, however, not assigned automatically
and may not be set ... | 22,192 |
def detect_objects():
"""
Detect objects in frame(from sharred array) and return target information
"""
detector = yolo()
detect_fps = FPS()
shm_to_yolo = shared_memory.SharedMemory(name='img_to_yolo')
shared_img_to_yolo = np.ndarray((720, 960, 3), dtype=np.uint8, buffer=shm_to_yolo.buf)
... | 22,193 |
def main():
"""Session manager"""
__remove_temp_session()
# **** Collect command line options ****
# Note regarding Options:
# It's important to collect options before monkey patching sys.exit,
# otherwise, optparse won't be able to exit if --help option is passed
options, args ... | 22,194 |
def ingestion_before_request():
""" Custom checks for login requirements """
pass | 22,195 |
def multi_layer_images():
"""
Returns complex images (with sizes) for push and pull testing.
"""
# Note: order is from base layer down to leaf.
layer1_bytes = layer_bytes_for_contents(
"layer 1 contents", mode="", other_files={"file1": "from-layer-1",}
)
layer2_bytes = layer_bytes_f... | 22,196 |
def display_all(eventfile,diag_var,lc_t,lc_counts,diag_t,diag_counts,filetype):
"""
To display the plots for desired time interval. Whether to save or show the
plots is determined in Lv3_diagnostics.
eventfile - path to the event file. Will extract ObsID from this for the NICER files.
diag_var - th... | 22,197 |
def user_teams(config: Config, email: str) -> Iterable[Team]:
"""Return the teams a user member is expected to be a member of.
Only the teams in which the user is a direct member are return. The
ancestors of these teams are not returned.
"""
names = config.by_member.get(email)
if not names:
... | 22,198 |
def se3_transform(g, a, normals=None):
""" Applies the SE3 transform
Args:
g: SE3 transformation matrix of size ([1,] 3/4, 4) or (B, 3/4, 4)
a: Points to be transformed (N, 3) or (B, N, 3)
normals: (Optional). If provided, normals will be transformed
Returns:
transformed po... | 22,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.