content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _clip_boxes(boxes, im_shape):
"""Clip boxes to image boundaries."""
# x1 >= 0
boxes[:, 0::4] = np.maximum(boxes[:, 0::4], 0)
# y1 >= 0
boxes[:, 1::4] = np.maximum(boxes[:, 1::4], 0)
# x2 < im_shape[1]
boxes[:, 2::4] = np.minimum(boxes[:, 2::4], im_shape[1] - 1)
# y2 < im_shape[0]
... | 36,100 |
def gen_api_url(endpoint):
"""Construct a Wger API url given the endpoint"""
# type: (str) -> str
return WGER["host_name"] + WGER["api_ext"] + endpoint | 36,101 |
def send_mail(receivers, subject, message, html=None):
"""
Sends an email to the recipients. Must be called from an EngineThread. This method will not raise any exception
if it fails to send a message to the recipients.
:param list(str) receivers: list of recipient email addresses
:param str subjec... | 36,102 |
def create_inputs(
data: np.ndarray,
input_type_name: Literal[
"data",
"data_one_column",
"one_in_one_out_constant",
"one_in_one_out",
"one_in_batch_out",
"sequentions",
],
input_type_params: dict,
mode: Literal["validate", "in_sample"] = "validate",
... | 36,103 |
def predictions(
dataset_path: str,
predictions_path: str,
output_path: str,
label_scores: bool,
calibration_factor: float
) -> None:
"""Analyze classification performance and write a report.
Read in the dataset from DATASET_PATH, as well as predictions from
PREDICTI... | 36,104 |
def CDLKICKINGBYLENGTH(df):
"""
函数名:CDLKICKINGBYLENGTH
名称:Kicking - bull/bear determined by the longer marubozu 由较长缺影线决定的反冲形态
简介:二日K线模式,与反冲形态类似,较长缺影线决定价格的涨跌。
python API
integer=CDLKICKINGBYLENGTH(open, high, low, close)
:return:
"""
open = df['open']
high = df['high']
low =... | 36,105 |
def report_count_table_sort(s1, s2):
""" """
# Sort order: Class and scientific name.
columnsortorder = [0, 2, 3, 6] # Class, species, size class and trophy.
#
for index in columnsortorder:
s1item = s1[index]
s2item = s2[index]
# Empty strings should be at the end.
... | 36,106 |
def test_none_stream_fails(capsys):
"""
Tests that if a call to the flush method is called (it shouldn't be called directly)
and no process is being monitored then a message is printed to stdout but it doesn't raise
an exception.
"""
streamer = Streamer(verbose=True)
none_stream = None
... | 36,107 |
def serch_handler(msg):
"""
处理音乐搜索结果
:param msg: 搜索信息
:return:
"""
# url = 'https://www.ximalaya.com/revision/search?core=all&kw={0}&spellchecker=true&device=iPhone'
url = 'https://www.ximalaya.com/revision/search?kw={0}&page=1&spellchecker=false&condition=relation&rows=50&device=iPhone&core... | 36,108 |
def test_workflow_cancel(hl7_message):
"""Validates cancel transition invocation"""
edi = EdiProcessor(hl7_message)
actual_result = edi.cancel()
assert actual_result.metadata is None
assert actual_result.metrics.analyzeTime == 0.0
assert actual_result.inputMessage == hl7_message
assert actua... | 36,109 |
def random(start: int, end: int) -> int:
"""Same as `random.randint(start, end)`"""
return randint(start, end) | 36,110 |
def zero_check(grid):
"""Take a 2d grid and calculates number of 0 entries."""
zeros = 0
for row in grid:
for element in row:
if element == 0:
zeros += 1
return zeros | 36,111 |
def get_channel_clips(channel: Channel) -> List[Clip]:
"""
Uses a (blocking) HTTP request to retrieve Clip info for a specific channel.
:param channel: A Channel object.
:returns: A list of Clip objects.
"""
clips = []
pagination = ""
while True:
query = gql.GET_CHANNEL_CLIPS_QUERY.format(
channel_id=cha... | 36,112 |
def scrollLevelData(playerList, level, goldCount, time, levelCount, highScore):
"""Draw the level data to the screen as it scrolls off-screen.
This includes the time remaining, gold remaining, players' lives, black hole sprites, gold sprites, text
sprites, trap sprites, and the level image.
After the l... | 36,113 |
def tensorflow2xp(tf_tensor: "tf.Tensor") -> ArrayXd: # pragma: no cover
"""Convert a Tensorflow tensor to numpy or cupy tensor."""
assert_tensorflow_installed()
if tf_tensor.device is not None:
_, device_type, device_num = tf_tensor.device.rsplit(":", 2)
else:
device_type = "CPU"
i... | 36,114 |
def test_gradient_blur_ascend():
"""
Feature: Test gradient blur.
Description: Add gradient blur to an image.
Expectation: success.
"""
context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
image = np.random.random((32, 32, 3))
number = 10
h, w = image.shape[:2]
po... | 36,115 |
def test_execute_query_flow():
"""
Test flow with Compose handle (non DB native handle).
Compose Editor API (non native DB api)
"""
interpreter = _get_interpreter(None)
with patch("compose.editor.query.engines.SqlAlchemyInterface.execute") as execute:
execute.return_value = {"guid": "ab... | 36,116 |
def __str__(self, indent=0, func_role="obj"):
"""
our own __str__
"""
out = []
out += self._str_signature()
out += self._str_index() + ['']
out += self._str_summary()
out += self._str_extended_summary()
out += self._str_param_list('Parameters')
out += self._str_options('Options')... | 36,117 |
def validate_contests_2006_general():
"""Check that there are the correct number of Contest records for the 2006 general election"""
Election2006General().validate_contests() | 36,118 |
def cmd():
"""Return the Juju command
There are times when multiple versions of Juju may be installed or
unpacked requiring testing.
This function leverages two environment variables to select the correct
Juju binary. Thus allowing easy switching from one version to another.
JUJU_BINARY: The ... | 36,119 |
def worker_years_6_download(request):
"""
纺织类通信带条件查询,然后下载对应结果文件
:param request:
:return:
"""
return download.worker_years_6_download(request) | 36,120 |
def generate_unique_id(mapper, connection, target):
"""Generates a firebase fancy unique Id
Args:
mapper (obj): The current model class
connection (obj): The current database connection
target (obj): The current model instance
Returns:
None
"""
... | 36,121 |
def set_autoscaler_location(autoscaler, is_regional, location):
""" Sets location-dependent properties of the autoscaler. """
name = autoscaler['name']
location_prop_name = 'region' if is_regional else 'zone'
autoscaler['type'] = REGIONAL_LOCAL_AUTOSCALER_TYPES[is_regional]
autoscaler['properties'... | 36,122 |
def test_check_if_metrics_file_are_same():
"""
General tests for checking if the metrics file is the same
"""
logging.info(
"### Check if files are the same from alignment metrics calculation ###"
) | 36,123 |
def test_rdkit_possible_fail():
"""RDKit can't generate structures for some SMILES, make sure they can
be generated in other ways"""
rh_complex = Molecule(smiles='C[Rh](=C=O)(=C=O)(=C=O)=C=O')
assert are_coords_reasonable(coords=rh_complex.coordinates)
# Trying to parse with RDKit should revert to... | 36,124 |
def _define_deformation_axes() -> Dict[str, Iterable[str]]:
"""Defines object sets for each axis of deformation."""
rgb_objects_dim = {}
for a in DEFORMATION_AXES:
rgb_objects_dim[a] = []
for v in _DEFORMATION_VALUES:
obj_id = f'{v}{a}'
# There are excluded objects we need to check for.
... | 36,125 |
def ldns_rr2buffer_wire_canonical(*args):
"""LDNS buffer."""
return _ldns.ldns_rr2buffer_wire_canonical(*args) | 36,126 |
def copy_snapshot(client, rds_instance, debug=True):
""" Copy a snapshot the latest automated snapshot """
latest_snap = get_latest_snap(client, rds_instance, debug)
try:
resp = client.copy_db_snapshot(
SourceDBSnapshotIdentifier=latest_snap['DBSnapshotIdentifier'],
TargetDBS... | 36,127 |
def get_stretch_factor(folder_name, indices, **kwargs):
""" Computes the stretch factor using the (16-50-84) percentile estimates
of x0 - x1 for each restframe wavelength assuming orthogonality
Parameters:
folder_name: folder containing the individual likelihoods and their
perc... | 36,128 |
def zonal_length(lat, nlon):
""" length of zonal 1/nlon segment at latitude lat"""
return R_earth * 2*np.pi/nlon * np.cos(lat*np.pi/180) | 36,129 |
def map_request_attrs(name_request, **kwargs):
"""
Used internally by map_request_data.
:param name_request:
:key nr_id: int
:key nr_num: str
:key request_entity: str
:key request_action: str
:key request_type: str
:return:
"""
try:
# Use class property values for the... | 36,130 |
def create_gw_response(app, wsgi_env):
"""Create an api gw response from a wsgi app and environ.
"""
response = {}
buf = []
result = []
def start_response(status, headers, exc_info=None):
result[:] = [status, headers]
return buf.append
appr = app(wsgi_env, start_response)
... | 36,131 |
def Squeeze(parent, axis=-1, name=""):
"""\
Dimension of size one is removed at the specified position (batch
dimension is ignored).
:param parent: parent layer
:param axis: squeeze only along this dimension
(default: -1, squeeze along all dimensions)
:param name: name of the output layer... | 36,132 |
def parse_namespace(tt):
"""
<!ELEMENT NAMESPACE EMPTY>
<!ATTLIST NAMESPACE
%CIMName;>
"""
check_node(tt, 'NAMESPACE', ['NAME'], [], [])
return attrs(tt)['NAME'] | 36,133 |
def test_get_asset_info_fii() -> None:
"""Return FII."""
asset_info = b3.get_asset_info("DOVL11B")
assert asset_info.category == "FII"
assert asset_info.cnpj == "10.522.648/0001-81" | 36,134 |
def clean(val, floor, ceiling):
"""Make sure RH values are always sane"""
if val > ceiling or val < floor or pd.isna(val):
return None
if isinstance(val, munits.Quantity):
return float(val.magnitude)
return float(val) | 36,135 |
def count_swaps_in_row_order(row_order: Union[List[int], Tuple[int]]) -> int:
"""
Counts the number of swaps in a row order.
Args:
row_order (Union[List[int], Tuple[int]]): A list or tuple
of ints representing the order of rows.
Returns:
int: The minimum number of swaps it take... | 36,136 |
def evaluate(ast, env):
"""Evaluate an Abstract Syntax Tree in the specified environment."""
print(ast)
if is_boolean(ast):
return ast
if is_integer(ast):
return ast
if is_string(ast):
return ast
if is_symbol(ast):
return env.lookup(ast)
if is_list(ast):
... | 36,137 |
def create_eulerian_circuit(graph_augmented, graph_original, start_node=None):
"""
networkx.eulerian_circuit only returns the order in which we hit each node. It does not return the attributes of the
edges needed to complete the circuit. This is necessary for the postman problem where we need to keep trac... | 36,138 |
def load_data(
assets: tp.Union[None, tp.List[tp.Union[str,dict]]] = None,
min_date: tp.Union[str, datetime.date, None] = None,
max_date: tp.Union[str, datetime.date, None] = None,
dims: tp.Tuple[str, str] = (ds.TIME, ds.ASSET),
forward_order: bool = True,
tail: tp.Union[... | 36,139 |
def test_popleft_empty_throws_error(deque_fixture):
"""Test popleft empty throws error."""
with pytest.raises(IndexError):
deque_fixture.popleft() | 36,140 |
def create_model(values):
"""create the model basing on the calculated values.
Args:
values (dict): values from the get_values_from_path function
Raises:
ValueError: if the loss function doesnt excist
Returns:
torch.nn.Module: model the network originally was trained with.
... | 36,141 |
def loss(logits, labels):
"""Calculates the loss from the logits and the labels.
Args:
logits: Logits tensor, float - [batch_size, NUM_CLASSES].
labels: Labels tensor, int32 - [batch_size].
Returns:
loss: Loss tensor of type float.
"""
loss = tf.reduce_mean(
tf.nn.softmax_cross... | 36,142 |
def old_get_obs_session(project=None, dss=None, date=None, path='proj'):
"""
Provides project, station, year and DOY, asking as needed.
It follows one of several possible paths to get to the session::
proj - path through /usr/local/projects/<project>
hdf5 - path through /usr/local/RA_data/HDF5
f... | 36,143 |
def create_pattern_neighbors_ca2d(width, height, n_states=2):
"""
Returns a list with the weights for 'neighbors' and 'center_idx' parameters
of evodynamic.connection.cellular_automata.create_conn_matrix_ca1d(...).
The weights are responsible to calculate an unique number for each different
neighborhood patte... | 36,144 |
def exception_logging(exctype, value, tb):
"""
Log exception by using the root logger.
Parameters
----------
exctype : type
value : NameError
tb : traceback
"""
write_val = {'exception_type': str(exctype),
'message': str(traceback.format_tb(tb, 10))}
print('Erro... | 36,145 |
def by_colname_like(colname, colname_val):
"""
Query to handle the cases in which somebody has the correct
words within their query, but in the incorrect order (likely
to be especially relevant for professors).
"""
def like_clause_constructor(colname, colname_val):
"""
Helper fu... | 36,146 |
def export(template,
values,
out,
verbose):
"""
Export OSM data using overpass query templates.
TEMPLATE is a file containing a template string with '$'-based substitution. Defines the overpass query and substitution keys.
VALUES is an yaml-file defining the va... | 36,147 |
def decode_classnames_json(preds, top=5):
"""
Returns class code, class name and probability for each class amongst top=5 for each prediction in preds
e.g.
[[('n01871265', 'tusker', 0.69987053), ('n02504458', 'African_elephant', 0.18252705), ... ]]
"""
if len(preds.shape) != 2 or preds.sha... | 36,148 |
def MCMC(prob_model):
"""
Samples exact posterior samples from the probabilistic model, which has been fit with VI before.
:param VI_optimized prob_model: the probabilistic model to sample from
"""
return | 36,149 |
def mock_create_schedule_request() -> Generator[MagicMock, Any, None]:
"""Fixture for mocking the create_schedule response.
Yields:
Mocked ``SwitcherV2CreateScheduleResponseMSG`` object.
"""
mock_response = MagicMock(messages.SwitcherV2CreateScheduleResponseMSG)
mock_response.successful = Tr... | 36,150 |
def validate_future(value: date):
"""Validate value >= today."""
if value < date.today():
raise ValidationError(f'{value} est déjà passé') | 36,151 |
def _GetSupplementalColumns(build_dir, supplemental_colummns_file_name):
"""Reads supplemental columns data from a file.
Args:
build_dir: Build dir name.
supplemental_columns_file_name: Name of a file which contains the
supplemental columns data (in JSON format).
Returns:
A dict of supplemen... | 36,152 |
def prime_decomposition(number):
"""Returns a dictionary with the prime decomposition of n"""
decomposition = {}
number = int(number)
if number < 2:
return decomposition
gen = primes_gen()
break_condition = int(math.sqrt(number))
while number > 1:
current_prime = next(gen)
... | 36,153 |
def remove_office_metadata(file_name):
"""
Remove all metadata from Microsoft Office 2007+ file types such as docx,
pptx, and xlsx.
:param str file_name: The path to the file whose metadata is to be removed.
"""
ns = {
'cp': 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties',
'dc': 'ht... | 36,154 |
def test_coalesce_ioresult():
"""Ensures that `coalesce` is always returning the correct type."""
assert _ioresult_converter(IOSuccess(1)) == IO(1)
assert _ioresult_converter(IOFailure(1)) == IO(0) | 36,155 |
def org_client(aws_credentials):
"""Organizations Mock Client"""
with mock_organizations():
connection = boto3.client("organizations", region_name="us-east-1")
yield connection | 36,156 |
def load_10x(
celltype: str = "CD8_healthy", exclude_singles: bool = True
) -> pd.DataFrame:
"""
Load 10x data. Columns of interest are TRA_aa and TRB_aa
"""
def split_to_tra_trb(s: Iterable[str]):
"""Split into two lists of TRA and TRB"""
# TODO this does NOT correctly handle cases... | 36,157 |
def levenshtein(s1, s2):
"""
Levenstein distance, or edit distance, taken from Wikibooks:
http://en.wikibooks.org/wiki/Algorithm_implementation/Strings/Levenshtein_distance#Python
"""
if len(s1) < len(s2):
return levenshtein(s2, s1)
if not s1:
return len(s2)
previous_row = ... | 36,158 |
def test_dump_file_name_without_timestamp():
"""
pgdump.dump_file_name returns the name of the database.
"""
assert pgdump.dump_file_name(url) == 'db_one.sql' | 36,159 |
def configure_mpi_node() -> Tuple[RabbitConfig, Celery]:
"""Will configure and return a celery app targetting GPU mode nodes."""
log.info("Initializing celery app...")
app = _celery_app_mpi
# pylint: disable=unused-variable
@app.task(
name="comp.task.mpi",
bind=True,
autoret... | 36,160 |
def customizations(record):
"""
Use some functions delivered by the library
@type record: record
@param record: a record
@rtype: record
@returns: -- customized record
"""
record = type(record)
# record = author(record)
record = convert_to_unicode(record)
# record = editor(r... | 36,161 |
def test_all_permission_string():
""" test the string representation of the "All" constan """
from fastapi_permissions import All
assert str(All) == "permissions:*" | 36,162 |
def enrichs_to_gv(G, enrich_fhs, ofh, **kwargs):
"""
Read the next line in each file handle in <enrich_fhs> and parse the significant GO:BP
annotation in that line. Then, write the GO:BP annotations, along with the original graph,
to a graphviz open file handle <ofh>.
Parameters
----------
G : nx.Graph
... | 36,163 |
def download_yeast_model(rawDir):
"""Download FBA model."""
url = 'https://pilotfiber.dl.sourceforge.net/project/yeast/yeast_7.6.zip'
outPath = os.path.join(rawDir, 'yeast_7.6')
if os.path.exists(outPath):
print outPath, 'already exists. Skipping.'
return
os.system('wget -P ' + rawDi... | 36,164 |
def export_from_checkpoint():
"""Restore variables from a given checkpoint."""
with tf1.Session() as sess:
model = effnetv2_model.EffNetV2Model(effnet_name)
isize = 224 or model.cfg.eval.isize
inputs = tf.ones((batch_size, isize, isize, 3), tf.float32)
_ = model(inputs, training=False)
sess.run(... | 36,165 |
def _has_letter(pw):
"""
Password must contain a lowercase letter
:param pw: password string
:return: boolean
"""
return any(character.isalpha() for character in pw) | 36,166 |
def closest_power_of_two(n):
"""Returns the closest power of two (linearly) to n.
See: http://mccormick.cx/news/entries/nearest-power-of-two
Args:
n: Value to find the closest power of two of.
Returns:
Closest power of two to "n".
"""
return pow(2, int(math.log(n, 2) + 0.5)) | 36,167 |
def prepare_time_inhomogeneous_cv_object(cv: BaseTimeSeriesCrossValidator):
"""
Creates a sample set consisting in 11 samples at 2h intervals, spanning 20h, as well as 10 samples at 59m intervals,
with the first samples of each group occurring at the same time.
pred_times and eval_times have the follow... | 36,168 |
def get_product(barcode, locale='world'):
"""
Return information of a given product.
"""
return utils.fetch(utils.build_url(geography=locale,
service='api',
resource_type='product',
param... | 36,169 |
def score(y_true, y_score):
""" Evaluation metric
"""
fpr, tpr, thresholds = roc_curve(y_true, y_score, pos_label = 1)
score = 0.4 * tpr[np.where(fpr>=0.001)[0][0]] + \
0.3 * tpr[np.where(fpr>=0.005)[0][0]] + \
0.3 * tpr[np.where(fpr>=0.01)[0][0]]
return score | 36,170 |
def group_umis(bam_file, groups_file, log_file, run_config):
"""
Idenfity UMI groups using ``umi_tools group``.
:param bam_file: BAM file (input)
:type bam_file: str or unicode
:param groups_file: UMI groups file (output)
:type groups_file: str or unicode
:param log_file: Log file (output)
... | 36,171 |
def divisors(num):
"""
Takes a number and returns all divisors of the number, ordered least to greatest
:param num: int
:return: list (int)
"""
list = []
x = 0
for var in range(0, num):
x = x + 1
if num % x == 0:
list.append(x)
return list | 36,172 |
def files_page():
"""Displays a table of the user's files."""
user = utils.check_user(token=request.cookies.get("_auth_token"))
if user is None:
return redirect(location="/api/login",
code=303), 303
return render_template(template_name_or_list="home/files.html",
... | 36,173 |
def GetCodepage(language):
""" Returns the codepage for the given |language|. """
lang = _LANGUAGE_MAP[language]
return "%04x" % lang[0] | 36,174 |
def dochdir(thedir):
"""Switch to dir."""
if flag_echo or flag_dryrun:
sys.stderr.write("cd " + thedir + "\n")
if flag_dryrun:
return
try:
os.chdir(thedir)
except OSError as err:
u.error("chdir failed: %s" % err) | 36,175 |
def NumVisTerms(doc):
"""Number of visible terms on the page"""
_, terms = doc
return len(terms) | 36,176 |
def download_all(path='data', verify=True, extract=True):
"""
Downloads all the example datasets. If verify is True then compare the
download signature with the hardcoded signature. If extract is True then
extract the contents of the zipfile to the given path.
"""
for name, meta in DATASETS.item... | 36,177 |
def test_fspl_noLD():
"""
check if FSPL magnification is calculate properly
"""
t_0 = 2456789.012345
t_E = 23.4567
u_0 = 1e-4
rho = 1e-3
t_vec = np.array([-(rho**2-u_0**2)**0.5, 0., ((0.5*rho)**2-u_0**2)**0.5])
t_vec = t_vec * t_E + t_0
params = mm.ModelParameters(
{'t_0... | 36,178 |
def replace_inf_price_nb(prev_close: float, close: float, order: Order) -> Order:
"""Replace infinity price in an order."""
order_price = order.price
if order_price > 0:
order_price = close # upper bound is close
else:
order_price = prev_close # lower bound is prev close
return ord... | 36,179 |
def get_trend(d):
"""
Calcuate trend for a frame `d`.
"""
dv = d.reset_index(drop=True)
dv["minutes"] = np.arange(dv.shape[0], dtype=np.float64)
covariance = dv.cov()
return (((covariance["minutes"]) / covariance.loc["minutes", "minutes"])[d.columns]
.rename(lambda cl: "_".join(... | 36,180 |
def getIpAddress():
"""Returns the IP address of the computer the client is running on,
as it appears to the client.
See also: system.net.getExternalIpAddress().
Returns:
str: Returns the IP address of the local machine, as it sees it.
"""
return "127.0.0.1" | 36,181 |
def line(x, y, weights=None, clip=0.25):
"""Fit a line
Args:
x (numpy.array): x-values
y (numpy.array): y-values
clip (float, optional): Fit only first part. Defaults to 0.25.
Returns:
pandas.Series: fit parameters
"""
if 0 < clip < 1:
clip_int = int(len(x) ... | 36,182 |
def one_hot(data):
"""
Using pandas to convert the 'data' into a one_hot enconding format.
"""
one_hot_table = pd.get_dummies(data.unique())
one_hot = data.apply(lambda x: one_hot_table[x] == 1).astype(int)
return one_hot | 36,183 |
def update_set(j, n):
"""Computes the update set of the j-th orbital in n modes
Args:
j (int) : the orbital index
n (int) : the total number of modes
Returns:
Array of mode indexes
"""
indexes = np.array([])
if n % 2 == 0:
if j < n / 2:
indexes = np.a... | 36,184 |
def chunklist(inlist: list, chunksize: int) -> list:
"""Split a list into chucks of determined size.
Keyword arguments:
inList -- list to chunk
chunkSize -- number of elements in each chunk
"""
if not isinstance(inlist, list):
raise TypeError
def __chunkyield() -> list:
# ... | 36,185 |
def test_config_is_allowed_external_url():
"""Test is_allowed_external_url method."""
config = ha.Config(None)
config.allowlist_external_urls = [
"http://x.com/",
"https://y.com/bla/",
"https://z.com/images/1.jpg/",
]
valid = [
"http://x.com/1.jpg",
"http://x... | 36,186 |
def _ArchiveFlakesForClosedIssue(flake_issue):
"""Archives flakes with closed issue.
Flakes with closed issue should be archived since they are fixed or not
actionable.
"""
flakes = Flake.query(Flake.flake_issue_key == flake_issue.key).fetch()
for flake in flakes:
flake.archived = True
ndb.put_multi(... | 36,187 |
def create_nwb_group(nwb_path, group_name):
"""
Create an NWB BehavioralTimeSeries for grouping data
Args:
config_filepath (Path): path to the config file
group_name (str): name of group to be created
Returns:
"""
with NWBHDF5IO(nwb_path,'a') as io:
nwbfile = io.read()... | 36,188 |
def getLocation(seq, meifile, zones):
""" Given a sequence of notes and the corresponding MEI Document, calculates and returns the json formatted list of
locations (box coordinates) to be stored for an instance of a pitch sequence in our CouchDB.
If the sequence is contained in a single system, only... | 36,189 |
def pytest_runtest_logfinish(nodeid: str) -> None:
"""
At the end of running the runtest protocol for a single item.
https://docs.pytest.org/en/latest/reference.html#_pytest.hookspec.pytest_runtest_logfinish
"""
global _syrupy
if _syrupy:
_syrupy.ran_item(nodeid) | 36,190 |
def overlay_on_image(display_image:numpy.ndarray, object_info_list:list, fps:float):
"""Overlays the boxes and labels onto the display image.
:param display_image: the image on which to overlay the boxes/labels
:param object_info_list: is a list of lists which have 6 values each
these are the 6 v... | 36,191 |
def calculate_A0_moving_LE(psi_baseline, psi_goal_0, Au_baseline, Au_goal, deltaz,
c_baseline, l_LE, eps_LE):
"""Find the value for A_P0^c that has the same arc length for the first bay
as for the parent."""
def integrand(psi_baseline, Al, deltaz, c ):
return c*n... | 36,192 |
def create_train_val_set(x_train, one_hot_train_labels):
"""[summary]
Parameters
----------
x_train : [type]
[description]
y_train : [type]
[description]
"""
x_val = x_train[:1000]
partial_x_train = x_train[1000:]
y_val = one_hot_train_labels[:1000]
partial_y_tr... | 36,193 |
def _initialize_indices(model_class, name, bases, attrs):
"""
Stores the list of indexed attributes.
"""
model_class._indexed_fields = []
model_class._indexed_meta_field = model_class.__index_meta__
model_class._indexed_unique_fields = model_class.__unique_index__
model_class._indexed_value_... | 36,194 |
def run_server(host, port, debug):
"""启动flask开发服务"""
threading.currentThread().name = 'server'
from libraryuir.web import create_app
app = create_app()
app.run(host, port, debug) | 36,195 |
def build_master_and_get_version():
"""Checks out the latest master build and creates a new binary."""
if not os.path.exists(TOOL_SOURCE):
process.call(
'git clone https://github.com/google/clusterfuzz-tools.git', cwd=HOME)
process.call('git fetch', cwd=TOOL_SOURCE)
process.call('git checkout origin... | 36,196 |
def get_adj_date(time,today):
"""
"""
#print(time,today)
if 'month' in time:
week_multiplier = 28
elif 'week' in time:
week_multiplier = 7
elif 'day' in time:
week_multiplier = 1
else:
week_multiplier = 0
# Hack! updated from 01.12.2020
# TOD... | 36,197 |
def update_dataset_temporal_attrs(dataset: xr.Dataset,
update_existing: bool = False,
in_place: bool = False) -> xr.Dataset:
"""
Update temporal CF/THREDDS attributes of given *dataset*.
:param dataset: The dataset.
:param update_exist... | 36,198 |
def pprint_bird_protocols(version):
"""
Pretty print the output from the BIRD "show protocols". This parses the
existing output and lays it out in pretty printed table.
:param version: The IP version (4 or 6).
:return: None.
"""
# Based on the IP version, run the appropriate BIRD command,... | 36,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.