content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def main(manager: Optional[Manager] = None):
"""Load BEL."""
if manager is None:
manager = Manager()
upload_bel_directory(alzheimer_directory, manager) | 43,000 |
def trsh_job_on_server(server: str,
job_name: str,
job_id: Union[int, str],
job_server_status: str,
remote_path: str,
server_nodes: list = None):
"""
Troubleshoot server errors.
Args:
... | 43,001 |
def get_native_backend_config_dict():
""" Get backend_config_dict for PyTorch Native backend (fbgemm/qnnpack). """
binary_op_dtype_configs = [
weighted_op_int8_dtype_config,
default_op_fp16_dtype_config,
]
share_qparams_op_dtype_configs = [
default_op_quint8_dtype_config,
... | 43,002 |
def dummy_content_widget(title='Dummy Content Widget', content="Dummy Content",
slug="dummy_content_widget", is_published=True):
"""Will directly write to the database a dummy content widget for our
tests.
Parameters
----------
title : str
Widget title.
content... | 43,003 |
def get_ckpt_epoch(ckpt_dir):
"""Get checkpoint epoch"""
ckpt_epoch = {}
files = os.listdir(ckpt_dir)
if not files:
print("No ckpt files")
return None, None
for file_name in files:
file_path = os.path.join(ckpt_dir, file_name)
if os.path.splitext(file_path)[1] == '.... | 43,004 |
def shed_serve(ctx, install_args_list, **kwds):
"""Serve a daemon instance of Galaxy with specified repositories installed."""
with serve_daemon(ctx, **kwds) as config:
install_deps = not kwds.get("skip_dependencies", False)
io.info("Installing repositories - this may take some time...")
... | 43,005 |
def ask_note():
"""Function to ask user for task notes"""
task_note = input("Enter any additional task notes here >")
return task_note | 43,006 |
def test_loader_metric():
"""Check that LoaderMetric doesn't store grads and results are on cpu to avoid memory leak"""
clb = pt_clb.LoaderMetrics(TEST_METRIC)
runner = Runner(model=TEST_MODEL, optimizer=TEST_OPTIMIZER, criterion=TEST_CRITERION, callbacks=clb)
runner.fit(TEST_LOADER, epochs=2)
asser... | 43,007 |
def test_tags(qisrc_action, git_server):
""" Test Tags """
git_server.create_repo("foo.git")
git_server.push_file("foo.git", "a.txt", "a")
git_server.push_tag("foo.git", "v0.1")
git_server.push_file("foo.git", "b.txt", "b")
git_server.set_fixed_ref("foo.git", "v0.1")
qisrc_action("init", git... | 43,008 |
def mkdir_for_girl(f_path):
"""
创建以标题命令的目录
:param f_path: 文件根路径
:return: 返回创建的目录路径
"""
if not os.path.exists(f_path):
os.mkdir(f_path)
return f_path | 43,009 |
def install_salt(installer="ppa"):
"""
Install salt with the chosen installer.
"""
if installer == "ppa":
run("echo deb http://ppa.launchpad.net/saltstack/salt/ubuntu `lsb_release -sc` main | \
sudo tee /etc/apt/sources.list.d/saltstack.list")
key_url = "http://keyserver.ubu... | 43,010 |
def main(prmtop_file, mdcrd_traj_file, inpcrd_file, get_B = False, target_length=15, cluster_size = 10, simplify_only = False, rod=None, radius = 5e-9, rod_out=None, unroll_rod=True, get_inhomogenous_beta=False, get_inhomogenous_kappa=False):
"""
For an atomistic trajectory, this will create an equivalent rod t... | 43,011 |
def test_anscombe():
"""Test anscombe function."""
# https://en.wikipedia.org/wiki/Anscombe_transform
data = rng.poisson(100, (128, 128, 128))
assert_almost_equal(data.mean(), 100, 1), "Data not generated properly!"
ans_data = anscombe(data)
assert_almost_equal(ans_data.var(), 1, 2)
in_ans_d... | 43,012 |
def Yt_1d_full():
"""
1d Yt fully observed
"""
y = np.array([[[2]], [[1.3]], [[2.5]], [[3.1]]])
return y | 43,013 |
def threshold_isodata(image, nbins=256, shift=None, max_limit=None, min_limit=None):
"""Return threshold value based on ISODATA method.
Histogram-based threshold, known as Ridler-Calvard method or intermeans.
Parameters
----------
image : array
Input image.
nbins : int, optional
... | 43,014 |
def populate_task_view(request):
"""
populate project_task view
"""
project_id = request.GET.get('project_id')
project_name = request.GET.get('project_name')
template = loader.get_template('project_management/add_project_tasks.html')
project = Project.objects.get(id=int(project_id))
sta... | 43,015 |
def cleanup_queryset(queryset):
"""
Remove multiple joins on the same table, if any
WARNING: can alter the origin queryset order
"""
return queryset.model.objects.filter(pk__in=[instance.pk for instance in queryset.all()]) | 43,016 |
def svn_diff_output_fns_invoke_output_conflict(*args):
"""
svn_diff_output_fns_invoke_output_conflict(svn_diff_output_fns_t _obj, void output_baton, apr_off_t original_start,
apr_off_t original_length,
apr_off_t modified_start, apr_off_t modified_length,
apr_off_t latest_start, apr_off_... | 43,017 |
def capacity_factors():
"""
This function generates a hard-coded dictionary
containing the capacity factors for different fuels
and movers. The values are defaulted to 1.0 if no
capacity factor information can be found. The
numbers are specific to the 2018 year and may lead
to innacurate res... | 43,018 |
def get_chunk_of_encodings(db, dp_id, entity_ids, stored_binary_size=132):
"""Yields raw byte encodings for a data provider given the encoding ids.
:param dp_id: Fetch encodings from this dataprovider (encoding ids are not unique across data providers).
:param entity_ids: List of ints of the entity ids to ... | 43,019 |
def _is_greater(list1: list, list2: list):
"""
return True if `list1[i] > list2[i]` for each `i`
"""
return all([list1[i] > list2[i] for i in range(len(list1))]) | 43,020 |
def isenabled(handle):
"""Return True if the window is enabled"""
return bool(win32functions.IsWindowEnabled(handle)) | 43,021 |
def test_all_commandline():
"""
Tests that alignment works properly using a string of arguments.
"""
base_dir = os.path.join(os.path.dirname(__file__), '..', 'aux_data')
sample_dir = os.path.join(base_dir, test_reference, "samples_METs_small")
output_dir = os.path.join(base_dir, "test_out_R")
... | 43,022 |
def monte_carlo(d):
"""
Calculate Monte Carlo value for π.
Arguments:
d: list of unsigned byte values.
Returns:
Approximation of π as Decimal
"""
MONTEN = 6
incirc = Decimal((256.0 ** (MONTEN // 2) - 1) ** 2)
d = (Decimal(j) for j in d[: len(d) // MONTEN * MONTEN])
... | 43,023 |
def verifyIfRepo(dirName):
"""
"""
dbPath = getDbPath(dirName)
print dbPath
try:
if verifyShelveVersionCompatibility(dbPath):
return True
else:
return False
except:
return False | 43,024 |
def machine_setter(_latfile=None, _machine=None, _handle_name=None):
""" set flame machine, prefer *_latfile*
:return: FLAME machine object
"""
if _latfile is not None:
try:
with open(_latfile, 'rb') as f:
m = Machine(f)
except:
if _machine is Non... | 43,025 |
def vgg_preprocess_images(image_tensor):
"""
:param image_tensor: float 32 array of Batch x Height x Width x Channel immages (range 0 - 1)
:return: pre-processed images (ready to input to VGG)
"""
vgg_mean = tf.convert_to_tensor(np.array([103.939, 116.779, 123.68], dtype=np.float32))
red, green,... | 43,026 |
def main(
version: Optional[bool] = typer.Option(
None, "--version", "-v", callback=version_callback, is_eager=True
),
):
"""Adjusts Australian dollars for inflation or returns interpolated socio-economic indices for Victorian suburbs."""
pass | 43,027 |
def delete_media_files(media):
"""
Delete all files associated with a MediaEntry
Arguments:
- media: A MediaEntry document
"""
no_such_files = []
for listpath in six.itervalues(media.media_files):
try:
mg_globals.public_store.delete_file(
listpath)
... | 43,028 |
def get_coordinates(ds: xr.Dataset, uri: str = '') -> t.Iterator[t.Dict]:
"""Generates normalized coordinate dictionaries that can be used to index Datasets with `.loc[]`."""
# Creates flattened iterator of all coordinate positions in the Dataset.
#
# Coordinates have been pre-processed to remove NaNs a... | 43,029 |
def computeIntCorrections(npix,factor):
"""Compute `newnpix` and `newfactor` such that `npix_new` is the
nearest odd-valued integer to ``npix*factor``.
Parameters
----------
npix : int
Odd-valued integer.
factor : float
Multiplicative factor.
Returns
-------
newn... | 43,030 |
def LU_factor(A,LOUD=True):
"""Factor in place A in L*U=A. The lower triangular parts of A
are the L matrix. The L has implied ones on the diagonal.
Args:
A: N by N array
Returns:
a vector holding the order of the rows, relative to the original order
Side Effects:
A is fact... | 43,031 |
def get_zvals_from_grid(line,xyzgrid):
""" Input: line (LineString or ARRAY with first two columns the xy coords)
get z values at every point in line from xyzgrid
xyzgrid: DataFrame with x,y,z columns or 3 column ARRAY
returns: array of z values for each point on line """
#create dataframe if np.arra... | 43,032 |
def HBIh(time, gsd = None, gh = None):
"""
paras
gsd: optional
Conductance of slow depolarizing
gh : optional
Return
Var_t : action potential
"""
def HyB(Var,t,tempF):
[rrho,pphi] = tempF
[v,ar,asd,ca,ah]=Var
ad = 1/(... | 43,033 |
def discovery(uri="", data_format="json"):
"""
Method description:
Deletes/Unregisters an application entity(AE) from the OneM2M framework/tree
under the specified CSE
Parameters:
uri_cse : [str] URI of parent CSE
ae_name : [str] name of the AE
fmt_ex : [str] payload format
"""
... | 43,034 |
async def test_map_two_iterables_expected_result(
arange: ty.Type[ty.AsyncIterator[int]], stop: int
):
"""Look for expected results which should returned by
:class:`none.collection.a.map` with two iterables given.
"""
async def _add(a: int, b: int) -> int:
return a + b
async for i, x ... | 43,035 |
def expand_command(cmd):
"""
Expand command by
replacing all substitutions ('{{...}}')
and wildcards ('*')
Args:
cmd (str): command where * will be replaced
Yields:
str. Command
"""
if cmd is not None:
check_command(cmd)
for s in expand_substitutions(cm... | 43,036 |
def dijkstra_search(problem):
"""
Best first search that uses g(n) to evaluate cost
:param problem:
:return: final node
"""
return best_first_graph_search(problem, lambda n: n.path_cost) | 43,037 |
def _get_pair_nodes(root_node):
"""
Internal method to get "pair" nodes under root_node
"""
method_elem = root_node
in_configs_elem_list = method_elem.getElementsByTagName("inConfigs")
in_configs_elem = in_configs_elem_list[0]
pair_elems_list = in_configs_elem.getElementsByTagName("pair")
... | 43,038 |
def test_distance_matrix_generation():
"""Check the generation of a proper distance matrix"""
# prepare
locations = [
[10, 10],
[10, 12],
[100, 500],
[22, 30]
]
# act
locations_distances_result = generate_distance_matrix(locations)
# assert
enumerated_l... | 43,039 |
def ngrams(
sequence,
n,
pad_left = False,
pad_right = False,
left_pad_symbol = None,
right_pad_symbol = None,
):
"""
generate ngrams.
Parameters
----------
sequence : list of str
list of tokenize words.
n : int
ngram size
Returns
-------
ngr... | 43,040 |
def get_string(message="Enter your response", title="Title",
default_response=""):
"""Simple text input box. Used to query the user and get a string back.
:param message: Message displayed to the user, inviting a response
:param title: Window title
:param default_response: defa... | 43,041 |
def has_ao_2e_int_eri_lr(trexio_file) -> bool:
"""Check that ao_2e_int_eri_lr variable exists in the TREXIO file.
Parameter is a ~TREXIO File~ object that has been created by a call to ~open~ function.
Returns:
True if the variable exists, False otherwise
Raises:
- Exception from tr... | 43,042 |
def corelucy(image, h):
"""
Make core for the LR estimation. Calculates f to produce the next
iteration array that maximizes the likelihood that the entire suite
satisfies the Poisson statistics.
This is a simplified version of MATLAB corelucy function without
damping, weights and externally def... | 43,043 |
def convert_to_bipartite(S):
"""
convert a standard stoichiometric matrix (in a Pandas DataFrame)
to a bipartite graph with an edge between every reactant and all its
reactions
"""
# convert the stoichiometric matrix to a sparse representation
S_sparse = pd.melt(S.reset_index(),
... | 43,044 |
def proj_l1_neg_tan_cone(u, v):
"""
Project u onto the negative tangent cone of l1 ball with diameter ||v||_1
at v. It's actually the tangent cone of l1 ball with bound ||v||_1 at -v.
@param u: the vector to calculate projection from.
@param v: the vector at whom the tangent cone forms.
... | 43,045 |
def reset_ranks_to_normal(dataframe: pd.DataFrame) -> None:
"""
This function calls the Set old ranks to normal function from wikidata uploader,
it goes through each settlement resetting its historic values to "Normal Rank"
subsequently, the upload sets the most recent population values to "Preferred Ra... | 43,046 |
def generate(prompt: str, context: str) -> str:
"""Generates a response for the given prompt and context.
:param prompt: The prompt to generate a response for.
:type prompt: str
:param context: The context to generate a response for.
:type context: str
:return: The generated response.
:rtyp... | 43,047 |
def fista(input_size, eval_fun, regulariser,
regulariser_function=None, thresholding_function=None, initial_x=0,
L0=1., eta=2., update_L=True,
verbose=1, verbose_output=0):
"""
FISTA (Fast Iterative Shrinkage Thresholding Algorithm) is an algorithm to solve the convex minimization ... | 43,048 |
def __ldns_pkt_set_question(*args):
"""LDNS buffer."""
return _ldns.__ldns_pkt_set_question(*args) | 43,049 |
def test_storage_get_timer(
storage: RepositoryStorage, url: URL, timer: FakeTimer
) -> None:
"""It updates the timestamp."""
record_0 = storage.allocate(url, provider="git")
timer.tick()
record = storage.get(url, provider="git")
assert record is not None
assert record.updated == timer.now
... | 43,050 |
def study2Pipeline(pairData):
"""Compute the data for the second part of the study
This will generate a list of PDFs permitting to visualize the dataset
@param pairData the data of pairs of participants"""
#Get the pointingData and the maximum axis for the TCT values
pointingData = {}
maxAxisTC... | 43,051 |
def get_nick(infraction_id: int, member_id: int) -> str:
"""Randomly select a nickname from the Superstarify nickname list."""
rng = random.Random(str(infraction_id) + str(member_id))
return rng.choice(STAR_NAMES) | 43,052 |
def find_best_path(starting):
"""Find the best moves using A*"""
@dataclass(order=True)
class PrioritizedState:
"""Dataclass to insert the RoomStates into the priority queue"""
cost: int
config: RoomState=field(compare=False)
open_set = PriorityQueue()
open_set.put(Priorit... | 43,053 |
def Shard(ilist, shard_index, num_shards):
"""Shard a given list and return the group at index |shard_index|.
Args:
ilist: input list
shard_index: 0-based sharding index
num_shards: shard count
"""
chunk_size = len(ilist) / num_shards
chunk_start = shard_index * chunk_size
if shard_index == num... | 43,054 |
def get_oof_pred(
model: Any,
X_train: pd.DataFrame,
y_train: pd.Series,
X_test: pd.DataFrame,
n_fold: int,
) -> Tuple[np.ndarray, np.ndarray]:
"""
Get Out of Fold prediction for both training and testing dataset
Args:
model (Any): Any model class which have `fit` and `predict` m... | 43,055 |
def venv_init():
"""Creates virtual environment using subprocess module"""
current_os = get_os()
print(creating_venv_str())
if current_os == 'linux':
init_venv_process = subprocess.run(
['python3', '-m', 'venv', 'venv'], capture_output=True)
else:
init_venv_process = sub... | 43,056 |
async def get_aes_key(password: str, settings: EncryptionSettings) -> bytes:
"""Returns the 32 byte system encryption key."""
assert isinstance(password, str)
assert isinstance(settings, EncryptionSettings)
return await decrypt_chunk(get_decryption_key(password, settings), settings.encrypted_key) | 43,057 |
def print_candidates(candidates):
"""후보자 명단을 출력한다."""
for candidate in candidates:
print(candidate) | 43,058 |
def nextpow2(value):
"""
Extracted from
caiman.source_extraction.cnmf.deconvolution import axcov
Find exponent such that 2^exponent is >= abs(value).
Parameters:
----------
value : int
Returns:
-------
exponent : int
"""
exponent = 0
avalue = np.abs(value)
while a... | 43,059 |
def workshopinquiry_accept_event(request, inquiry_id):
"""Accept workshop inquiry by creating a new event."""
wr = get_object_or_404(WorkshopInquiryRequest, state='p', pk=inquiry_id)
if request.method == 'POST':
form = EventCreateForm(request.POST)
if form.is_valid():
event = f... | 43,060 |
def create_rsa_key(password="123456"):
"""
创建RSA密钥,步骤说明:
1、从 Crypto.PublicKey 包中导入 RSA,创建一个密码(此密码不是RSA秘钥对)
2、生成 1024/2048 位的 RSA 密钥对(存储在私钥文件和公钥文件)
3、调用 RSA 密钥实例的 exportKey 方法(传入"密码"、"使用的 PKCS 标准"、"加密方案"这三个参数)得到私钥。
4、将私钥写入磁盘的文件。
5、使用方法链调用 publickey 和 exportKey 方法生成公钥,写入磁盘上的文件。
"""
key... | 43,061 |
def load_level_data():
"""Read the `level.dat` file and return the `Data` compound."""
try:
level_data = nbt.load(LEVEL_DATA_PATH, gzipped=True).root['Data']
except FileNotFoundError:
display_error(f'Couldn\'t find any "{LEVEL_DATA_PATH}" file. Are you '
'sure that the ... | 43,062 |
def separation_scorer(catalogue,name_TGSS,name_NVSS):
"""given two names, gives separation
by set-up, only gives non-zero for those in catalogue"""
if (name_TGSS,name_NVSS) in catalogue.index:
sep = catalogue.loc[name_TGSS,name_NVSS].separation
sep *= 3600
return max(0,(40-sep)/40)
... | 43,063 |
def mms_hpca_calc_anodes(fov=[0, 360], probe='1', suffix=''):
"""
This function will sum (or average, for flux) the HPCA data over the requested field-of-view (fov)
Parameters
----------
fov : list of int
field of view, in angles, from 0-360
probe : str
prob... | 43,064 |
def get_host_call_fn(model_dir):
"""`host_call` function for creating training summaries when using TPU."""
def host_call_fn(**kwargs):
"""Host_call_fn.
Args:
**kwargs: dict of summary name to tf.Tensor mapping. The value we see here
is the tensor across all cores, concatenated along axis 0.... | 43,065 |
def determine_horizons_id(lines, now=None):
"""Attempts to determine the HORIZONS id of a target body that has multiple
possibilities. The passed [lines] (from the .args attribute of the exception)
are searched for the HORIZONS id (column 1) whose 'epoch year' (column 2)
which is closest to [now] (a pas... | 43,066 |
def export_read_file(channel, start_index, end_index, bulkfile, output_dir, remove_pore=False):
"""Generate a read FAST5 file from channel and coordinates in a bulk FAST5 file
Parameters
----------
channel : int
channel number from bulk FAST5 file
start_index : int
start index for r... | 43,067 |
def escape_html(s: str)-> str:
"""
Escape html
:param str s: string
:return: replaced html-string
"""
s = s.replace('&','&')
s = s.replace('<','<')
s = s.replace( '>','>')
s = s.replace('"','"')
s = s.replace("'", ''')
return s | 43,068 |
def CSCH(*args) -> Function:
"""
The CSCH function returns the hyperbolic cosecant of any real number.
Learn more:
https//support.google.comhttps://support.google.com/docs/answer/9116336.
"""
return Function("CSCH", args) | 43,069 |
def test_use_positional_as_keyword1(a, /):
"""
>>> test_use_positional_as_keyword1(1)
>>> test_use_positional_as_keyword1(a=1) # doctest: +ELLIPSIS
Traceback (most recent call last):
TypeError: test_use_positional_as_keyword1() ... keyword arguments...
""" | 43,070 |
def mkt_gc(**kw):
"""Site-wide garbage collections."""
days_ago = lambda days: datetime.today() - timedelta(days=days)
log.debug('Collecting data to delete')
logs = (ActivityLog.objects.filter(created__lt=days_ago(90))
.exclude(action__in=amo.LOG_KEEP).values_list('id', flat=True))
for... | 43,071 |
def _download_to_file(url, pyfile):
"""
Downloads a single URL to a file.
"""
with contextlib.closing(urlopen(url)) as socket:
file_size = socket.info().get("Content-Length")
if file_size:
file_size = int(file_size)
# There is no guarantee that the content-length head... | 43,072 |
def _get_valid_name(proposed_name):
"""Return a unique slug name for a service"""
slug_name = slugify(proposed_name)
name = slug_name
if len(slug_name) > 40:
name = slug_name[:40]
return name | 43,073 |
def main():
"""Handle command-line arguments."""
from docopt import docopt
arguments = docopt(__doc__)
if arguments['pretty-print']:
pretty_print(arguments['<filename>'][0])
elif arguments['print-tag-value']:
filenames = arguments['<filename>']
if type(filenames) == str:... | 43,074 |
def test_atomic_time_max_exclusive_2_nistxml_sv_iv_atomic_time_max_exclusive_3_3(mode, save_output, output_format):
"""
Type atomic/time is restricted by facet maxExclusive with value
23:35:02.
"""
assert_bindings(
schema="nistData/atomic/time/Schema+Instance/NISTSchema-SV-IV-atomic-time-max... | 43,075 |
def create_pif(headers, row):
"""
Creates PIFs from lists of table row
:param headers: header data from the table
:param row: the row of data
:return: ChemicalSystem containing the data from that row
"""
sys_dict = {}
keywords, names, units, systs = get_header_info(headers)
sys_di... | 43,076 |
def update_user(old_email, new_email=None, password=None):
"""Update the email and password of the user.
Old_email is required, new_email and password are optional, if both parameters are
empty update_user() will do nothing. Not asking for the current password is
intentional, creating and updating are ... | 43,077 |
def get_text(text_node: Optional[ET.Element]) -> Optional[str]:
"""Return stripped text from node. None otherwise."""
if text_node is None:
return None
if not text_node.text:
return None
return text_node.text.strip() | 43,078 |
def function_d(d, d1, d2=1):
"""doc string"""
return d + d1 + d2 | 43,079 |
def qgs_access_control_filter():
"""
Mock some QgsAccessControlFilter methods:
- __init__ which does not accept a mocked QgsServerInterface;
- serverInterface to return the right server_iface.
"""
class DummyQgsAccessControlFilter:
def __init__(self, server_iface):
self.ser... | 43,080 |
def _assert_file_exist(filename):
"""Checks if a file exists."""
if not _exists_file(filename):
raise IOError("File, '{0}', does not exist.".format(filename)) | 43,081 |
def crawl(links=[], domains=[], delay=20.0, parse=HTMLLinkParser().parse, sort=FIFO, method=DEPTH, **kwargs):
""" Returns a generator that yields (Link, source)-tuples of visited pages.
When the crawler is idle, it yields (None, None).
"""
# The scenarios below defines "idle":
# - crawl(delay=10... | 43,082 |
def ppmv2pa(x, p):
"""Convert ppmv to Pa
Parameters
----------
x Gas pressure [ppmv]
p total air pressure [Pa]
Returns
-------
pressure [Pa]
"""
return x * p / (1e6 + x) | 43,083 |
def make_elastic_uri(schema: str, user: str, secret: str, hostname: str, port: int) -> str:
"""Make an Elasticsearch URI.
:param schema: the schema, e.g. http or https.
:param user: Elasticsearch username.
:param secret: Elasticsearch secret.
:param hostname: Elasticsearch hostname.
:param port... | 43,084 |
def _truncate(s: str, max_length: int) -> str:
"""Returns the input string s truncated to be at most max_length characters
long.
"""
return s if len(s) <= max_length else s[0:max_length] | 43,085 |
def verify_days_of_week_struct(week, binary=False):
"""Given a dictionary, verify its keys are the correct days
of the week and values are lists of 24 integers greater than zero.
"""
if set(DAYS_OF_WEEK) != set(week.keys()):
return False
# Each day must be a list of ints
for _, v in we... | 43,086 |
def create_attention_mask_from_input_mask(from_tensor, to_mask):
"""Create 3D attention mask from a 2D tensor mask.
Args:
from_tensor: 2D or 3D Tensor of shape [batch_size, from_seq_length, ...].
to_mask: int32 Tensor of shape [batch_size, to_seq_length].
Returns:
float Tensor of shape [batch_size, from_seq_... | 43,087 |
def dump_model_to_file(prompt_string, feature_ext, classifier, text, score, model_path):
"""
Writes out a model to a file.
prompt string is a string containing the prompt
feature_ext is a trained FeatureExtractor object
classifier is a trained classifier
model_path is the path of write out the m... | 43,088 |
def execute_inspection_visits_data_source(operator_context, return_value, non_data_function_args) -> BackendResult:
"""Execute inspections when the current operator is a data source and does not have parents in the DAG"""
# pylint: disable=unused-argument
inspection_count = len(singleton.inspections)
it... | 43,089 |
def parse(template, delimiters=None, name='<string>'):
"""
Parse a template string and return a ParsedTemplate instance.
Arguments:
template: a template string.
delimiters: a 2-tuple of delimiters. Defaults to the package default.
Examples:
>>> parsed = parse(u"Hey {{#who}}{{name}}... | 43,090 |
def print_user_stories(us_array, columns):
"""
Prints an user story array like:
+------------+------------+
| column 1 | column 2 |
+============+============+
| value1 | value2 |
+------------+------------+
| value3 | value4 |
+------------+------------+
@pa... | 43,091 |
def setup(bot):
"""Loads cog"""
bot.add_cog(CommandErrorHandler(bot)) | 43,092 |
def main():
"""
Main Loop
"""
global DEBUG
global PLUG
options = parsingopt()
if options.verbose:
DEBUG = True
print('Listening.....')
# Plugin Thread
if options.pluginfd:
valplugin(options.pluginfd)
if flogin():
if DEBUG:
... | 43,093 |
def get_phases(t, P, t0):
"""
Given input times, a period (or posterior dist of periods)
and time of transit center (or posterior), returns the
phase at each time t. From juliet =]
"""
if type(t) is not float:
phase = ((t - np.median(t0)) / np.median(P)) % 1
ii = np.where(phase >... | 43,094 |
async def my_profile(current_user: User = Depends(get_current_active_user)):
"""GET Current user's information."""
return current_user | 43,095 |
def are_2d_vecs_collinear(u1, u2):
"""Check that two 2D vectors are collinear"""
n1 = np.array([-u1[1], u1[0]])
dot_prod = n1.dot(u2)
return np.abs(dot_prod) < TOL_COLLINEAR | 43,096 |
def TimeFromTicks(ticks: int) -> datetime.time: # pylint: disable=invalid-name
"""
Constructs an object holding a time value from the given ticks value.
Ticks should be in number of seconds since the epoch.
"""
return Time(*time.gmtime(ticks)[3:6]) | 43,097 |
def load_model(opt, dataloader):
""" Load model based on the model name.
Arguments:
opt {[argparse.Namespace]} -- options
dataloader {[dict]} -- dataloader class
Returns:
[model] -- Returned model
"""
model_name = opt.model
model_path = f"lib.models.{model_name}"
pr... | 43,098 |
def process(cntrl):
""" We have all are variables and parameters set in the object, attempt to
login and post the data to the APIC
"""
if cntrl.aaaLogin() != 200:
return (1, "Unable to login to controller")
rc = cntrl.genericGET()
if rc == 200:
return (0, format_content(cn... | 43,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.