content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_page_response(query, page, per_page, itemskey, return_method=None,
replaceobj=None, replaceobj_key_only=False, **kwargs):
""" 获取一个多页响应对象
:param query: 查询对象,或者直接返回的对象
:param page: 当前页
:param per_page: 每页项目数
:param itemskey: 对应 items 的键名
:param return_method: 若值不为 Non... | 77,300 |
def decrypted(data, password=None, is_user=True):
"""Decrypt to any Python object
:param data: a byte string previously encrypted using :func:`encrypted`
:param passowrd: the optional password originally used to encrypt
:param is_user: optionally indicate whether user or machine
:returns: a P... | 77,301 |
def on_pad_pressed(pad_n=None, pad_ij=None):
"""Shortcut for registering handlers for ACTION_PAD_PRESSED events.
Optional "pad_n" or "pad_ij" arguments are to link the handler to a specific pad.
Functions decorated with this decorator will be called with the following positional
arguments:
* Pus... | 77,302 |
def score(n):
"""根据成绩,计算成绩的级别,级别有:A、B、C、D
成绩>=90 ——A
成绩>=80 ——B
成绩>=70 ——C
成绩>=60 ——D
参数:
- n-:成绩
返回值:返回‘A’或‘B’或者'C'或者'D'
"""
if n >= 90:
return 'A'
if n >= 80:
return 'B'
if n >= 70:
return 'C'
if n >= 60:
return 'D' | 77,303 |
def normalize_path(p):
"""Normalize filesystem path (case and origin). If two paths are identical, they should be equal when normalized."""
return os.path.normcase(os.path.abspath(p)) | 77,304 |
def handle_cron_reacts():
"""Check for new reactions - if any, run through and react to them"""
# Check emojis uploaded (every 60 mins)
# This url is hit in crontab as such:
# 0 * * * * /usr/bin/curl -X POST https://YOUR_APP/cron/reacts
logg.debug('Handling recent reacts...')
reacts = Bot.... | 77,305 |
def get_linked_clusters():
"""
Get linked clusters.
:returns: list of linked clusters
:rtype: [LinkedCluster]
"""
current_cluster = get_attached_cluster()
if not current_cluster:
return []
links = get_cluster_links(current_cluster.get_url()).get('links')
linked_clusters = ... | 77,306 |
def cStatementToPyAst(funcEnv, c):
"""
:param FuncEnv funcEnv:
:param cparser._CBaseWithOptBody c:
"""
body = funcEnv.getBody()
if isinstance(c, (CVarDecl,CFunc)):
funcEnv.registerNewVar(c.name, c)
elif isinstance(c, CStatement):
a, t = astAndTypeForCStatement(funcEnv, c)
... | 77,307 |
def cube_mesh():
""" cube mesh """
mesh = Mock()
mesh.vertices = cube_vertices()
mesh.loop_triangles = [
triangle(0, 2, 1),
triangle(0, 3, 2),
triangle(2, 3, 4),
triangle(2, 4, 5),
triangle(1, 2, 5),
triangle(1, 5, 6),
triangle(0, 7, 4),
tr... | 77,308 |
def algo_options():
"""
Return the list of default options for supported algorithms.
"""
return {"grid": "",
"hubbard": "",
"medial": "-merge -burst -expand",
"octree": "",
"spawn": ""} | 77,309 |
def test_config(config):
"""
Test the configuration file.
:param config: Fixture of the JSON configuration file.
"""
assert config.__class__ is dict, "CONFIGURATION NOT A VALID DICTIONARY"
assert config['inputPath'].__class__ is str, "INPUT PATH CONF NOT A STRING"
assert config['outputP... | 77,310 |
def test_reset():
"""Reseting registry"""
registry = RstConfigSite()
registry.update({
'foo': 42,
'bar': True,
})
registry.reset()
assert registry.get_registry() == {} | 77,311 |
def dyld_framework(filename, framework_name, version=None):
"""Find a framework using dyld semantics"""
filename = ensure_unicode(filename)
framework_name = ensure_unicode(framework_name)
version = ensure_unicode(version)
def _search():
spath = ensure_unicode(os.environ.get("DYLD_FRAMEWORK_... | 77,312 |
def handle_matching_rs(logger, local_response_sets, remote_response_sets, response_set_name, sc_client):
"""
:param logger: The logger
:param local_response_sets: Response_set data pulled from spreadsheet
:param remote_response_sets: Response_set data pulled from API
:param response_s... | 77,313 |
def fill_matrix(X: np.ndarray, mixture: GaussianMixture) -> np.ndarray:
"""Fills an incomplete matrix according to a mixture model
Args:
X: (n, d) array of incomplete data (incomplete entries =0)
mixture: a mixture of gaussians
Returns
np.ndarray: a (n, d) array with completed data... | 77,314 |
def start(ctx, name):
"""Start Project.
If name is not specified will start Project set in auger.yaml/name
"""
ProjectCmd(ctx).start(name) | 77,315 |
def detect(agent, fill_none=False):
"""
fill_none: if name/version is not detected respective key is still added to the result with value None
"""
result = dict(platform=dict(name=None, version=None))
_suggested_detectors = []
for info_type in detectorshub:
detectors = _suggested_detect... | 77,316 |
def advance_euler(gridc, gridx, gridy, scalars, grid_var_list, predcorr):
"""
Subroutine for the fractional step euler explicit time advancement of Navier Stokes equations
Arguments
---------
gridc : object
Grid object for cell centered variables
gridx : object
Grid objec... | 77,317 |
def shutting_down(globals=globals):
"""
Whether the interpreter is currently shutting down.
For use in finalizers, __del__ methods, and similar; it is advised
to early bind this function rather than look it up when calling it,
since at shutdown module globals may be cleared.
"""
# At shutdow... | 77,318 |
def _err(msg=None):
"""To return a string to signal "error" in output table"""
if msg is None:
msg = 'error'
return '!' + msg | 77,319 |
def run_qpe(
unitary,
precision_qubits,
query_qubits,
query_circuit,
device,
items_to_keep=1,
shots=1000,
save_to_pck=False,
):
"""
Function to run QPE algorithm end-to-end and return measurement counts.
Args:
precision_qubits: list of qubits defining the precision r... | 77,320 |
def LNETF(N,loc_rad,taper='GC',infl=1.0,Rs=1.0,rot=False,**kwargs):
"""
The Nonlinear-Ensemble-Transform-Filter (localized).
Ref: Julian Tödter and Bodo Ahrens (2014):
"A Second-Order Exact Ensemble Square Root Filter for Nonlinear Data Assimilation"
It is (supposedly) a deterministic upgrade of the NLEAF ... | 77,321 |
def alert_unmanaged_error(request_id, error, sys_exc_info):
"""Compose error on unmanaged error."""
return UNMANAGED_TEXT_MESSAGE.format(
date=get_date(),
request_id=request_id,
error=error,
traceback=format_traceback(sys_exc_info),
locals=format_locals(sys_exc_info)
... | 77,322 |
def load_transcript(transcript_path):
""""
Load transcript from *.srt file
"""
transcript = []
subs = pysrt.open(transcript_path)
for sub in subs:
transcript.append((sub.text, time2second(tuple(sub.start)[:4]), time2second(tuple(sub.end)[:4])))
return transcript | 77,323 |
def test_generate_e_file_query(monkeypatch, database):
"""Verify that generate_e_file makes an appropriate query (matching both D1 and D2 entries)"""
# Generate several file D1 entries, largely with the same submission_id, and with two overlapping DUNS. Generate
# several D2 entries with the same submission... | 77,324 |
def test_storage_opf():
""" Testing a simple network with storage to ensure the correct behaviour
of the storage OPF-Functions """
# boundaries
vm_max = 1.1
vm_min = 0.9
max_line_loading_percent = 100
# create network
net = pp.create_empty_network()
b1 = pp.create_bus(... | 77,325 |
async def get_attachment_obj(ctx: commands.Context):
"""Gets the attachment object from a message"""
# switch to the replied message if it's there
if ctx.message.attachments:
msg = ctx.message
elif ctx.message.reference:
msg = ctx.message.reference.resolved
else:
return False... | 77,326 |
def day_wind_chart(qs_list, unit, plot_func, width, height, colors):
"""
Returns a URL which produces one line for each queryset.
"""
data_list = [] # list of value lists
for date_qs in qs_list:
if date_qs: # only work on this if the queryset is not empty
data_list.append(conv... | 77,327 |
def conso(h, t, l):
""" Logical cons -- l[0], l[1:] == h, t """
if isinstance(l, (tuple, list)):
if len(l) == 0:
return fail
else:
return (conde, [(eq, h, l[0]), (eq, t, l[1:])])
elif isinstance(t, (tuple, list)):
return eq((h, ) + tuple(t), l)
else:
... | 77,328 |
def select_text(table, col_names, version):
"""Generate a select statement for new or old values of this table."""
slt = "SELECT {tuple_str} FROM {table} WHERE rowid={version}.rowid".format(
tuple_str=sqlite_list_text([col_pair_text(c, version)
for c in col_names]),
... | 77,329 |
def test_get_config_list(configrep):
"""Test getting a list from the configuration."""
assert set(
configrep.get_config_list('platform')
) == set(['Linux', 'Windows']) | 77,330 |
def predict(Theta1, Theta2, X):
""" outputs the predicted label of X given the
trained weights of a neural network (Theta1, Theta2)
"""
if X.ndim == 1:
X = X.reshape(1, -1)
# Useful values
m = len(X)
# ====================== YOUR CODE HERE ======================
# Instructions:... | 77,331 |
def test_unregister_config_decl1(collector, config_decl):
"""Test unregistering a task.
"""
config_decl.register(collector, {})
config_decl.unregister(collector)
assert not collector.contributions | 77,332 |
def aml_token(chain, team_multisig, token_name, token_symbol, initial_supply) -> Contract:
"""Create the token contract."""
args = [token_name, token_symbol, initial_supply, 0, True] # Owner set
tx = {
"from": team_multisig
}
contract, hash = chain.provider.deploy_contract('AMLToken', de... | 77,333 |
def invr():
"""
For taking space seperated integer variable inputs.
"""
return(list(map(int, input().split()))) | 77,334 |
def _path_residuals(X, y, train, test, path, path_params, alphas=None,
l1_ratio=1, X_order=None, dtype=None):
"""Returns the MSE for the models computed by 'path'
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Training data.
y : arr... | 77,335 |
def is_an_exact_imagined_object(predicate, imagined_object):
"""
Returns whether the imagined object matches exactly what the predicate
describes.
Inputs:
predicate: WordPredicate instance
imagined_object: RecognizedObject instance
"""
target = pos... | 77,336 |
def decrypt(inputs: tuple, output):
"""
\b
ECO2 저장 파일 (`.eco`, `.tpl`)을 해석해서 header와 value 파일로 나눠 저장.
header: ECO2 저장 파일의 버전, 생성 날짜 등 정보를 담은 바이너리 파일.
`output.header` 형식.
value : 해석 설정 정보를 담은 xml 파일. `output.xml` 형식.
\b
Argument:
INPUTS: 해석할 ECO2 저장 파일의 경로.
... | 77,337 |
def read_field__list(infile, varname, lon, lat):
"""Read point list and initialize field."""
# Read field ...
if infile.endswith(".npz"):
# ... from numpy archive
with np.load(infile) as fi:
pts_lon, pts_lat, pts_fld = fi["lon"], fi["lat"], fi[varname]
fld = point_list_t... | 77,338 |
def idautils_strings():
"""
Examples for all the APIs that idautils contains. I will follow the exact order that the IDA documentation follows.
"""
"""
Get existing Strings from a program from IDA.
IDA GUI: View - Open SubViews - Strings
"""
s = idautils.Strings()
for i in s:
#These op... | 77,339 |
def write_to_file(cont):
"""Write to file."""
file_name = input("Enter the name of file you want to save:")
with open("{}".format(file_name), "w") as user_file:
user_file.write(cont)
user_file.close()
print("File successfully saved!\n") | 77,340 |
def CircuitHeaderStartConfigurationVector(builder, numElems):
"""This method is deprecated. Please switch to Start."""
return StartConfigurationVector(builder, numElems) | 77,341 |
def get_processed_masks_and_boundaries(mask_path: str, boundary_path: str) -> tuple[ndarray, ndarray]:
"""Utility function for loading and applying preprocessing to mask and boundary image array
:param paths:
:return: tuple[ndarray, ndarray]
"""
masks = np.array(
cv2.imread(
mask... | 77,342 |
def get_replace_columns(dialect):
"""Get the replace values for columns from the user."""
val = clean_input("replace_columns (separated by "
"';', with comma-separated values) "
"(press return to skip): ",
split_char=';', ignore_empty=True)
i... | 77,343 |
def error(update, context):
"""Log Errors caused by Updates"""
logger.warning('Update "%s" caused error "%s"', update, context.error)
logger.info(f"The user data context: {context.user_data}") | 77,344 |
def git_to_filename(git_url):
"""
translates a git url to a file name
Parameters
----------
git_url: str
the url to the git repository
Returns
-------
str:
name of the file
"""
lib_file = git_url.replace('git+https://github.com/', '')
lib_file = lib_file.rep... | 77,345 |
def test_translate_invalid_input_type():
"""input type is not valid"""
obj = HumanReadableTranslator(INVALID_JSON, tolerance=LOW_TOLERANCE)
with pytest.raises(BadRequest):
obj.traslate() | 77,346 |
def nx_to_gdf(net, points=True, lines=True, spatial_weights=False, nodeID="nodeID"):
"""
Convert ``networkx.Graph`` to LineString GeoDataFrame and Point GeoDataFrame
Parameters
----------
net : networkx.Graph
``networkx.Graph``
points : bool
export point-based gdf representing i... | 77,347 |
def p2pkh(pubkey) -> Script:
"""Return Pay-To-Pubkey-Hash ScriptPubkey"""
return Script(b'\x76\xa9\x14'+hashes.hash160(pubkey.sec())+b'\x88\xac') | 77,348 |
def _extract_center_face(image_shape, detected_faces):
"""Extracts the face that's the closest to the center of a image.
### Parameters
image: image with the faces.
detected_faces: list of resulting bounding boxes and keypoints from\
MTCNN().detect_faces().
### Returns
(bounding_b... | 77,349 |
def list_files():
"""List files in nested subfolders."""
for root, subdirs, filenames in sorted(os.walk(SOURCE)):
for filename in filenames:
if not filename.endswith('dat'):
continue
yield join(root, filename) | 77,350 |
def get_county_polygons(county_ids: Optional[intseq], state_ids: Union[int, intseq]):
"""Get a dataframe with the polygons or multipolygons representing county borders
The returned dataframe will have the county polygons for each county listed. `county_ids` and `state_ids` may both
be scalar integers or li... | 77,351 |
def main():
"""
FUNCTION: main()
"""
# Read bin filename from the command line
filename = sys.argv[len(sys.argv) - 1]
# call bin2init() function
bin2init(filename) | 77,352 |
def add_xls_tag(file_name):
"""
Check the file_name to ensure it has ".xlsx" extension, if not add it
"""
if file_name[:-5] != ".xlsx":
return file_name + ".xlsx"
else:
return file_name | 77,353 |
def order_queryset_by_z_coord_desc(queryset, geometry_field="location"):
"""Order an queryset based on point geometry's z coordinate"""
return queryset.annotate(
z_coord=models.ExpressionWrapper(
models.Func(geometry_field, function="ST_Z"),
output_field=models.FloatField(),
... | 77,354 |
def err_number(error) :
""" Return a error number """
result = errOk
if isinstance(error, int) :
result = error
elif isinstance(error, Error) :
result = error.error_code
if result < 0 :
result = (result - ErrorBaseNumber) * -1
return result | 77,355 |
def value_iteration(env):
"""
Performs Value Iteration to find the most optimal policy for the
Tax-v3 environment
Args:
env: Taxiv3 Gym environment
Returns:
policy: the most optimum policy
"""
V = dict()
gamma = 0.9
state_size = env.observation_space.n
action_si... | 77,356 |
def keypoint_3d_pck(pred, gt, mask, alignment='none', threshold=150.):
"""Calculate the Percentage of Correct Keypoints (3DPCK) w. or w/o rigid
alignment.
Paper ref: `Monocular 3D Human Pose Estimation In The Wild Using Improved
CNN Supervision' 3DV'2017. <https://arxiv.org/pdf/1611.09813>`__ .
Note... | 77,357 |
def upload_blob(repository_ref, storage, settings, extra_blob_stream_handlers=None):
"""
Starts a new blob upload in the specified repository and yields a manager for interacting with
that upload.
When the context manager completes, the blob upload is deleted, whether committed to a blob or
not. Yi... | 77,358 |
def verbose_print(*args, **kwargs):
"""Prints only if -v or --verbose flag is set
"""
if VERBOSE:
print(*args, **kwargs) | 77,359 |
def mitochondrial_genes(host, org):
"""Mitochondrial gene symbols for specific organism through BioMart.
Parameters
----------
host : {{'www.ensembl.org', ...}}
A valid BioMart host URL.
org : {{'hsapiens', 'mmusculus'}}
Organism to query. Currently available are human ('hsapiens') ... | 77,360 |
def Bold(string):
"""Returns string wrapped in escape codes representing bold typeface."""
return '\x02%s\x0F' % string | 77,361 |
def test_create_repo(mock_download_file, load_test_data):
""" Test to create a rpm repository of out a dir. """
tmp_dir = tempfile.TemporaryDirectory()
config = Config("koji_fake_url", "koji_fake_storage", "mbs_fake_storage", "x86_64", ".")
build = load_test_data("pki_core_build")
tags = load_test_... | 77,362 |
def compile_src(commit_id, language):
"""将程序编译成可执行文件"""
commit = Commit.query.get(commit_id)
language = language.lower()
dir_work = os.path.join(work_dir, str(commit_id))
build_cmd = {
"c":
"gcc main.c -o main",
"c++": "g++ main.cpp -o main",
"java": "javac Main.java"... | 77,363 |
def from_bbox_array(bbox_array: List[decimal.Decimal]):
"""returns a geojson geometry object from a bounding box array.
Keeping default number of decimal places to 6 for now,
can change depending on data precision requirements."""
if bbox_array:
shapely_geometry = shapely.geometry.box(bbox_array... | 77,364 |
def Open(filename):
"""
You can open/read a Zype File with Open() function.
Usage: Open(filename)
Filename is the Zype File's Name.
"""
if os.path.isfile(filename):
with open(filename) as Zype:
content = Zype.read()
content = content.replace('<', ' "')
... | 77,365 |
def taiwanLightCompensation(im, theta=0.5, thresh=0.2, B=[10, 30]):
""" Perform light compensation
http://www.csie.ntu.edu.tw/~fuh/personal/LightCompensation.pdf
:param theta: weight of corrected image in final output
:return: light compensated image
"""
def getOptimalB(im, thresh, B):
... | 77,366 |
def _is_sweep_sequential(radar, sweep_number):
""" Test if a specific sweep is sequentially ordered. """
start = radar.sweep_start_ray_index['data'][sweep_number]
end = radar.sweep_end_ray_index['data'][sweep_number]
if radar.scan_type == 'ppi':
angles = radar.azimuth['data'][start:end+1]
el... | 77,367 |
def random_expand(image, boxes):
"""
Perform a zooming out operation by placing the image.
Helps to learn to detect smaller objects.
Args:
image(numpy.array): image, a array of dimensions (original_h, original_w, 3)
boxes(numpy.array): bounding boxes in boundary coordinates, a array of... | 77,368 |
def google_maps(query: str) -> bool:
"""Uses google's places api to get places near by or any particular destination.
This function is triggered when the words in user's statement doesn't match with any predefined functions.
Args:
query: Takes the voice recognized statement as argument.
Retur... | 77,369 |
def matMULTI(first,second):
"""
Take in two matrix
multiply each element against the other at the same index
return a new matrix
"""
newMAT = []
newCOL = []
for i in range(len(first)):
for j in range(len(first[i])):
newMAT.append(first[i][j]*second[i][j])
... | 77,370 |
def put_html(html, sanitize=False, scope=Scope.Current, position=OutputPosition.BOTTOM) -> Output:
"""
Output HTML content
:param html: html string
:param bool sanitize: Whether to use `DOMPurify <https://github.com/cure53/DOMPurify>`_ to filter the content to prevent XSS attacks.
:param int scope,... | 77,371 |
def check_enableusersite():
"""Check if user site directory is safe for inclusion
The function tests for the command line flag (including environment var),
process uid/gid equal to effective uid/gid.
None: Disabled for security reasons
False: Disabled by user (command line option)
True: Safe a... | 77,372 |
def show_outlierDetection(X, X_outliers, label_inlier, label_outlier, saveFileName, show):
"""
-> X is a numpy array containing tje training data
-> X_outliers is the data to test
=> seems to have problem when X is small
"""
n_outliers = len(X_outliers)
n_samples = len(X)
#X[-n_outliers:] = X_outliers
# fi... | 77,373 |
def convert_list2dict(word_list):
"""
把列表写成字典
"""
word_dict = defaultdict(int)
for w in word_list:
word_dict[w] = 1
return word_dict | 77,374 |
def GetAuthorizationCodeViaCommandLine(config):
"""Gets authorization code via command line.
This way is useful anywhere without a browser.
Args:
config: a dictionary of config.
Returns:
authorization code.
"""
body = urlencode({
'scope': config['scope'],
'redirect_uri': config['redir... | 77,375 |
def sync(config, state, catalog):
""" Sync data from tap source """
# Loop over selected streams in catalog created in discover()
for stream in catalog.get_selected_streams(state):
LOGGER.info("Syncing stream:" + stream.tap_stream_id)
bookmark_column = stream.replication_key
is_sort... | 77,376 |
def printUser(user: dict[Any, Any]):
"""Print user function."""
printf.logPrint(user["login"], LogType.BOLD)
printf.logPrint(user["html_url"]) | 77,377 |
def pedestal_ids_file(base_test_dir):
"""Mock pedestal ids file for testing."""
pedestal_ids_dir = base_test_dir / "auxiliary/PedestalFinder/20200117"
pedestal_ids_dir.mkdir(parents=True, exist_ok=True)
file = pedestal_ids_dir / "pedestal_ids_Run01808.0000.h5"
file.touch()
return file | 77,378 |
def test_argv(argv):
"""
Keyrings should initialize without error even
when sys.argv is malformed. Ref #445.
"""
code = f'import sys; {argv}; import keyring'
cmd = [sys.executable, '-c', code]
assert not subprocess.check_output(cmd, stderr=subprocess.STDOUT) | 77,379 |
def get_fa_icon_class(app_config):
"""Return Font Awesome icon class to use for app."""
if hasattr(app_config, "fa_icon_class"):
return app_config.fa_icon_class
else:
return 'fa-circle' | 77,380 |
def save_environment_agent_video(
filename: str,
agent: tf_agent.TFAgent,
tf_env: TFPyEnvironment,
py_env: TimeLimit,
num_episodes: int = 1,
) -> None:
"""
Save a video of an agent acting in the environment. Render method needs to be available in the
python version of the environment.
... | 77,381 |
def enqueue_source_create_or_update(source_id):
"""
Queues a source update event to be processed by the synchronize_sources method.
Args:
source_id (Integer) - Platform-Sources identifier.
Returns:
None
"""
source = get_source(
source_id, f"[enqueue_source_create_or_up... | 77,382 |
def linear_activation_forward(a_prev, w, b, activation):
"""
activation step for forward propagation with multiple choices of activation function.
@param a_prev: previous A from last step of forward propagation, numpy arrays
@param w: parameter W in current layer, numpy arrays
@param b: parameter b... | 77,383 |
def git_checkout(repo: Repo, git_ref: str) -> str:
"""
git_ref is of the form refs/heads/main or refs/tags/0.0.3
"""
git_dir = repo.directory
is_branch = git_ref.startswith('refs/heads/')
target = git_ref
if is_branch:
# We need the branch name
target = git_ref.split('/')[-1... | 77,384 |
def create_token(args):
"""
POST /api/v1/create_token HTTP/1.1
Host: 127.0.0.1:5000
Content-Type: application/json
Content-Length: 74
{
"name":"1234",
"password" :"1234",
"email" : "1234",
"duration":123
}
{"access_token":"ad236cdb-f645-456c-918c-dd8d808... | 77,385 |
def getDictionary(id_or_identifier):
"""
指定した id または identifier を持つ辞書のメタデータを返します。
id, identifier に一致する辞書が存在しない場合は None を返します。
Parameters
----------
id_or_identifier : str or int
str の場合は辞書 identifier で指定。
int の場合は内部辞書 id で指定。
Returns
-------
Metadata
Metadat... | 77,386 |
def load_import_config(project: Project) -> Optional[ImportConfig]:
"""
Loads the import config for the project (if it exists, otherwise None is returned):
"""
import_path = os.path.join(project.folder(), IMPORT_PROJECT_FILENAME)
if not os.path.exists(import_path):
return None
local_pat... | 77,387 |
def is_phone_in_call(log, ad):
"""Return True if phone in call.
Args:
log: log object.
ad: android device.
"""
return ad.droid.telecomIsInCall() | 77,388 |
def omicron_model(
xs: np.ndarray,
ts: np.ndarray,
params: dict
) -> np.ndarray:
"""
SL_2I_4R model with dual immunity
:param np.ndarray xs: actual array of states
:param np.ndarray ts: time values
:param dict params: dictionary of parameters
:return np.ndarray
""... | 77,389 |
def identity(n):
""" Return n """
return n | 77,390 |
def look_for_general(
m_str: str,
ref_dict: defaultdict,
base_num: t.Pattern[str],
full_num: t.Pattern[str],
doc_type: str,
) -> defaultdict:
"""
Reference Extraction by Regular Expression: For general use
Args:
m_str: text string to search
ref_dict: dictionary of refere... | 77,391 |
def losses_and_metrics(num_classes):
"""
Define loss and metrics
Loss: Categorical Crossentropy
Metrics: (Train, Validation) Accuracy, Precision, Recall, F1
Returns:
loss, train loss, train acc, valid loss, valid acc, precision, recall, auc, f1
"""
loss_fn = CategoricalCrossentropy... | 77,392 |
def BakeBadge(imageFile: Path, outputFile: Path, json_string: str) -> None:
"""
imageFile: 元ネタの画像ファイル pngまたは、svg への path + filename
outputFile: 出力する png または、svg への path + filename
json_string: 焼きこむjsonの文字列
subprocess.run を用いて bakery bake コマンドを起動する。
shell インジェクションを警戒するので、引数には、空白やアスタリスクなどの
s... | 77,393 |
def get_skill_from_model(skill_model):
"""Returns a skill domain object given a skill model loaded
from the datastore.
Args:
skill_model: SkillModel. The skill model loaded from the
datastore.
Returns:
skill. A Skill domain object corresponding to the given
skill mo... | 77,394 |
def get_loaders(dataset_path, batch_size=32, num_workers=12, mean=None, std=None):
"""
Function to load the train/test loaders.
Parameters
----------
dataset_path: str, dataset path.
batch_size: int, batch size.
num_workers: int, number of workers.
mean:None or torch.Tensor, mean per c... | 77,395 |
def delete_tags_for_manifest(manifest):
""" Deletes all tags pointing to the given manifest. Returns the list of tags
deleted.
"""
query = Tag.select().where(Tag.manifest == manifest)
query = filter_to_alive_tags(query)
query = filter_to_visible_tags(query)
tags = list(query)
now_ms = get_epoch_ti... | 77,396 |
def eeg_epochs_dataset(subject, trial, config, preload=True):
"""Get the epoched eeg data excluding unnessary channels
from fif file and also filter the signal.
Parameter
----------
subject : string of subject ID e.g. 7707
trial : HighFine, HighGross, LowFine, LowGross
Returns
------... | 77,397 |
def excel_writer(data, out_file):
"""
The excel_writer function handles the main logic of writing
the excel output
:param data: the list of lists containing parsed UA data
:param out_file: the desired output directory and filename
for the excel file
:return: Nothing
"""
print('[+] Writing ... | 77,398 |
def differences(lis, n=1):
"""
Returns the `n` successive differences of the elements in
`lis`.
EXAMPLES::
sage: differences(prime_range(50))
[1, 2, 2, 4, 2, 4, 2, 4, 6, 2, 6, 4, 2, 4]
sage: differences([i^2 for i in range(1,11)])
[3, 5, 7, 9, 11, 13, 15, 17, 19]
... | 77,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.