content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def remove_indices(dist_array, indices):
"""
Remove given indices from dist_array
:param dist_array: a flattened version of the dist_matrix in the format of entries (node0/ window0, node1/ window1, distance),
usually sorted
:param indices: indices which should be removed
:return:
""... | 3b61645655a19c18889f7a02b8bfda0368091873 | 3,630,926 |
def bow_net(data, dict_dim, emb_dim=128, hid_dim=128, hid_dim2=96, class_dim=2):
"""
Bow net
"""
# embedding layer
emb = fluid.layers.embedding(
input=data,
size=[dict_dim, emb_dim],
param_attr=fluid.ParamAttr(name="@HUB_senta_bow@embedding_0.w_0"))
# bow layer
bow =... | 94c7f0483c98644d943815ba92e00cbee0196e50 | 3,630,927 |
def close_story(request):
"""
Tags: logs+stories
---
Closes an open story.
---
story_id:
in: path
type: string
required: true
"""
auth_context = auth_context_from_request(request)
# Only available to Owners for now.
if not auth_context.is_owner():
raise... | 4b28978c99c26f76bbe04d62a55ca22ba9d40676 | 3,630,928 |
def convert_dates_to_ISO(date: str, date_2: str):
"""Assumes both dates are current system year. If the latter one occurs chronologically
before the former (i.e given "december 4 2021" and "january 4 2021", january comes first in the year.
This means that the second date is likely the next year, so we'll assume tha... | 7fd68c06ad5abff67e5bd69c1a23530f985857e0 | 3,630,929 |
def findliteralblocks(blocks):
"""Finds literal blocks and adds a 'type' field to the blocks.
Literal blocks are given the type 'literal', all other blocks are
given type the 'paragraph'.
"""
i = 0
while i < len(blocks):
# Searching for a block that looks like this:
#
# ... | 43b2472784744e5d1c17b5b4e306b23c953223fa | 3,630,930 |
import requests
def urlcheck():
"""takes all devurls and checks their header return"""
urlstatus = []
for elem in get_bundle_dev_url():
appads = "https://" + elem[1] + "/app-ads.txt"
try:
x = requests.head(appads, timeout=3.5, allow_redirects=True)
except requests.excep... | b4f8aa5cdd8cc4aab9b2a4ddf204ab3dd43f0792 | 3,630,932 |
def get_vpc_dhcp_options(dhcp_options_id=None,filters=None,tags=None,opts=None):
"""
Retrieve information about an EC2 DHCP Options configuration.
## Example Usage
### Lookup by DHCP Options ID
```python
import pulumi
import pulumi_aws as aws
example = aws.ec2.get_vpc_dhcp_options(dhc... | 05d73c3d230c3e815e47aa8c6134c89efb814439 | 3,630,933 |
def ms2str(v):
"""
Convert a time in milliseconds to a time string.
Arguments:
v: a time in milliseconds.
Returns:
A string in the format HH:MM:SS,mmm.
"""
v, ms = divmod(v, 1000)
v, s = divmod(v, 60)
h, m = divmod(v, 60)
return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}" | 5d50aa072584e5ad17d8bd3d08b0b0813aced819 | 3,630,935 |
import operator
def regroup(X, N):
"""
Regroup the rows and columns in X.
Rows/Columns that are N apart in X are adjacent in Y.
Parameters:
X (np.ndarray): Image to be regrouped
N (list): Size of 1D DCT performed (could give int)
Returns:
Y (np.ndarray): Regoruped image
"""
#... | d4492e71a42a69d86d0e2a1c21bf05d13dfe13d7 | 3,630,936 |
def uint_to_two_compl(value: int, length: int) -> int:
"""Convert int to two complement integer with binary operations."""
if value >> (length - 1) & 1 == 0: # check sign bit
return value & (2 ** length - 1)
else:
return value | (~0 << length) | a0b7bd5192a3f12119ea7ec1a58ca785c37369bf | 3,630,937 |
def synthetic_pattern_program():
"""A program that tests pattern matching of `PrimOp` outputs.
Returns:
program: `instructions.Program`.
"""
block = instructions.Block(
[
instructions.prim_op(
[], ("one", ("five", "three")), lambda: (1, (2, 3))),
instructions.prim_op... | c3f55b75301604a394d9f0ec01d4198a27f90c8e | 3,630,938 |
def generator(z, out_channel_dim, is_train=True, alpha=0.2):
"""
Create the generator network
:param z: Input z
:param out_channel_dim: The number of channels in the output image
:param is_train: Boolean if generator is being used for training
:param alpha : leaky relu rate
:return: The tens... | 9bea06f8c78aadc2e9a4287ce44b12422cfead99 | 3,630,939 |
import re
def manual_filtration(word, neg_list):
"""作用在 word 上, 若该词为负例则返回 True, 否则返回 False"""
pattern_1 = r',|\.|:|;|"'
pattern_2 = r'行|示|为|较|见|天|音'
pattern_3 = r'切除|标本|摄取|存在|活检|穿刺|开口|引流|胸痛|患者|治疗|不适|受限|疼痛|基本|压缩'
pattern_4 = r'^[A-Za-z0-9_]+$'
remove_word_list = neg_list + ['病理', '癌', '炎', '占位'... | 6957c8a3b86073060ffeded9c5a7c7badf1005cc | 3,630,940 |
def two(f):
"""Church numeral 2: same as successor(successor(zero))"""
"*** YOUR CODE HERE ***"
return lambda x: f(f(x)) | 0ae1c89aca0a3fa85319882d49aea0cc05c12b7a | 3,630,941 |
import warnings
def _find_indexes(obj, var_name, min_limit, max_limit, use_dask):
"""
Function to find array indexes where failing limit tests
Parameters
----------
obj : Xarray.Dataset
Dataset containing data to use in test
var_name : str
Variable name to inspect
min_limi... | ad59ce154bf056d0ede5b98250fc95265ec83c89 | 3,630,942 |
def asinh_grad(orig, grad):
"""Returns [grad * 1/((1 + (x ^ 2)) ^ (1/2))]"""
x = orig.args[0]
ones = ones_like(x)
return [grad * ones / sqrt(ones + (x * x))] | 6cdcc4b0271aa8173059fe165fc77a556da79834 | 3,630,943 |
def inject_test_seed(seed, signature, user_data_dir):
"""Injects the given test seed.
Args:
seed (str): A variations seed.
signature (str): A seed signature.
user_data_dir (str): Path to the user data directory used to launch Chrome.
Returns:
bool: Whether the injection succeeded.
"""
seed_d... | 838c4f0a2bd969327f0733c270659243caa3a881 | 3,630,944 |
import math
def _scale_stage_depth(stack_args, repeats, depth_multiplier=1.0, depth_trunc='ceil'):
""" Per-stage depth scaling
Scales the block repeats in each stage. This depth scaling impl maintains
compatibility with the EfficientNet scaling method, while allowing sensible
scaling for other models ... | e1411f4c62bf5834a994d6c0313ea77e7368ee2c | 3,630,945 |
def tokenize(s):
"""
Ковертирует строку в питон список токенов
"""
return s.replace('(',' ( ').replace(')',' ) ').split() | 639baad1a6ec7640abe6752ad44e1f8585a9aafe | 3,630,946 |
def vote_entropy(votes, classes):
"""Calculates the vote entropy for measuring the level of disagreement in
QBC.
Parameters
----------
votes : array-like, shape (n_samples, n_estimators)
The class predicted by the estimators for each sample.
classes : array-like, shape (n_classes)
... | 2f8232d85fae5511555eba469d7b7c33b375a8e0 | 3,630,947 |
def printModelDict(localsDict):
"""Convert serverConfig model configuration to a dictionary. This writes
the dictionary as text. This does not create a usable modelDict, just one to
use to print out the dictionary as python code."""
modelDict={}
parmsDict={}
tcDict={}
dbs=DATABASES
scTe... | af8450e0d2807198de5f09d3245ff8100f9e8cdf | 3,630,948 |
import ctypes
def ira_equinox(jd_tdb, equinox, accuracy=0):
"""
To compute the intermediate right ascension of the equinox at
the input Julian date, using an analytical expression for the
accumulated precession in right ascension. For the true equinox,
the result is the equation of the origins.
... | ce145a20c623e444623c6ae3f5d7d59910520a82 | 3,630,949 |
from typing import Sequence
from typing import Any
from typing import Callable
from typing import Dict
def _generate_steps(
episode: Sequence[Any],
step_fn: Callable[[Dict[str, Any]], Dict[str, Any]]) -> Dict[str, Any]:
"""Constructs a dictionary of steps for the given episode.
Args:
episode: Sequenc... | 4ddafb41501a1ab6b61b325ebb8db0c2bd40bf85 | 3,630,951 |
def format_results_data(results_data, compute_rank=True):
"""Formats results_data as sorted list of rows so it can be easily displayed as results_table
Appends user and ranks.
Side effect: This function modifies objects (i.e. individual results)
contained in results_data
"""
Result = namedtuple(... | 6fdceb3a07ebcc23b245e43a2eb3770f67073cd0 | 3,630,952 |
def encode_triangle(X, centroids):
"""
Perform triangle k-means encoding
"""
X3 = X.reshape(X.shape[0], 1, X.shape[1])
centroids3 = centroids.reshape(1, centroids.shape[0], centroids.shape[1])
z = np.sqrt(((X3 - centroids3) ** 2).sum(2))
means = z.mean(1).reshape(-1, 1)
return np.maximum... | 98f11930892b61d8a7ee653a4dab677a6d0543d1 | 3,630,953 |
def get_user_and_check_password(username, password):
"""
Called by account controller and/or AuthKit valid_password to return a user from local db
"""
try:
q = Session.query(User).select_from(join(User, UserLogin, User.login_details))
q = q.filter(User.id == make_username(usernam... | 3def5ad6bba4486d235d58b4f8f50cf3ac27b734 | 3,630,954 |
import hashlib
def get_db_for_id(id_value):
"""
Work out the database number containing a Review record with pk of
"id_value".
"""
# XXX: If we were interested in being able to add databases and do minimal
# data moving, it would be better to use a consistent hashing algorithm
# here (dist... | 7ece564172061e31c61168cba02b034ac2666533 | 3,630,955 |
def subclass(request):
"""Return a Object subclass"""
try:
params = request.param
except AttributeError:
params = {}
class TestObject(Object):
@property
def fields(self):
return params.get("fields", {})
TestObject.__name__ = params.get("name", "TestObjec... | 376578606f20ae8899dba01590675847a2c8e11f | 3,630,956 |
def is_index(file_name: str) -> bool:
"""Determines if a filename is a proper index name."""
return file_name == "index" | 7beb5779b61e25b4467eb7964478c78d44f28931 | 3,630,957 |
def GenerateShardedFilenames(spec): # pylint:disable=invalid-name
"""Generate the list of filenames corresponding to the sharding path.
Args:
spec: Sharding specification.
Returns:
List of filenames.
Raises:
ShardError: If spec is not a valid sharded file specification.
"""
basename, num_sha... | 38fe085c7063c80d633221aab9c0159fc8bc68ac | 3,630,959 |
def _tseries_from_nifti_helper(coords, data, TR, filter, normalize, average):
"""
Helper function for the function time_series_from_nifti, which does the
core operations of pulling out data from a data array given coords and then
normalizing and averaging if needed
"""
if coords is not None:
... | 1e464b0f54536ab062ae32b49ed821f2d230f45f | 3,630,960 |
import hashlib
def hash_short(message, length=16):
""" Given Hash Function"""
return hashlib.sha1(message).hexdigest()[:length / 4] | bd071674ce5caf382dc73d27835f43409a6a49d2 | 3,630,961 |
def feincms_frontend_editing(cms_obj, request):
"""
{% feincms_frontend_editing feincms_page request %}
"""
if hasattr(request, 'session') and request.session.get('frontend_editing'):
context = template.RequestContext(request, {
"feincms_page": cms_obj,
'FEINCMS_ADMIN_ME... | 6e1e1e0ee771d4260ffd310f970bf53a045a48ba | 3,630,962 |
def _add_tensor_cores(tt_a, tt_b):
"""Internal function to be called from add for two TT-tensors.
Does the actual assembling of the TT-cores to add two TT-tensors.
"""
ndims = tt_a.ndims()
dtype = tt_a.dtype
shape = shapes.lazy_raw_shape(tt_a)
a_ranks = shapes.lazy_tt_ranks(tt_a)
b_ranks = shapes.lazy_... | 07c1c79fff1547afe6c69fc82fe584f418432d8a | 3,630,963 |
from typing import OrderedDict
def create_mosaic_iterative(dataset_in, clean_mask=None, no_data=-9999, intermediate_product=None):
"""
Description:
Creates a most recent - oldest mosaic of the input dataset. If no clean mask is given,
the 'cf_mask' variable must be included in the input dataset, a... | 6ba190145b2b655decd7bdd770abd8a6390b09bc | 3,630,964 |
from typing import Sequence
from typing import cast
import collections
def dicom_file_loader(
accept_multiple_files: bool, stop_before_pixels: bool
) -> Sequence["pydicom.Dataset"]:
"""A Streamlit component that provides DICOM upload functionality.
Parameters
----------
accept_multiple_files : ``... | acaf9c54270a67f1893605a9a1d5b101dd02aba6 | 3,630,965 |
def get_substrings(source: str):
"""Get all substrings of a given string
Args:
string (str): the string to generate the substring from
Returns:
list: list of substrings
"""
# the number of substrings per length is the same as the length of the substring
# if the characters are... | 79f1db4184c51235a9d6beb8437f1647bc993958 | 3,630,966 |
import csv
def _write_output_csv(reader: csv.DictReader, writer: csv.DictWriter,
config: dict) -> list:
"""Reads each row of a CSV and creates statvars for counts of
Incidents, Offenses, Victims and Known Offenders with different bias
motivations.
Args:
reader: CSV dict ... | 057820c97100b626171250d4d97f90b07f0c48a7 | 3,630,967 |
def get_vehicle_lay_off_engine_acceleration(carla_vehicle):
"""
Calculate the acceleration a carla vehicle faces by the engine on lay off
This respects the following forces:
- engine brake force
:param carla_vehicle: the carla vehicle
:type carla_vehicle: carla.Vehicle
:return: acceleratio... | 84ca84d75866840e88cc6afdb615cbc0529ea311 | 3,630,968 |
def _run_docker_shell_script(script_name, docker_dir, trailing_args=None,
env_variables=dict()):
"""
script_name (String) filename of a script in the nest/docker/ directory
docker_dir (String) directory of docker scripts in the nest repo. expected
to be /code_live/docker, but may be different is... | a68d85a6affd1905d312b91ccc85475c30809c22 | 3,630,970 |
def _create_functional_connect_edges_dynamic(n_node, is_edge_func):
"""Creates complete edges for a graph with `n_node`.
Args:
n_node: (integer scalar `Tensor`) The number of nodes.
is_edge_func: (bool) callable(sender, receiver) that returns tf.bool if connected. Must broadcast.
Returns:
A di... | 338b7a240f516703853af8f810f56e313fcb2b99 | 3,630,971 |
from operator import matmul
def simulateBERParallel(codes, channelfun, params, printValue=True):
"""
Simulates BER values at multiple SNRs, where the massively parallel algorithm is used. This implementation is especially designed for cupy.
Args:
codes (ndarray): an input codebook, which is gener... | 89df47bbe05b19f32276d608c260ae51ea9c7f28 | 3,630,973 |
from datetime import datetime
import json
def modify_app_description(s, base_url, app_id, description):
"""
Modifies the description of an app
"""
rjson = app_full(s, base_url, app_id)[1]
rjson["modifiedDate"] = str(
((datetime.today()) + timedelta(days=1)).isoformat() + "Z"
)
rjs... | e4f1529a31dd982b2ccf56d31542139f6cc564ef | 3,630,974 |
def search_tag(resource_info, tag_key):
"""Search tag in tag list by given tag key."""
return next(
(tag["Value"] for tag in resource_info.get("Tags", []) if tag["Key"] == tag_key),
None,
) | 5945631a3de7032c62c493369e82dd330ef2bc47 | 3,630,975 |
def compute_GARCH_price(theta,
num_periods,
init_price,
init_sigma,
risk_free_rate,
num_simulations=50000):
"""
Compute asset price at period t + s (s periods ahead) given estimated theta... | de6a6aca57bb6ea63cfa39221522798322bafdda | 3,630,976 |
def create_order_nb(size: float,
price: float,
size_type: int = SizeType.Amount,
direction: int = Direction.All,
fees: float = 0.,
fixed_fees: float = 0.,
slippage: float = 0.,
min... | 660940e9258f1b43352cf5e2b78e083b0c984bc7 | 3,630,977 |
def generate_noise_2d_fft_filter(F, randstate=None, seed=None, fft_method=None,
domain="spatial"):
"""Produces a field of correlated noise using global Fourier filtering.
Parameters
----------
F : dict
A filter object returned by
:py:func:`pysteps.noise... | 4c4dbe8b22cf73730bff84affa5ff592e0484a1c | 3,630,978 |
def get_spending_features(txn, windows_size=[1, 7, 30]):
"""
This function computes:
- the cumulative number of transactions for a customer for 1, 7 and 30 days
- the cumulative average transaction amount for a customer for 1, 7 and 30 days
Args:
txn: grouped transactions of custome... | b648df3d1217074edec455a416e0eb698d8069ee | 3,630,980 |
def break_up(expr):
"""
breaks up an expression with nested parenthesis into sub expressions with
no parenthesis, with the innermost expressions first, that needs to be
calculated before doing the outer expression. also replaces the statement with
a single symbol in the larger expression
"""
p=0
new_ex... | 7f28290a3dadfec2bd42696bcf7be348288a7bca | 3,630,981 |
def fft_operation(file_path):
"""
FFT operation
:param file_path: Original wav file path
:return: freqs, 20 * log10(fft/max_fft), name
"""
wave_data, nchannels, sample_width, framerate, numframes = read_file(file_path)
abs_fft = np.abs(np.fft.fft(wave_data))
normalized_abs_fft = abs_fft... | 75c672298e3d8650e79ee56ce540006102a1b375 | 3,630,982 |
import six
def _expand_expected_codes(codes):
"""Expand the expected code string in set of codes.
200-204 -> 200, 201, 202, 204
200, 203 -> 200, 203
"""
retval = set()
for code in codes.replace(',', ' ').split(' '):
code = code.strip()
if not code:
continue
... | 52056db88bf14352d4cda2411f25855457defbd7 | 3,630,983 |
from typing import Optional
from pathlib import Path
import importlib
def predict(
seq: np.ndarray,
aa_cut: Optional[np.ndarray] = None,
percent_peptide: Optional[np.ndarray] = None,
model: Optional[GradientBoostingRegressor] = None,
model_file: Optional[Path] = None,
pam_audit: bool = True,
... | 50cb3adc03d017e7e94353dd9a9b15166e616d4a | 3,630,984 |
import collections
def _is_proper_sequence(seq):
"""Returns is seq is sequence and not string."""
return (isinstance(seq, collections.abc.Sequence) and
not isinstance(seq, str)) | d5f1f211330a9f4928b8cc8c7407adaf705fd4b2 | 3,630,985 |
def sigmoid(mat, target = None):
"""
Apply the logistic sigmoid to each element of the matrix mat.
"""
if not target:
target = mat
err_code = _cudamat.apply_sigmoid(mat.p_mat, target.p_mat)
if err_code:
raise generate_exception(err_code)
return target | ba02fe038ce1d491b40b605baf43e4bf8afda057 | 3,630,986 |
def mutation_modify_controlaction(controlaction_id: str, actionstatus: ActionStatusType, error: str = None):
"""Returns a mutation for modifying the status and errors of the ControlAction
Arguments:
controlaction_id: The unique identifier of the ControlAction.
actionstatus: the status to update ... | f7ef2c0174fe8c31505d2397df38602c9cee46ac | 3,630,987 |
def get_colours(time, flux, data, nuv=[nuvwave, nuvtrans], u=[uwave, utrans], r=[rwave, rtrans], filter_pairs=None):
"""" Calculates the colours of a given sfh fluxes across time given the BC03 models from the magnitudes of the SED.
:time:
Array of times at which the colours should be calcu... | d03c33822918c50d30db06284fbe56571886228c | 3,630,988 |
def loginpage():
"""A route to login the user."""
year = date.today().year
return render_template("website/login.html",
base=get_base_data(year),
route=Routes,
year=year,
github_enabled=is_github_supp... | 282630fb7c4585cf0321c3fa3fc3ce55bfc33c8e | 3,630,989 |
from hypothesis.internal.conjecture.shrinker import dfa_replacement, sort_key
import math
def learn_a_new_dfa(runner, u, v, predicate):
"""Given two buffers ``u`` and ``v```, learn a DFA that will
allow the shrinker to normalise them better. ``u`` and ``v``
should not currently shrink to the same test cas... | ff0ba6d5831099d8d5f392b3cd7dec59ac3a3663 | 3,630,990 |
def generate_corrected_profiles (corr_factor, fwd_border_dicts, fwd_profile, plasmid_length, scale):
""" Correct the edges of the transcription profiles
"""
# New profile to hold the normalised data
Normalized_fwd_profile = np.ones(plasmid_length)*scale
# Cycle through each transcript (no idea why this is a dict)
... | d7fbd70e7651b7467d7cc6e754bb4baad1e8d2ca | 3,630,991 |
def transforToManagerProxyObject(manager, data):
"""将不转换dict中的key
只支持基础数据,dict,list和tuple
tuple将会转换成list
result = data
"""
if isinstance(data, dict):
result = manager.dict()
for key in data:
result[key] = transforToManagerProxyObject(manager, data[key])
elif isinstance(data, list) or isinstance(data, tupl... | d9b0c17b1e1eb50a9bede908130d8444422b8fd4 | 3,630,994 |
import json
import time
def get_new_account_id(event):
"""Return account id for new account events."""
create_account_status_id = (
event["detail"]
.get("responseElements", {})
.get("createAccountStatus", {})["id"] # fmt: no
)
LOG.info("createAccountStatus = %s", create_accoun... | e782e930d09b2f02b10547e5a39e14bba852d896 | 3,630,995 |
from tvrenamer.common import tools
def list_opts():
"""Returns a list of oslo_config options available in the library.
The returned list includes all oslo_config options which may be registered
at runtime by the library.
Each element of the list is a tuple. The first element is the name of the
gr... | a650cf9fb8d3bfd0ee60e6301463ff62d3842f8f | 3,630,996 |
from datetime import datetime
def tokenize_for_t5_advice_training(encoder, subreddit=None, date=None, title=None,
selftext=None, body=None):
"""
Tokenizes the post title / post selftext / comment body.
If it's too long we'll cut some paragraphs at random from the selfte... | 5716eb12d2f1c7773fcb49abfe7c203375ef9c65 | 3,630,997 |
def hvdisp_plot_records_2d(records,
to_pe,
config,
t_reference,
time_stream=None,
tools=(x_zoom_wheel(), 'xpan'),
default_tools=('save', 'pan', 'box_zoom', 's... | 0fa08d4f71ef08c35a2121e4716bce213e39d9d8 | 3,630,998 |
import re
def join_url(url, *paths):
"""
:param url: api url
:param paths: endpoint
:return: full url
"""
for path in paths:
url = re.sub(r"/?$", re.sub(r"^/?", "/", path), url)
return url | 32e085acc64590901afcf3d4ded47f8be7d40119 | 3,630,999 |
def _get_minimum_columns(
nrows, col_limits, families, family_counts, random_state
):
"""If ``col_limits`` has a tuple lower limit then sample columns of the
corresponding element of ``families`` as needed to satisfy this bound."""
columns, metadata = [], []
for family, min_limit in zip(families, c... | 56a0abc58a6e6c3356be08511e7a30da3c1c52e3 | 3,631,000 |
from typing import Union
from typing import Any
from typing import cast
def ensure_callable(x: Union[Any, Function]) -> Function:
"""ensure a given args is a callable by returning a new callable if not"""
if not callable(x):
def wrapped(*args: Any, **kwargs: Any) -> Any:
return x
... | 5165a1b44de13f570454f223f3b9b1e799bd309d | 3,631,001 |
from typing import List
def concat_dataframes(dataframes: List[pd.DataFrame],
remove_duplicates: bool = True,
keep: str = 'first'
) -> pd.DataFrame:
"""
Concatenate list of dataframes with optional removal of duplicate keys.
Args:
... | fd21c0ca6e95bdc5e5c854ba0d3cd2e30f018966 | 3,631,002 |
def __split_pair(number: SnailfishNumber, left: bool) -> int | None:
"""Splits a number into a pair if the number is >= 10.
:param number: Number node from the binary tree.
:param left: Boolean if we are inspecting the right or left leaf.
:return: 1 if we split else None.
"""
# Search for the l... | cd9a762fbad3148989fa2f823d83779ebd12e3ba | 3,631,003 |
def def_pin_pout(m):
# This could be better implemented.
# In particular, it should not use m.p directly but m.find_component(name_var)
"""
Defines power 'in' and 'out' variables
:param m:
:return:
"""
assert isinstance(m, Block), f"argument 'm', must be an instance of Block, but i... | 606d21f8b3204ca4394a891a260c88384e56c435 | 3,631,004 |
def get_user_choice() -> tuple[str, str]:
"""Returns the headers for the x and y value choices as a tuple."""
while True:
# X
console_display_choices(X_OPTIONS, "X")
x_choice = get_x_y_value(X_OPTIONS, "X")
# Y
console_display_choices(Y_OPTIONS, "Y")
y_choice ... | 94ff044acfbd52752dbe625e2a3f43531692ac14 | 3,631,005 |
import torch
import test
def exp(args, model_type, vertex_label, b_true, X_train, X_test_ID, X_test_OOD):
"""Experiment function."""
torch.set_default_dtype(torch.double)
np.set_printoptions(precision=3)
model, w_est = train(
X_train,
vertex_label=vertex_label,
b_true=b_true,
model_t... | 245f0feea515cfa1c28c8d59c176a486ddf43675 | 3,631,006 |
def sliding_window(warped):
"""
Using sliding window to find the lane line segments. This method will be used at the start of a video or when there is no lane line found on the previous video frame.
"""
img_height, img_width = warped.shape[0], warped.shape[1]
histogram = np.sum(warped[img_heig... | 9c495a502b79e8708573a94a0015915a35d44e41 | 3,631,007 |
def get_config(n_layers, use_auto_acts,
fp_quant):
"""Returns a ConfigDict instance for a WMT transformer.
The ConfigDict is wired up so that changing a field at one level of the
hierarchy changes the value of that field everywhere downstream in the
hierarchy. For example, changing the top-level... | c3b30a30ed2e272cd5e9802508d3eab78a679b47 | 3,631,008 |
import torch
def get_train_loader(transform=None):
"""
Args:
transform (transform): Albumentations transform
Returns:
trainloader: DataLoader Object
"""
if transform:
trainset = Cifar10SearchDataset(transform=transform)
else:
trainset = Cifar10SearchDataset(root="~/data/cifar10", train... | c72222835c98b104fa4a04f4bf49de5850071365 | 3,631,009 |
def train_regression(train_data, model, criterion, optimizer, batch_size, device, scheduler=None, collate_fn=None):
"""Train a Pytorch regresssion model
Parameters
----------
train_data : torch.utils.data.Dataset
Pytorch dataset
model: torch.nn.Module
Pytorch Model
criterion: fu... | 6a20c532137e32e1a56656b3cecf0c1686ec9f40 | 3,631,010 |
import re
import urllib
import locale
import socket
def get_url_content(url):
"""Performs a HTTP GET on the url.
Returns False if the url is invalid or not-found"""
res = None
if not re.search(r'^http', url):
url = 'http://' + url
try:
req = urllib.request.urlopen(url, None, 30)
... | a6cebdb19eff1daa86e9f7aa18943c19854e5641 | 3,631,011 |
def _evaluate(cmd, dork):
"""Parse a command and execute it"""
cmd = cmd.strip().split(" ", 1)
if cmd[0]:
verb, *noun = cmd
noun = noun[0] if noun else None
call = _CMDS.get(verb, _MOVES.get(verb, _META.get(verb, _ERRS["u"])))
if isinstance(call, dict):
method, ... | cfb6957cf1c10c18cc768c266992412c36222571 | 3,631,012 |
from typing import OrderedDict
def build_input_dict(feature_columns):
"""
基于特征列(feature columns)构建输入字典
:param feature_columns: list 特征列
:return:
input_dict: dict 输入字典,形如{feature_name: keras.Input()}
"""
# 1,基于特征列构建输入字典
input_dict = OrderedDict()
for fc in feature_columns:
... | 033a6cb0d73a9652a5a9ce83026a05a93756e85c | 3,631,013 |
def factorial(n):
"""Calcula el factorial de un numero"""
fact = 1
for i in range (1, n+1):
fact = fact * i
return fact | b341682fbc13fd184af8551be37348bf36ec082c | 3,631,014 |
def sigmoid(x):
"""
Computes sigmoid of x element-wise.
Parameters
----------
x : tensor
A Tensor with type float16, float32, float64, complex64, or complex128.
Returns
-------
A Tensor with the same type as x.
"""
outputs = P.Sigmoid()
return outputs(x) | 314c13df8127e3bb602e3a3eab98b2c2b68fb82d | 3,631,015 |
def conf_serializer(configuration: Configuration) -> str:
"""Serialize configuration to .conf files."""
lines = [f"{key} {val}" for key, val in configuration.Properties.items()]
return "\n".join(lines) + "\n" | 8bf3104495cf849ad0b3576c3bf61482c51d04fe | 3,631,016 |
def redness_greenness_response(C, e_s, N_c, N_cb):
"""
Returns the redness / greenness response :math:`M_{yb}`.
Parameters
----------
C : array_like
Colour difference signals :math:`C`.
e_s : numeric or array_like
Eccentricity factor :math:`e_s`.
N_c : numeric or array_like
... | 06ea4162ec83957db705a2903c8cd748f7a7c34a | 3,631,017 |
import platform
def _format_source(src, virtual_cells = None): # type: (Union[str, RuleTarget], str) -> str
"""
Converts a 'source' to a string that can be used by buck native rules
Args:
src: Either a string (for a source file), or a RuleTarget that needs converted to a label
platform: ... | 530c13b7ce8239e97159f57ef794f036f958f9d4 | 3,631,020 |
def get_player():
"""Returns a driver to control the VoiceHat speaker.
The aiy modules automatically use this player. So usually you do not need to
use this. Instead, use 'aiy.audio.play_wave' if you would like to play some
audio.
"""
global _voicehat_player
if not _voicehat_player:
... | f8c242083072392663a19bc720fac156e96cef7a | 3,631,023 |
import json
def post_user_events():
"""Endpoint for users to post the events they want to add to their calendar
Returns:
Response: JSON with the success status of each event
"""
body = request.json
response = insert_user_calendar_events(
session['google-idap']['access_token'],
... | 23dc6e8d4751e4c630b4049f1aec50ee6a8783b2 | 3,631,024 |
def zmq_version():
"""return the version of libzmq as a string"""
return "%i.%i.%i" % zmq_version_info() | 49fc037744e4215a583ccc8de07cd415a99fc17c | 3,631,025 |
def parse_datetime_interval(period_from: str, period_to: str, strformat: str = None) -> date_tuple:
"""
Returns given period parameters in datetime format, or next step in back-fill mode
along with generated last state for next iteration.
Args:
period_from: YYYY-MM-DD or relative string support... | ddf97283465b04cc85bf74a079465439c49c82ff | 3,631,026 |
def _paths_from_ls(recs):
"""The xenstore-ls command returns a listing that isn't terribly
useful. This method cleans that up into a dict with each path
as the key, and the associated string as the value.
"""
ret = {}
last_nm = ""
level = 0
path = []
ret = []
for ln in recs.split... | afa0fbe3e5c1773074569363a538587664a00a2f | 3,631,027 |
def TRS_between_rounds(X1, X2):
"""
Calculate the TRS rotor between any pair of rounds of the same grade
Bring rounds to origin, line up carriers, calculate scale
"""
T1 = generate_translation_rotor(-down((X1 * einf * X1)(1)))
X1h = (T1 * X1 * ~T1).normal()
T2 = generate_translation_rotor(-d... | 6e25e89999e22a6f3e3ef853f7b4c8e6268824b6 | 3,631,029 |
def col_range_nb(col_arr, n_cols):
"""Build column range for sorted column array.
Creates a 2-dim array with first column being start indices (inclusive) and
second column being end indices (exclusive).
!!! note
Requires `col_arr` to be in ascending order. This can be done by sorting."""
c... | f6ff35b01c34b917f9aaf69acfe4aa3d1e6d7548 | 3,631,030 |
def filterfiles(files, criteria):
"""Rerturns only the files from filelist that match the criteria.
The criteria should be a list of (unit,keyword,function) where the function
returns true for desired values of the keyword. For example
criteria = ((0,'OPT_ELEM', lambda x: x == 'G130M'),
... | 5a60a2a46944eeb8d70337b342824cad6156c33d | 3,631,031 |
def module_start(ip, port, dev, module):
"""模块启动
Args:
ip(str):ip地址
port(int):端口号
dev(str): 设备名称
module(str):模块名称
Returns:
tuple:返回错误码以及对应信息
"""
command = "模块启动"
AP.__class__.logout("发送{}{}{}指令".format(dev, module, command))
MESSAGE_DICT["mod_start_... | 9eb5f222cb3fb6f55398c2390fb67b9f823cae6e | 3,631,032 |
def activate_bgp_neighbor(dut, local_asn, neighbor_ip, family="ipv4", config='yes',vrf='default', **kwargs):
"""
:param dut:
:param local_asn:
:param neighbor_ip:
:param family:
:param config:
:param vrf:
:return:
"""
st.log("Activate BGP neigbor")
cli_type = get_cfg_cli_ty... | 8e335938c73b1cd816afc77b0a8af75c5dfdd893 | 3,631,033 |
def print_experiment_record_argtable(records):
"""
Print a table comparing experiment arguments and their results.
"""
funtion_names = [record.info.get_field(ExpInfoFields.FUNCTION) for record in records]
args = [record.get_args() for record in records]
common_args, different_args = separate_com... | 04b8e5e07e19f6dae0f8b9d988a4bda0a0a1de17 | 3,631,034 |
def key_validator(*args, **kwargs):
"""Wraps hex_validator generator, to keep makemigrations happy."""
return hex_validator()(*args, **kwargs) | 59c6ddda60ac4d1a954f112e426bd2952800dd8e | 3,631,035 |
from . import routes
from . import auth
def create_app():
""" Initialize the core application """
app = Flask(__name__, instance_relative_config=False)
app.config.from_object(Config)
# Initialize Plugins
db.init_app(app)
login_manager.init_app(app)
with app.app_context():
# Regi... | 1aaffaf9ece821e6448670006871c143286ac37c | 3,631,037 |
from typing import Optional
def plot_points_3D_mayavi(
points: np.ndarray,
bird: bool,
fig: Figure,
per_pt_color_strengths: np.ndarray = None,
fixed_color: Optional[Color] = (1, 0, 0),
colormap: str = "spectral",
) -> Figure:
"""Visualize points with Mayavi. Scale factor has no influence o... | e9f80d8de890cd4b1c51a9614dc69812c951cec5 | 3,631,038 |
import io
def read_binary_integer32_token(file_desc: io.BufferedReader) -> int:
"""
Get next int32 value from file
The carriage moves forward to 5 position.
:param file_desc: file descriptor
:return: next uint32 value in file
"""
buffer_size = file_desc.read(1)
return get_uint32(file_d... | 81a0c6a592476a142e28ddbf65bddd59004486ad | 3,631,039 |
def pop(key):
"""
从缓存队列的后尾读取一条数据
:param key: 缓存key,字符串,不区分大小写
:return: 缓存数据
"""
# 将key转换为小写字母
key = str(key).lower()
try:
value = r.rpop(key)
except Exception as e:
log_helper.info('读取缓存队列失败:key(' + key + ')' + str(e.args))
value = None
return _str_to_jso... | 92cc254b9b2270ac2fa6c7d66b7f8a13b11b2522 | 3,631,040 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.