content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def write_tube_sample(radius):
"""Saves the image of the tube with selected radius"""
tube_input = files.slices.get_tube_sample()
circ = get_bound_circ(tube_input, radius)
x, y = circ[:2]
tube_file = tube_input.copy()
cv2.circle(tube_file, (x, y), radius, (255, 0, 0), 1)
cv2.imwrite("src/gui... | 5,354,700 |
def evaluate_score_batch(
predicted_classes=[], # list, len(num_classes), str(code)
predicted_labels=[], # shape (num_examples, num_classes), T/F for each code
predicted_probabilities=[], # shape (num_examples, num_classes), prob. [0-1] for each code
raw_ground_truth_labels=[], # list(('dx1', 'dx2')... | 5,354,701 |
def pair(data, color=None, tooltip=None, mark='point', width=150, height=150):
"""
Create pairwise scatter plots of all column combinations.
In contrast to many other pairplot tools,
this function creates a single scatter plot per column pair,
and no distribution plots along the diagonal.
Para... | 5,354,702 |
def gauss_kernel(model_cell, x, y, z, sigma=1):
"""
Convolute aligned pixels given coordinates `x`, `y` and values `z` with a gaussian kernel to form the final image.
Parameters
----------
model_cell : :class:`~colicoords.cell.Cell`
Model cell defining output shape.
x : :class:`... | 5,354,703 |
def main(argv):
"""
Creates a parquet file with tissue data.
:param list argv: the list elements should be:
[1]: Parquet file path with raw sample data
[2]: Output file
"""
raw_source_parquet_path = argv[1]
output_path = argv[2]
spark = SparkSession.b... | 5,354,704 |
def create_file2four(file_list):
"""
Function to merge ascii files.
Parameters
-------------
file_list : 'str'
Path to the files. Taken automatically.
Returns
-------------
Merged file: output_file4.txt
"""
with open('output_file4.txt', 'w') as file3:
readers = [open(file) for file in file_l... | 5,354,705 |
def get_configs_from_multiple_files():
"""Reads training configuration from multiple config files.
Reads the training config from the following files:
model_config: Read from --model_config_path
train_config: Read from --train_config_path
input_config: Read from --input_config_path
Returns:
mode... | 5,354,706 |
def from_package(package_name, extensions=('.py',)):
"""Generate *.py file names available in given package."""
extensions = tuple(extensions) # .endswith doesn't like list
process = Popen("/usr/bin/dpkg -L %s" % package_name,
shell=True, stdout=PIPE)
stdout, stderr = process.commun... | 5,354,707 |
def line_to_numbers(line: str) -> t.List[int]:
"""Split a spreadsneet line into a list of numbers.
raises:
ValueError
"""
return list(map(int, line.split())) | 5,354,708 |
def bits_to_amps(bits):
"""helper function to convert raw data from usb device to amps"""
return bits*BITS_TO_AMPS_SLOPE + BITS_TO_AMPS_Y_INTERCEPT | 5,354,709 |
def fields_to_dict(fields):
""" FIXME:
https://www.debuggex.com/r/24QPqzm5EsR0e2bt
https://www.debuggex.com/r/0SjmBL55ySna0kFF
https://www.debuggex.com/r/Vh9qvHkCV4ZquS14
"""
result = {}
if not fields or len(fields.strip()) == 0:
return result
# look_behind_keys = r... | 5,354,710 |
def get_font_paths(fonts_dir):
"""
Load font path recursively from a folder
:param fonts_dir: folder contains ttf、otf or ttc format font
:return: path of all fonts
"""
print('Load fonts from %s' % os.path.abspath(fonts_dir))
fonts = glob.glob(fonts_dir + '/**/*', recursive=True)
fonts = ... | 5,354,711 |
def create(arguments):
""" Create a document """
if arguments.attack_log is None:
raise CmdlineArgumentException("Creating a new document requires an attack_log")
doc_get = DocGenerator()
doc_get.generate(arguments.attack_log, arguments.outfile) | 5,354,712 |
def time_difference(t_early, t_later):
"""
Compute the time difference between t_early and t_later
Parameters:
t_early: np.datetime64, list or pandas series.
t_later: np.datetime64, list or pandas series.
"""
if type(t_early) == list:
t1 = np.array(t_early)
elif type(t_early) ==... | 5,354,713 |
def test_get_id_info_fuzzy_min_ratio():
"""
Tests the get_id_info function fuzzy matching with a specified minimum ratio.
"""
sa_id_book = SAIDBook()
in_str = (
'edn0 7101135111011\n'
'Suriname\n'
'Doe\n'
'Forenames\n'
'John-Michael\n'
'Robert\n'
... | 5,354,714 |
def conv2d_block(input_tensor, n_filters, kernel_size=3, batchnorm=True):
""" Convolutional block with two convolutions followed by batch normalisation (if True) and with ReLU activations.
input_tensor: A tensor. Input tensor on which the convolutional block acts.
n_filters: An integer. Number of filters in... | 5,354,715 |
def check_credentials(username):
"""
Function that check if a Credentials exists with that username and return true or false
"""
return Credentials.if_credential_exist(username) | 5,354,716 |
def rpc_category_to_super_category(category_id, num_classes):
"""Map category to super-category id
Args:
category_id: list of category ids, 1-based
num_classes: 1, 17, 200
Returns:
super-category id, 0-based
"""
cat_id = -1
assert num_classes in RPC_SUPPORT_CATEGORIES, \
... | 5,354,717 |
def setup_integration():
"""Set up a test resource."""
print('Setting up a test integration for an API')
return Integration(name='myapi',
base_url='https://jsonplaceholder.typicode.com') | 5,354,718 |
def secondsToHMS(intervalInSeconds):
"""converts time in seconds to a string representing time in hours, minutes, and seconds
:param intervalInSeconds: a time measured in seconds
:returns: time in HH:MM:SS format
"""
interval = [0, 0, intervalInSeconds]
interval[0] = (inter... | 5,354,719 |
def build_rdn(coords, r, **kwargs):
"""
Reconstruct edges between nodes by radial distance neighbors (rdn) method.
An edge is drawn between each node and the nodes closer
than a threshold distance (within a radius).
Parameters
----------
coords : ndarray
Coordinates of points where... | 5,354,720 |
def find_layer(model, type, order=0):
"""
Given a model, find the Nth layer of the specified type.
:param model: the model that will be searched
:param type: the lowercase type, as it is automatically saved by keras in the layer's name (e.g. conv2d, dense)
:param order: 0 by default (the first matc... | 5,354,721 |
def _interpretable(model):
# type: (Union[str, h2o.model.ModelBase]) -> bool
"""
Returns True if model_id is easily interpretable.
:param model: model or a string containing a model_id
:returns: bool
"""
return _get_algorithm(model) in ["glm", "gam", "rulefit"] | 5,354,722 |
def uploaded_mapping(mimic_mapping, destroy_mimic_source):
"""Impots the mimic mapping to river-api
Args:
mimic_mapping (dict): the mimic mapping fixture loaded as dict
Raises:
Exception: when the mapping could not be uploaded
Yields:
dict: The uploaded mapping
"""
try... | 5,354,723 |
def apply_pb_correction(obs,
pb_sensitivity_curve,
cutoff_radius):
"""
Updates the primary beam response maps for cleaned images in an ObsInfo object.
Args:
obs (ObsInfo): Observation to generate maps for.
pb_sensitivity_curve: Primary beam se... | 5,354,724 |
def makeLoadParams(args):
"""
Create load parameters for start load request out of command line arguments.
Args:
args (dict): Parsed command line arguments.
"""
load_params = {'target': {},
'format': {'date_time': {},
'boolean': {}},
... | 5,354,725 |
def main(argv=None):
"""
Steps if script is run directly
"""
if argv is None:
argv = sys.argv
parser = argparse.ArgumentParser(
prog='getawscreds.py',
description=HELP_MESSAGE,
)
# Determine verbosity (optional argument)
parser.add_argument(
"-v", "--... | 5,354,726 |
def empty_hash():
"""Initialize empty hash table."""
from hash import HashTable
test_hash = HashTable()
return test_hash | 5,354,727 |
def denoise_sim(image, std, denoiser):
"""Simulate denoising problem
Args:
image (torch.Tensor): image tensor with shape (C, H, W).
std (float): standard deviation of additive Gaussian noise
on the scale [0., 1.].
denoiser: a denoiser instance (as in algorithms.denoiser).
... | 5,354,728 |
def _find_weektime(datetime, time_type='min'):
"""
Finds the minutes/seconds aways from midnight between Sunday and Monday.
Parameters
----------
datetime : datetime
The date and time that needs to be converted.
time_type : 'min' or 'sec'
States whether the time difference shoul... | 5,354,729 |
def test_calculator_get_result_method():
"""Testing the Calculator"""
calculator = Calculator()
assert calculator.get_result() == 0 | 5,354,730 |
def linear_to_image_array(pixels:List[List[int]], size:Tuple[int,int]) -> np.ndarray:
"""\
Converts a linear array ( shape=(width*height, channels) ) into an array
usable by PIL ( shape=(height, width, channels) )."""
a = np.array(pixels, dtype=np.uint8)
split = np.split(pixels, [i*size[0] for i in range(1,... | 5,354,731 |
def stop_processes(hosts, pattern, verbose=True, timeout=60):
"""Stop the processes on each hosts that match the pattern.
Args:
hosts (list): hosts on which to stop the processes
pattern (str): regular expression used to find process names to stop
verbose (bool, optional): display comma... | 5,354,732 |
def test_user_edit_post_minimal_values(client, logged_in_dummy_user):
"""Test posting to the user edit page: /user/<username>/settings/profile/
with the bare minimum of values """
with fml_testing.mock_sends(
UserUpdateV1(
{
"msg": {
"agent": "dumm... | 5,354,733 |
def field_as_table_row(field):
"""Prints a newforms field as a table row.
This function actually does very little, simply passing the supplied
form field instance in a simple context used by the _field_as_table_row.html
template (which is actually doing all of the work).
See soc/templates/soc/templatetags/_... | 5,354,734 |
def get_samples(select_samples: list, avail_samples: list) -> list:
"""Get while checking the validity of the requested samples
:param select_samples: The selected samples
:param avail_samples: The list of all available samples based on the range
:return: The selected samples, verified
"""
# S... | 5,354,735 |
def createMemoLayer(type="", crs=4326, name="", fields={"id":"integer"}, index="no"):
"""
Créer une couche en mémoire en fonction des paramètres
:param type (string): c'est le type de geometrie "point", "linestring",
"polygon", "multipoint","multilinestring","multipolygon"
:par... | 5,354,736 |
def draw_arc(arc):
"""draw arc"""
xy = (arc.center.x, arc.center.y)
start = 0
end = 0
if arc.start_angle < arc.end_angle:
start = arc.start_angle / math.pi * 180
end = arc.end_angle / math.pi * 180
else:
end = arc.start_angle / math.pi * 180
start = arc.end_angle ... | 5,354,737 |
def load_templates(package):
"""
Returns a dictionary {name: template} for the given instrument.
Templates are defined as JSON objects, with stored in a file named
"<instrument>.<name>.json". All templates for an instrument should
be stored in a templates subdirectory, made into a package by inclu... | 5,354,738 |
def get_count_matrix(args):
"""首先获取数据库中全部文档的id,然后遍历id获取文档内容,再逐文档
进行分词,生成计数矩阵。"""
global DOC2IDX
with DocDB(args.db_path) as doc_db:
doc_ids = doc_db.get_doc_ids()
DOC2IDX = {doc_id: i for i, doc_id in enumerate(doc_ids)}
row, col, data = [], [], []
_count = partial(count, args)
... | 5,354,739 |
def communication_round(model, clients, train_data, train_labels, train_people, val_data, val_labels, val_people,
val_all_labels, local_epochs, weights_accountant, individual_validation, local_operation):
"""
One round of communication between a 'server' and the 'clients'. Each client 'd... | 5,354,740 |
def _find_stop_area_mode(query_result, ref):
""" Finds the mode of references for each stop area.
The query results must have 3 columns: primary key, foreign key
reference and number of stop points within each area matching that
reference, in that order.
:param ref: Name of the ref... | 5,354,741 |
def get_all_funds_ranking(fund_type: str = 'all',
start_date: str = '-1y',
end_date: str = arrow.now(),
sort: str = 'desc',
subopts: str = '',
available: str = 1):
"""Get all funds ranki... | 5,354,742 |
def transfer_from_iterable(
grm: util.PathLike,
data: Iterable[str],
**kwargs: Any) -> Iterator[interface.Response]:
"""
Transfer from each MRS in *data* with ACE using grammar *grm*.
Args:
grm (str): path to a compiled grammar image
data (iterable): source MRSs as S... | 5,354,743 |
def recovermarks():
"""Walk through the tags made by ``colormarks`` and re-create the marks that were found.
This is useful if any marks were accidentally deleted and can be used for
recovering them as long as they were initally tagged properly.
"""
# collect
result = []
for fn, l in databa... | 5,354,744 |
async def test_setting_attribute_via_mqtt_json_message(hass, mqtt_mock):
"""Test the setting of attribute via MQTT with JSON payload."""
await help_test_setting_attribute_via_mqtt_json_message(
hass, mqtt_mock, binary_sensor.DOMAIN, DEFAULT_CONFIG
) | 5,354,745 |
def exec_anaconda():
"""Re-execute the current Python script using the Anaconda Python
interpreter included with Splunk_SA_Scientific_Python.
After executing this function, you can safely import the Python
libraries included in Splunk_SA_Scientific_Python (e.g. numpy).
Canonical usage is to put th... | 5,354,746 |
def _conform_list(li: List[Any]) -> List[T]:
"""
Ensures that every element in *li* can conform to one type
:param li: list to conform
:return: conformed list
"""
conform_type = li[0].__class__
for i in li:
if isinstance(i, StrictType):
conform_type = i.__class__
... | 5,354,747 |
def _255_to_tanh(x):
"""
range [0, 255] to range [-1, 1]
:param x:
:return:
"""
return (x - 127.5) / 127.5 | 5,354,748 |
def read_content(filename):
"""Read content and metadata from file into a dictionary."""
# Read file content.
text = fread(filename)
# Read metadata and save it in a dictionary.
date_slug = os.path.basename(filename).split('.')[0]
match = re.search('^(?:(\\d\\d\\d\\d-\\d\\d-\\d\\d)-)?(.+)$', da... | 5,354,749 |
def helm_commands():
"""Helm commands group.""" | 5,354,750 |
def train_one_epoch(train_loader, model, criterion, optimizer, epoch, opt, num_train_samples, no_acc_eval=False):
""" model training
:param train_loader: train dataset loader
:param model: model
:param criterion: loss criterion
:param optimizer:
:param epoch: current epoch
... | 5,354,751 |
def _d3hw_id_map(item, id_map, id_counter, is_unit):
"""
Assigns numeric ID for each unit, port and edge
Fills in string ID to numeric ID map
Replaces string ID with numeric
Sets maxID for unit meta
:param item: unit, port or edge
:param id_map: dict with mapping string ids to numeric ids
... | 5,354,752 |
def Write(Variable, f):
"""Function to Convert None Strings to Strings and Format to write to file with ,"""
import datetime
if isinstance(Variable, str) == False:
if isinstance(Variable, datetime.datetime) == True:
return f.write(f"{Variable.strftime('%Y-%m-%d')},")
else:
... | 5,354,753 |
def graphs_infos():
"""
Build and return a JSON file containing some information on all the graphs.
The json file is built with the following format:
[
For each graph in the database :
{
'graph_id': the id of the graph,
'name': the name of the graph,
'iso'... | 5,354,754 |
def collect_compare(left, right):
"""
returns a tuple of four lists describing the file paths that have
been (in order) added, removed, altered, or left the same
"""
return collect_compare_into(left, right, [], [], [], []) | 5,354,755 |
def runSuite(suiteparam, testrun, testid):
""" Runs the whole test suite, main entry
Args:
suiteparam : RunSuiteParam container
testrun: following values possible: one, all or from
testid: test case to run (for 'one' or 'from')
Returns:
nothing
Raises:
Exception... | 5,354,756 |
def test_response_failure_initialisation_with_exception(response_type: str) -> None:
"""It builds a ResponseFailure from exception."""
response = res.ResponseFailure(response_type, Exception("Just an error message"))
assert bool(response) is False
assert response.type == response_type
assert respon... | 5,354,757 |
def _get_smallest_vectors(supercell, primitive, symprec):
"""
shortest_vectors:
Shortest vectors from an atom in primitive cell to an atom in
supercell in the fractional coordinates. If an atom in supercell
is on the border centered at an atom in primitive and there are
multiple vectors... | 5,354,758 |
def root():
"""Root endpoint that only checks if the server is running."""
return 'Server is running...' | 5,354,759 |
def _PGProperty_SetAttributes(self, attributes):
"""
Set the property's attributes from a Python dictionary.
"""
for name,value in attributes.items():
self.SetAttribute(name, value) | 5,354,760 |
def clone_model(model, **new_values):
"""Clones the entity, adding or overriding constructor attributes.
The cloned entity will have exactly the same property values as the
original entity, except where overridden. By default, it will have no
parent entity or key name, unless supplied.
Args:
... | 5,354,761 |
def describe_project(projectId=None, syncFromResources=None):
"""
Gets details about a project in AWS Mobile Hub.
See also: AWS API Documentation
Exceptions
:example: response = client.describe_project(
projectId='string',
syncFromResources=True|False
)
:t... | 5,354,762 |
def learn_laterals(frcs, bu_msg, perturb_factor, use_adjaceny_graph=False):
"""Given the sparse representation of each training example,
learn perturbation laterals. See train_image for parameters and returns.
"""
if use_adjaceny_graph:
graph = make_adjacency_graph(frcs, bu_msg)
graph = ... | 5,354,763 |
def get_info(ingest_ldd_src_dir):
"""Get LDD version and namespace id."""
# look in src directory for ingest LDD
ingest_ldd = find_primary_ingest_ldd(ingest_ldd_src_dir)
# get ingest ldd version
tree = ETree.parse(ingest_ldd[0])
root = tree.getroot()
ldd_version = root.findall(f'.//{{{PDS_N... | 5,354,764 |
def generate_tfidf(corpus_df, dictionary):
"""Generates TFIDF matrix for the given corpus.
Parameters
----------
corpus_df : pd.DataFrame
The corpus dataframe.
dictionary : gensim.corpora.dictionary.Dictionary
Dictionary defining the vocabulary of the TFIDF.
Returns
-------... | 5,354,765 |
def load_config_file(file_path, fallback_file_path):
"""Load YAML format configuration file
:param file_path: The path to config file
:type file_path: `str`
:param fallback_file_path: The fallback path to config file
:type fallback_file_path: `str`
:return: config_map
:rtype: dict
"""
... | 5,354,766 |
def compute_mask_indices(
shape: Tuple[int, int],
padding_mask: Optional[torch.Tensor],
mask_prob: float,
mask_length: int,
mask_type: str = "static",
mask_other: float = 0.0,
min_masks: int = 0,
no_overlap: bool = False,
min_space: int = 0,
) -> n... | 5,354,767 |
def main():
"""Queries PanelApp, checks Moka database and imports Moka PanelApp panels.
Args:
args (list): A list of command-line arguments. e.g. ['-c', 'config.ini']
"""
# Read server details from config file
_args = lib.cli(sys.argv[1:])
db_config = _args.config['mokadb']
... | 5,354,768 |
async def test_single_get(currencies: Currencies, symbol_from: str, symbol_to: str):
"""
>>> from aiocrypto_prices import currencies
>>> await currencies.ETH.prices.get('USD')
1053.28
"""
resp = await getattr(currencies, symbol_from).prices.get(symbol_to)
assert isinstance(resp, float) | 5,354,769 |
def test_double_linked_list_pop_shifts_head_properly(dll_fixture):
"""Test pop shifts head."""
dll_fixture.push('potato')
dll_fixture.push('cabbage')
dll_fixture.pop()
assert dll_fixture.head.data == 'potato' | 5,354,770 |
def _rankingmap_mpl(countrymasksnc, ranking, x, scenario=None, method='number', title='', label=''):
"""
countrymasksnc : nc.Dataset instance of countrymasks.nc
ranking: Ranking instance
method: "number" (default) or "value"
"""
import matplotlib.pyplot as plt
import numpy as np
if meth... | 5,354,771 |
def test_sent_entities(sent_loader):
"""Test getting Entities from a Sentinel Incident."""
responses.add(
responses.POST,
re.compile("https://management.azure.com/.*"),
json={"entities": [{"kind": "ipv4", "properties": "13.67.128.10"}]},
status=200,
)
ents = sent_loader.g... | 5,354,772 |
def pathpatch_2d_to_3d_affine(pathpatch, mat_rot=np.array([[1,0,0],[0,1,0],[0,0,1]]), vec_trans=np.array([0,0,0])):
"""
Transforms a 2D Patch to a 3D patch using the affine tranform
of the given rotation matrix and translation vector.
The pathpatch is assumed to be on the plane Z = 0.
"""
... | 5,354,773 |
def fetch_data(
property: Property,
start_date: dt.date,
*,
end_date: Optional[dt.date] = None,
dimensions: Optional[List[Dimension]] = None,
) -> List[Dict[str, Any]]:
"""Query Google Search Console API for data.
Args:
property (Property): Property to request data for.
star... | 5,354,774 |
def fileOpenDlg(tryFilePath="",
tryFileName="",
prompt=_translate("Select file to open"),
allowed=None):
"""A simple dialogue allowing read access to the file system.
:parameters:
tryFilePath: string
default file path on which to open the dia... | 5,354,775 |
def inport(port_type, disconnected_value):
"""Marks this field as an inport"""
assert port_type in port_types, \
"Got %r, expected one of %s" % (port_type, port_types)
tag = "inport:%s:%s" % (port_type, disconnected_value)
return tag | 5,354,776 |
def Align(samInHandle, fa, id, position, varId, refseq, altseq, mapq = 20):
"""
position is the left break point of the variants
And the position should be 1-base for convenience.
Because I use something like fa[id][position-1] to get bases from fa string
"""
if position < 1:
raise Val... | 5,354,777 |
def _empty_aggregate(*args: npt.ArrayLike, **kwargs) -> npt.ArrayLike:
"""Return unchaged array."""
return args[0] | 5,354,778 |
def kfpartial(fun, *args, **kwargs):
""" Allows to create partial functions with arbitrary arguments/keywords """
return partial(keywords_first(fun), *args, **kwargs) | 5,354,779 |
def test_post_an_margin_order_without_symbol():
"""Tests the API endpoint to post a new margin order without symbol"""
client = Client(key, secret)
client.new_margin_order.when.called_with(
symbol="", side="SELL", type="LIMIT", quantity=0.02
).should.throw(ParameterRequiredError) | 5,354,780 |
def test_extract_subgraph_default_edge_weight(property_graph_instance):
"""
Ensure the default_edge_weight value is added to edges with missing
properties used for weights.
"""
pG = property_graph_instance
selection = pG.select_edges("_TYPE_=='transactions'")
G = pG.extract_subgraph(create_... | 5,354,781 |
def power_state_update(system_id, state):
"""Report to the region about a node's power state.
:param system_id: The system ID for the node.
:param state: Typically "on", "off", or "error".
"""
client = getRegionClient()
return client(
UpdateNodePowerState,
system_id=system_id,
... | 5,354,782 |
def load_apigateway_locations_tx(
tx: neo4j.Transaction, locations: List[Dict],
project_id: str, gcp_update_tag: int,
) -> None:
"""
Ingest GCP Project Locations into Neo4j
:type neo4j_session: Neo4j session object
:param neo4j session: The Neo4j session object
:type locati... | 5,354,783 |
def draw_piechart(question_info, explode, path):
"""Draw pie chart of each question.
:param: question_info is a list of users. eg: [12, 23, 43, 13]
means 12 people select A, 23 select B, 43 C, 13 D.
"""
labels = 'A', 'B', 'C', 'D'
colors = ['yellowgreen', 'gold', 'lightskyblue', 'light... | 5,354,784 |
def build_post307_request(*, json: Any = None, content: Any = None, **kwargs: Any) -> HttpRequest:
"""Post redirected with 307, resulting in a 200 after redirect.
See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder
into your code flow.
:keyword json: Pass in... | 5,354,785 |
def rm_ssp_storage(ssp_wrap, lus, del_unused_images=True):
"""Remove some number of LogicalUnits from a SharedStoragePool.
The changes are flushed back to the REST server.
:param ssp_wrap: SSP EntryWrapper representing the SharedStoragePool to
modify.
:param lus: Iterable of LU ElementWrappers or ... | 5,354,786 |
def urp_detail_view(request, pk):
"""Renders the URP detail page
"""
urp = get_object_or_404(URP, pk=pk)
ctx = {
'urp': urp,
}
# if user is logged in as a student, check if user has already applied
if request.user.is_authenticated:
if request.user.uapuser.is_student:
... | 5,354,787 |
def squeeze_excite(input_name, squeeze_factor):
"""Returns a squeeze-excite block."""
ops = []
append = functools.partial(append_op, ops)
append(op_name="se/pool0",
op_type=OpType.AVG_POOL,
input_kwargs={"window_shape": 0},
input_names=[input_name])
append(op_name="se/dense1",
... | 5,354,788 |
def get_code_v2(fl = r'C:\Users\bogdan\code_seurat\WholeGenome_MERFISH\Coordinates_code_1000region.csv'):
"""
Given a .csv file with header this returns 2 dictionaries: tad_to_PR,PR_to_tad
"""
lst = [(ln[:-1].split(',')[0].replace('__','_'),['R'+R for R in ln[:-1].split(',')[3].split('--')])
for ln... | 5,354,789 |
def print_update_decks_help(fd):
"""Print the 'update-decks' command usage to the file descriptor."""
w = fd.write
w("Command 'update-decks':\n")
w(" Check if any decks are out-of-date (using etags)")
w(" and pull in the changes as needed.\n")
w("\n")
exe = os.path.basename(sys.argv[0])
... | 5,354,790 |
def run_source_lsq(vars, vs_list=vs_list):
"""
Script used to run_source and return the output file.
The function is called by AdaptiveLejaPCE.
"""
from funcs.modeling_funcs import modeling_settings, generate_observation_ensemble
import spotpy as sp
print('Read Parameters')
parameters = ... | 5,354,791 |
def finnegans_wake_unicode_chars():
"""Data fixture that returns a string of all unicode characters in Finnegan's Wake."""
return '¤·àáãéìóôþŒŠŸˆ–—‘’‚“”‡…‹' | 5,354,792 |
def get_upload(upload_key: UploadPath = Path(..., description="上传文件块位置")):
"""
获取文件上传目录
:param upload_key:
:return:
"""
root_path = posixpath.abspath(UPLOAD_PATH_DICT[upload_key])
def func(folder):
path = security.safe_join(root_path, folder)
os.makedirs(path, exist_ok=Tr... | 5,354,793 |
def kit(): # simpler version
"""Open communication with the dev-kit once for all tests."""
return usp.Devkit() | 5,354,794 |
def run_batch_import(jobs: Dict[Future, str], impl, ctx, db):
"""
Run a batch of import jobs using threading and process the results
"""
# Run the threads
with ThreadPoolExecutor(max_workers=config['batch_size']) as executor:
# Dictionary of {future: accession}
# Following this examp... | 5,354,795 |
def givens_rotation(A):
"""Perform QR decomposition of matrix A using Givens rotation."""
(num_rows, num_cols) = np.shape(A)
# Initialize orthogonal matrix Q and upper triangular matrix R.
Q = np.identity(num_rows)
R = np.copy(A)
# Iterate over lower triangular matrix.
(rows, cols) = np.tr... | 5,354,796 |
def test_suggest_add_no_netixlan(entities, capsys):
"""
There isn't any netixlan between ix and network.
Network does not have automatic updates.
There isn't a local-ixf that matches the remote-ixf.
We create local-ixf[as,ip4,ip6] and email the network
but don't create a ticket or email the IX.
... | 5,354,797 |
async def test_ssdp_discovery_confirm_abort(hass: HomeAssistantType) -> None:
"""Test we handle SSDP confirm cannot connect error."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={CONF_SOURCE: SOURCE_SSDP},
data={ATTR_SSDP_LOCATION: SSDP_LOCATION, ATTR_UPNP_SERIAL:... | 5,354,798 |
def lex_from_str(
*,
in_str: Union[str, Path],
grammar: str = "standard",
ir_file: Optional[Union[str, Path]] = None,
) -> JSONDict:
"""Run grammar of choice on input string.
Parameters
----------
in_str : Union[str, Path]
The string to be parsed.
grammar : str
Gra... | 5,354,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.