content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_key_metrics_fig(confirmed_ser, recovered_ser, deaths_ser, metric_type):
"""
Return key metrics graph object figure
Parameters
----------
confirmed_ser: pandas.Series
Confirmed pandas series objects with index=dates,
values=number of cases
r... | a11130a21d124c2bf44a02d9c3c58bcde5a326cb | 3,636,900 |
from re import A
from re import I
from re import T
def cms_post_popup(r):
"""
Customized Map popup for cms_post resource
- style like the cards
- currently unused
"""
record = r.record
pkey = "cms_post.id"
# Construct the item ID
map_id = "default_map" # @ToDo: provid... | c0ee3430d1fbee769c708df93f03748ab3c0554b | 3,636,901 |
from typing import List
def pr_curve(results: List[TrecEvalResults]) -> plt:
"""
Create a precision-recall graph from trec_eval results.
:param results: A list of TrecEvalResults files.
:return: a matplotlib plt object
"""
names = [r.run_id for r in results]
iprec = [[r.results['ipre... | 90f1e3234304fa7966b93ebdc76235e5356002e6 | 3,636,902 |
def plotData(datalist, part = "real", progressive = True, color = None, clip = False, tcutoff = None):
"""Plot real or imaginary parts of a given list of functions.
arguments:
datalist (list of tuples, each tuple of form (xlist,ylist)): data to plot;
xlist should be real numbers, ylist can be comp... | 5e328c19fe63389d7f2d55e5fd5d75d2dd5d7c24 | 3,636,903 |
def train_and_test(model, dataset, robustness_tests=None, base_config_dict=None, save_model=True):
"""
Train a recommendation model and run robustness tests.
Args:
model (str): Name of model to be trained.
dataset (str): Dataset name; must match the dataset's folder name located in 'data_pat... | 3681bc732b2b39837c871267f4659825105d6e2b | 3,636,904 |
def total_cost(content_cost, style_cost, alpha, beta):
"""Return a tensor representing the total cost."""
return alpha * content_cost + beta * style_cost | 98d42bd8d62dc8cd7110b2f5eb9a9a4e4eb6bc65 | 3,636,905 |
def create_command_using_pip_action(
num_bash_entries=10, uninstall_use_creation_time=False, skip=0):
"""Create commands using latest pip action."""
valid_pip_commands = get_valid_pip_history(num_bash_entries)[skip:]
assert valid_pip_commands, 'No undoable pip commands.'
last_valid_pip_command =... | 5ba22f63d33c1ae60ec3a93590965453885e5e29 | 3,636,906 |
def extract_word_pos_sequences(form, unknown_category, morpheme_splitter=None, extract_morphemes=False):
"""Return the unique word-based pos sequences, as well as (possibly) the morphemes, implicit in the form.
:param form: a form model object
:param morpheme_splitter: callable that splits a strings into i... | e08c285910c4da2f827f81ac65abc2ee3d62b1dc | 3,636,907 |
def model_test(Py, Px_y, testDataArr, testLabelArr):
"""
模型测试
@Args:
Py: 先验概率分布
Px_y: 条件概率分布
testDataArr: 测试集数据
testLabelArr: 测试集标签
@Returns:
准确率
@Riase:
"""
# 错误值
errorCnt = 0
# 循环遍历测试集中的每一个样本
for i in range(len(testDataArr... | f1e06725511750c79e34dc528728aab8cebc7c34 | 3,636,908 |
from typing import Optional
import torch
def int2c2e(shortname: str, wrapper: LibcintWrapper,
other: Optional[LibcintWrapper] = None) -> torch.Tensor:
"""
2-centre 2-electron integrals where the `wrapper` and `other1` correspond
to the first electron, and `other2` corresponds to another electr... | 1f5b6c70c8373c885103d6deb7cba77ea8d0aa73 | 3,636,909 |
def send_group_membership_request(request, group_id, template='group_send_request.html'):
"""
Send membership request to the administrator
of a private group.
"""
if request.method == 'POST':
form = GroupMembershipRequestForm(request.POST)
if form.is_valid():
group = Grou... | 22324765a915e1677fb6abab41dfa214fcc05d40 | 3,636,910 |
import sys
import os
import argparse
import logging
def arg_parse():
"""Base all default folders from script location
scripts: ./pymetric/tools/cimis
tools: ./pymetric/tools
output: ./pymetric/cimis
"""
script_folder = sys.path[0]
code_folder = os.path.dirname(script_folder)... | 05e5d5d33a475e25a76267c3aa8812f11084d9a1 | 3,636,911 |
def _dataset_type_dir(signer):
"""Returns the directory name of the corresponding dataset type.
There is a `TFRecord` file written for each of the 25 signers. The `TFRecord` files of the first 17 signers are
assigned to the train dataset, the `TFRecord` files of the next 4 signers are assigned to the valid... | 515fd2e0871cf9549f3f724da0b45bb07f09e24b | 3,636,912 |
def _merge_blanks(src, targ, verbose=False):
"""Read parallel corpus 2 lines at a time.
Merge both sentences if only either source or target has blank 2nd line.
If both have blank 2nd lines, then ignore.
Returns tuple (src_lines, targ_lines), arrays of strings sentences.
"""
merges_done = [] #... | fe5f765022b2b4de5320272701148cc9f8e691b8 | 3,636,913 |
import codecs
def get_line(file_path, line_rule):
"""
搜索指定文件的指定行到指定行的内容
:param file_path: 指定文件
:param line_rule: 指定行规则
:return:
"""
s_line = int(line_rule.split(',')[0])
e_line = int(line_rule.split(',')[1][:-1])
result = []
# with open(file_path) as file:
file = codecs.o... | a6ccda48f8083e5ff6827306f4abd7f19e8d445c | 3,636,914 |
def _generate_odd_sequence(sequence_id: int, start_value: int,
k_factor: int, max_iterations: int):
"""
This method generates a Collatz sequence containing only odd numbers.
:param sequence_id: ID of the sequence.
:param start_value: The integer value to start with. The value... | d886631d153531fafa2cd9b15be621df9746a909 | 3,636,915 |
import os
import cpuinfo
def find_initcpio_features(partitions, root_mount_point):
"""
Returns a tuple (hooks, modules, files) needed to support
the given @p partitions (filesystems types, encryption, etc)
in the target.
:param partitions: (from GS)
:param root_mount_point: (from GS)
:re... | 9e35e597af3b3ac1d5bd749740491ffa728d2130 | 3,636,916 |
def _is_unique_rec_name(info_name):
"""
helper method to see if we should use the uniqueness recommendation on the
fact comparison
"""
UNIQUE_INFO_SUFFIXES = [".ipv4_addresses", ".ipv6_addresses", ".mac_address"]
UNIQUE_INFO_PREFIXES = ["fqdn"]
if info_name.startswith("network_interfaces.lo... | cba744e1e5b6a9612363d2ca12d4751e1894c8ad | 3,636,917 |
def initialized():
"""
Connection finished initializing?
"""
return __context__["netmiko_device"].get("initialized", False) | 6ca85744478bdb17ac99ce827825cde1db8bae3a | 3,636,918 |
def n_round(a, b):
"""safe round"""
element_round = np.vectorize(np.round)
return element_round(a, intify(b)) | 2c38e1585b71d5717ea3cc560521b8a006ceeee3 | 3,636,919 |
def _json_view_params(shape, affine, vmin, vmax, cut_slices, black_bg=False,
opacity=1, draw_cross=True, annotate=True, title=None,
colorbar=True, value=True):
""" Create a dictionary with all the brainsprite parameters.
Returns: params
"""
# Set color pa... | 50ea71a5a99facf4c472f0c18984d84e23b8e301 | 3,636,920 |
from typing import List
from datetime import datetime
def get_timestamps_from_df_data(df) -> List[datetime.datetime]:
"""Get a list of timestamp from rows of a DataFrame containing
raw data.
"""
timestamps = []
for index, row in df.iterrows():
year = int(row["dteday"][:4... | 21f985ebf28d6f5819635a13294e8db0544a292b | 3,636,921 |
def debug_user(request):
"""
Allows superusers to log in as a regular user to troubleshoot problems.
"""
if not settings.DEBUG:
messages.error(request, "Can only use when in debug mode.")
redirect("/")
target = request.GET.get("uid", "")
profile = Profile.objects.filter(uid=tar... | 73a1f3cfdaa45a5693c9589c012206f6d83d56d0 | 3,636,922 |
def select(var_name, attr_name=None):
"""
Return attribute(s) of a variable given the variable name and an optional field name, or list of attribute name(s)
:param var_name: Name of the variable we're interested in.
:param attr_name: A string representing the name of the attribute whose value we want to... | 22b65439ff4dc831c2fb334595b0f0cd2e764b67 | 3,636,923 |
import re
def _parseWinBuildTimings(logfile):
"""Variant of _parseBuildTimings for Windows builds."""
res = {'Compile': re.compile(r'\d+>Time Elapsed (\d+):(\d+):([0-9.]+)'),
'Test running': re.compile(r'.*?\.+.*?([0-9.]+) sec')}
times = dict([(k, 0.0) for k in res])
for line in logfile:
... | 0473c426d29bb7fe44ff3384f81962f121c11afa | 3,636,924 |
import typing
import requests
def _try_to_extract_issuing_url_from_well_known_metadata(well_known_address: str) -> typing.Optional[str]:
"""
Try to extract token issuing url from well-known location
:param well_known_address: well-known URL
:type well_known_address: str
:return: str or None -- to... | 209a521fe29c8f47b7bc63207cdbc5736d053887 | 3,636,925 |
def get_malid(anime: AnimeThemeAnime) -> int:
"""
Returns anime theme of resource.
"""
for resource in anime['resources']:
if resource["site"] == "MyAnimeList":
return resource['external_id'] | a745f95e73e8e061d98100e314faf5a662d69693 | 3,636,926 |
import glob
def wav16khz2mfcc(dir_name):
"""
Loads all *.wav files from directory dir_name (must be 16kHz), converts them into MFCC
features (13 coefficients) and stores them into a dictionary. Keys are the file names
and values and 2D numpy arrays of MFCC features.
"""
features = {}
for ... | 6eae15a7ac999cd42c1e3161221356cf720d54c0 | 3,636,927 |
def add_metadata(infile, outfile, sample_metadata):
"""Add sample-level metadata to a biom file. Sample-level metadata
should be in a format akin to
http://qiime.org/tutorials/tutorial.html#mapping-file-tab-delimited-txt
:param infile: String; name of the biom file to which metadata
... | e779f876159741de60e99002a90906b151dc7530 | 3,636,928 |
def multinomial(n):
"""Finds the multinomial coefficient for a given array of numbers.
Args:
n (list): the interegs to be used.
"""
binomials = [[np.sum(n),n[0]]]
for i in range(1,len(n)):
new_sum = binomials[i-1][0]-binomials[i-1][1]
binomials.append([new_sum,n[i]])
... | 6f38656d295a4d5ecf32a01a238cdad701e6e530 | 3,636,929 |
def get_qc_data(sample_prj, p_con, s_con, fc_id=None):
"""Get qc data for a project, possibly subset by flowcell.
:param sample_prj: project identifier
:param p_con: object of type <ProjectSummaryConnection>
:param s_con: object of type <SampleRunMetricsConnection>
:returns: dictionary of qc resul... | f267148f48f86151852e12fa3be8d5f8aefc6b11 | 3,636,930 |
def sql_sanitize(sql_name):
"""
Return a SQL name (table or column) cleaned of problematic characters.
ex. punctuation )(][; whitespace
Don't use with values, which can be properly escaped with parameterization.
Ideally retaining only alphanumeric char.
Credits: Donald Miner, Source: StackOverfl... | 9ce9e0e8bed2348079fb23f2d27c53880fa1c795 | 3,636,931 |
import os
def add_event_number(job_metrics, workdir):
"""
Extract event number from file and add to job metrics if it exists
:param job_metrics: job metrics (string).
:param workdir: work directory (string).
:return: updated job metrics (string).
"""
path = os.path.join(workdir, 'eventLo... | f4ac76a01ac9bb4ce5dec8baf754d54b6e1ac4e2 | 3,636,932 |
def exists(name):
"""
`True` if a category named `name` exists;
`False` otherwise.
"""
return db.cursor().execute('SELECT COUNT(*) FROM categories WHERE name = ?', (name,)).fetchone()[0] != 0 | e15f5d961a4420ef6bd00fa393ab9af440e5f983 | 3,636,933 |
def ESMP_MeshGetOwnedElementCount(mesh):
"""
Preconditions: An ESMP_Mesh has been created.\n
Postconditions: The owned elementCount for 'mesh' has been
returned.\n
Arguments:\n
:RETURN: integer :: elementCount\n
ESMP_Mesh :: mesh\n
"""
lec = ct.c_int(0)... | 067411ba3b2fbc4f862375e2a3699d617999b6ed | 3,636,934 |
def remove_control_chars_author(input):
"""
:param input:
:return:
"""
return CONTROL_CHAR_RE.sub('', input) | 632bb20de05f3461156fa7ed311b9a04459de60f | 3,636,935 |
def run():
"""Default Run Method"""
return problem51(8) | 3357bb4e6461f8142f93fc394f3b5aba0fba7ceb | 3,636,936 |
def calc_c(e, a, b, u=1): # Check units
"""
calculate the z components of 4 partial waves in medium
e: dielectric tensor
a,b: components of wavevector in direction of x and y direction
return a list containting 4 roots for the z components of the partial waves
"""
# assign names
x = ... | 46a1ae481c9525ecc7ae1e5e3b119b8d3983ca16 | 3,636,937 |
from typing import Sequence
from typing import Tuple
def _jax_decode(
compressed_message: ndarray,
tail_limit: int,
message_len: int,
message_shape: Sequence[int],
codec: CrayCodec,
cdf_state: Sequence[ndarray],
) -> Tuple[Tuple[ndarray, int], ndarray, Sequence[ndarray]]:
"""
JAX rANS ... | 648cb4af4ddaaec01e5d5997e8698aad6acd4c01 | 3,636,938 |
def subtask1_eval(_answers, _ref):
"""
子任务1的评分函数。
:param _answers: 答卷答案。
:param _ref: 参考答案。
:return: 统计数据对象。
"""
_map = {
'11': 'TP',
'00': 'TN',
'10': 'FN',
'01': 'FP',
}
_st = {
'TP': 0,
'TN': 0,
'FN': 0,
'FP': 0,
... | 7249992f70b67928a99e96c7877e5ef4be261429 | 3,636,939 |
def render_horizontal_fields(*fields_to_render, **kwargs):
"""Render given fields with optional labels"""
labels = kwargs.get('labels', True)
media = kwargs.get('media')
hidden_fields = []
visible_fields = []
for bound_field in fields_to_render:
if bound_field.field.widget.is_hidden:
... | 22ac9c05b602c0f65ab2fc348ab9399855780bc3 | 3,636,940 |
def get_darwin_memory():
""" Use system-call to extract total memory on macOS """
system_output = sabnzbd.newsunpack.run_simple(["sysctl", "hw.memsize"])
return float(system_output.split()[1]) | 1458881c61cdb5b765c4c56fa494ff7c6f06c49b | 3,636,941 |
from datetime import datetime
def parseTextModeTimeStr(timeStr):
""" Parses the specified SMS text mode time string
The time stamp format is "yy/MM/dd,hh:mm:ss±zz"
(yy = year, MM = month, dd = day, hh = hour, mm = minute, ss = second, zz = time zone
[Note: the unit of time zone is a quarter of an... | 52a45116a2b0153595161f94fda38129ddd59b3a | 3,636,942 |
import torch
def angle_to_rotation_matrix(angle) -> Tensor:
"""
Creates a rotation matrix out of angles in degrees
Args:
angle: (Tensor): tensor of angles in degrees, any shape.
Returns:
Tensor: tensor of *x2x2 rotation matrices.
Shape:
- Input: :math:`(*)`
- Outp... | 9b88eaa0277d0c3ad672e94e4d41ec45ebe0b272 | 3,636,943 |
def extract_text():
"""Extracts text from an HTML document."""
html = request.form['html']
article = Article(html)
try:
return article.text
except AttributeError as e:
log.warn(e)
# NOTE: When a parsing error occurs, an AttributeError is raised.
# We'll deal with this... | 8efc10539462ab51715b54b17a018e5f296496eb | 3,636,944 |
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... | 4433b080b24d1a7ad276541103e55acf7bbfa137 | 3,636,945 |
from typing import List
def lag_indexes(tf_stat)-> List[pd.Series]:
"""
Calculates indexes for 3, 6, 9, 12 months backward lag for the given date range
:param begin: start of date range
:param end: end of date range
:return: List of 4 Series, one for each lag. For each Series, index is date in ran... | de8d355d213146013eb4720860dd844d22ccab45 | 3,636,946 |
def weather_outfit(req):
"""Returns a string containing text with a response to the user
with a indication if the outfit provided is appropriate for the
current weather or a prompt for more information
Takes a city, outfit and (optional) dates
uses the template responses found in weather_responses.... | ee5b3cd3ed10062155bbce532343ef51f9a83177 | 3,636,947 |
from sentence_splitter import SentenceSplitter
def parse_paragraphs(record):
"""
parse paragraphs into sentences, returns list
"""
splitter = SentenceSplitter(language='en')
sentences=splitter.split(record['value'])
article_id = remove_prefix(record['key'],'paragraphs:')
pre = 'sentence:' ... | 9a8cce4692af5e61b9f01becd8dafa9234c08f17 | 3,636,948 |
def get_stage_environment() -> str:
"""
Indicates whether the source is running as PRD or DEV. Accounts for the
user preference via TEST_WORKING_STAGE.
:return: One of the STAGE_* constants.
"""
return TEST_WORKING_STAGE | 1c2e14132af1760a13aae268b5179e70c79f5df5 | 3,636,949 |
def get_all_table_acls(conn, schema=None):
"""Get privileges for all tables, views, materialized views, and foreign
tables.
Specify `schema` to limit the results to that schema.
Returns:
List of :class:`~.types.SchemaRelationInfo` objects.
"""
stmt = _table_stmt(schema=schema)
retu... | 9067a614197d19c3256828b2a8dbb491bede0fe6 | 3,636,950 |
def add_atom_map(molecule, **kwargs):
"""
Add canonical ordered atom map to molecule
Parameters
----------
molecule :
`oechem.OEMOl` or `rdkit.Chem.Mol`
Returns
-------
molecule with map indices
"""
toolkit = _set_toolkit(molecule)
return toolkit.add_atom_map(molecu... | 584324aae018f211fc31c9f727687e9a6971822d | 3,636,951 |
from typing import Any
def build_put_dictionary_request(*, json: Any = None, content: Any = None, **kwargs: Any) -> HttpRequest:
"""Put External Resource as a Dictionary.
See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder
into your code flow.
:keyword jso... | 045c00835d592d777a155696bda76a5ecb12aa6f | 3,636,952 |
def midpoint(rooms):
"""
Helper function to help find the midpoint between the two rooms.
Args:
rooms: list of rooms
Returns:
int: Midpoint
"""
return rooms[0] + (rooms[0] + rooms[2]) // 2, rooms[1] + (rooms[1] + rooms[3]) // 2 | 60b3ba53fb15154ff97ab9c6fa3cf1b726bc2df1 | 3,636,953 |
def secondSolution( fixed, c1, c2, c3 ):
"""
If given four tangent circles, calculate the other one that is tangent
to the last three.
@param fixed: The fixed circle touches the other three, but not
the one to be calculated.
@param c1, c2, c3: Three circles to which the other tangent c... | a5f7545a3c4600e29bfdb9c516ede6ba244894c3 | 3,636,954 |
import random
def generate_concept_chain(concept_desc, sequential):
"""
Given a list of availiable concepts, generate a dict with (start, id) pairs
giving the start of each concept.
Parameters
----------
sequential: bool
If true, concept transitions are
determined by ID witho... | fcfeb345d92d627684d04da4c1d445120554bf15 | 3,636,955 |
def get_inputs(input_queue,
num_classes,
merge_multiple_label_boxes=False,
use_multiclass_scores=False):
"""Dequeues batch and constructs inputs to object detection model.
Args:
input_queue: BatchQueue object holding enqueued tensor_dicts.
num_classes: Number of... | 96185efe5e1b6ee3064136e052387da0bfb1ddaa | 3,636,956 |
def doFilter(pTable, proxyService):
"""
filter candidates by column header candidates
- column headers are kept, if they support at least (minSupport * #rows) many cells
- only filter for columns that are part of the targets (if activated)
subsequently remove:
- CTA candidates with less support... | 8b28f945e94e37302b2086e23f695c40c08b8d7c | 3,636,957 |
def int_or_float(x):
"""Convert `x` to either `int` or `float`, preferring `int`.
Raises:
ValueError : If `x` is not convertible to either `int` or `float`
"""
try:
return int(x)
except ValueError:
return float(x) | d0a4def320f88655e494f89b7239e47e1ee70d0d | 3,636,958 |
def request_factory():
"""Pytest setup for factory."""
return RequestFactory() | d6b5710dd42da06f6bb10e23fe3826a6a754228a | 3,636,959 |
def is_onehotencoded(x):
"""If input is a one-hot encoded representation of some set of values.
Parameters
----------
x : array-like
Returns
-------
bool
Whether `x` is a one-hot encoded / categorical representation.
"""
if x.ndim != 2:
return False
fractional,... | 21a023afeec886512ef806c76ade5523817ef350 | 3,636,960 |
def sequence_of_words(fname_doc, dictionary):
"""
Compute Sequence-of-Words from word list and dictionary
"""
txtdata = loadtxt(fname_doc)
words = extract_keyword(txtdata, "all")
SOW = []
for i,word in enumerate(words):
print(word)
if word in dictionary.keys():
S... | 92aeb61ce91b7149143bfb67905793caee83d3be | 3,636,961 |
def shd(B_est, B_true):
"""Compute various accuracy metrics for B_est.
true positive = predicted association exists in condition in correct direction
reverse = predicted association exists in condition in opposite direction
false positive = predicted association does not exist in condition
Args:
B_true (np.nda... | 04c1fb44025ae1a3cfd86bc877c68e93027b75fe | 3,636,962 |
from typing import Any
import time
import copy
import os
def test_separate_networks(
configs: dict[str, Any],
make_plots: bool = True,
**kwargs,
) -> TestOutputs:
"""Test training on separate networks."""
t0 = time.time()
logger.info(f'Testing separate networks')
configs_ = dic... | 246f608af98a41ed138ac5c80314661b29a88e07 | 3,636,963 |
def nohighlight(nick):
"""add a ZWNJ to nick to prevent highlight"""
return nick[0] + "\u200c" + nick[1:] | 1b8d0cafc5df4a442daafdece59af1675ab1de33 | 3,636,964 |
def _get_r_val(z, omega_m, omega_l):
"""Returns the comoving distance at for one z value.
Parameters
----------
z : float
Redshift.
omega_m : float
Present matter density.
omega_l : float
Present dark energy density.
"""
r, err = integrate.quad(_get_r_integrand, ... | 4f33eccdf4485c640f5c71808485fbf96a5f7614 | 3,636,965 |
def user_response_controller(bank_request, user_response):
"""
processes user's response for bank's request sent
: bank_request --> what is user currently requesting for
: user_response --> what a user wants to actually do amongst the options in the
above bank_requests
"""
user_re... | 3d959fac84a8460e7ab228127d9b6f0b9cc1a21c | 3,636,966 |
from datetime import datetime
def create_features(datestrs):
"""
Find the features associated with a set of dates.
These will include:
weekday / weekend
day of week
season
month of year
Parameters
----------
datestrs: list of strings
Date strings of the... | 75a72a54396150ed73ea43b3390994b1a41d2cf5 | 3,636,967 |
import inspect
def obj_src(py_obj, escape_docstring=True):
"""Get the source for the python object that gets passed in
Parameters
----------
py_obj : callable
Any python object
escape_doc_string : bool
If true, prepend the escape character to the docstring triple quotes
Retu... | 8ce0c7cc7672de5005b5a1c60e6b6cf5fa9ee050 | 3,636,968 |
def get_back_button_handler(current_panel: "GenericPanel") -> CallbackQueryHandler:
"""
returns a Handler for BACK_PATTERN that returns the user to current_panel
:param GenericPanel current_panel: the destination panel
:return: a CallbackQueryHandler for BACK_PATTERN that returns the user to current_pa... | 365e37b3d362afa31d231613180070be69ac7972 | 3,636,969 |
from typing import Optional
def openocd_prog_path(request: FixtureRequest) -> Optional[str]:
"""Enable parametrization for the same cli option"""
return _request_param_or_config_option_or_default(request, 'openocd_prog_path', None) | f3628427bde73d7e26e5ed30e103d4ba36df7c1b | 3,636,970 |
def reindexMatrix(iss, jss, A):
"""iss and jss are lists of indices of equal size, representing
a permuation: iss[i] is replaced with jss[i]. all other indices which are
not in the lists left unchanged.
"""
n = len(A)
B = np.zeros_like(A)
tss = [i for i in range(n)]
for i in range(len(is... | 9c36802d7e5f35ca6789d49e47d8124bc4f74c57 | 3,636,971 |
def createInfoMatix(character_id):
"""初始化创建的角色的阵法
"""
petlist = getCharacterPetList(character_id)
sql = "INSERT INTO `tb_character_matrix`(`characterId`,`eyes_4`,`eyes_5`,`eyes_6`) \
VALUES(%d,%d,%d,%d);"%(character_id,petlist[0],petlist[1],petlist[2])
conn = dbpool.connection()
cursor = co... | 7392f899ed8b46fd35ed360601edd8621aace7ac | 3,636,972 |
def help():
"""<b>Print available functions as json.<br>"""
func_list = {}
for rule in app.url_map.iter_rules():
if rule.endpoint != 'static':
func_list[rule.rule] = app.view_functions[rule.endpoint].__doc__
return jsonify(func_list) | 2ef2193aaa9d882b238a7681cb3e868690a58398 | 3,636,973 |
import os
async def grid_train(params: Grid, background_tasks: BackgroundTasks, credentials: HTTPBasicCredentials = Depends(validate_access)):
"""
Choose an estimator, and hyper-parameters to optimize for a GridSearchCV. Results can be recorded in Neptune.ai.
"""
try:
X_train, X_test, y_train... | 30f68446ac1fb0d9bd76a54a11a99540fb9a32d6 | 3,636,974 |
def version():
"""
Returns the name, version and api_version of the application when
a HTTP GET request is made.
"""
return jsonify(
name='openshift-python-flask-sample',
version=VERSION
) | 70686195978cf9d26e2d4cd954c81fc216d7bd4d | 3,636,975 |
import json
def search_quotes(request, currency):
""" Consulta a API procurando por ações que contenham o campo 'currency' no nome """
# verifica se a barra de pesquisa foi preenchida ou se está vazia
if currency:
conn.request("GET", "/auto-complete?q="+currency+"®ion=BR", headers=headers)
... | 926f29d802a7bb6a9681b3b90fd46966894a0604 | 3,636,976 |
def destroy(N, dtype=tf.complex64):
"""Returns a destruction (lowering) operator in the Fock basis.
Args:
N (int): Dimension of Hilbert space
dtype (tf.dtypes.DType, optional): Returned dtype. Defaults to c64.
Returns:
Tensor([N, N], dtype): NxN creation operator
"""
a = diag... | a92ef2cc5aa9b7bbe2c0cf109282c5fde56d4603 | 3,636,977 |
from typing import Optional
from typing import Any
def get_nearest_operation(
db: Redis[bytes], address: hash_t, subdag: Optional[str] = None
) -> Optional[Operation]:
"""Return the operation at address or the operation generating address."""
root = "root"
art = None
try:
node = Operation.... | a402ed795d60f321cd362517e9350994be836cdd | 3,636,978 |
def load_CIFAR_batch(file_path):
""" load single batch of cifar """
data_dict = load_pickle(file_path)
data = data_dict['data']
labels = data_dict['labels']
data = data.reshape(10000, 3, 32, 32).astype("float")
labels = np.array(labels)
return data, labels | 0164293fb2f31e7361da5a817c64899db96c6156 | 3,636,979 |
def _disposable_and_async_gen_from_obs(obs: Observable):
"""
Compatability layer for legacy Observable to async generator
This should be removed and subscription resolvers changed to
return async generators after removal of flask & gevent based dagit.
"""
queue: Queue = Queue()
disposable ... | ed0620b3615a36e82c20789f6a3b40aa6ae61410 | 3,636,980 |
def interesting_pattern(x: float, y: float) -> float:
"""This function is interesting in x and y in range -10..10, returning
a float value in range 0..1
"""
z = 0.5 + (np.sin(x) ** 10 + np.cos(10 + y * x) * np.cos(x)) / 2
return z | 432e13324b1834cbdd62259f0ac0b59751008f90 | 3,636,981 |
import logging
def cut(st, sec_before_split=None):
"""
Cut/trim the record.
This method minimally requires that the windows.signal_end method has been
run, in which case the record is trimmed to the end of the signal that
was estimated by that method.
To trim the beginning of the record, the... | e71d8a7635aa35dc5746541f00f90d991b4c4e62 | 3,636,982 |
def interp_road(d,croad,roads,intersections,normD = False):
""" Get the position of a point along a road """
start_int = roads[croad]['start_int']
start_pos = intersections[start_int]['position']
end_int = roads[croad]['end_int']
end_pos = intersections[end_int]['position']
if not normD:
... | f6406dbb586ba2870d95f627f18085ec12c3b64b | 3,636,983 |
def zero_pad2d(inputs, padding=0, output_dtype="float32", requires_grad=False):
"""
Zero padding for 2d tensor
Args:
-----------------------------
inputs : Tensor
shape [batch, channel, height, width]
padding: (optional:0) int or tuple
expected: (h_pad_up, h_pad_down, w_pad_up, ... | 77ae8065f6e1c3b181a6bb49bd84ae4951848d7b | 3,636,984 |
def gtfs_admin(request):
"""admin page for adding new review categories (and potentially other features down the road)"""
return render(request, 'admin/gtfs_admin.html') | 14fccf4c1a8758fa223133f6e191860b6aee01a9 | 3,636,985 |
def get_file_path():
"""
Get current file's directory.
Return `None` if there is no file path available.
"""
try:
file_path = sublime.active_window().extract_variables()['file_path']
except KeyError:
return None
else:
return file_path | 0f991da4edf82435260aad443a4b506d1e2a5453 | 3,636,986 |
import random
def mutate_word(word):
"""Introduce a random change into the word: delete, swap, repeat, and add
stray character. This may raise a ValueError. """
word = list(word)
choice = random.randrange(4)
if choice == 0: # Delete a character
word.pop(random.randrange(len(word)))
... | f3b45f36893a7541131710ada5f1343387f06797 | 3,636,987 |
def data_layer_property_from_dict(data_layer_property_dictionary: dict,
client: cl.Client = None):
"""
The method converts a dictionary of DataLayerProperty to a DataLayerProperty object.
:param data_layer_property_dict: A dictionary that contains the keys of a Data... | ab579c1d6527abb176cd05c81d89fb1a74af50b0 | 3,636,988 |
def pcc_vector(v1, v2):
"""Pearson Correlation Coefficient for 2 vectors
"""
len1 = len(v1)
len2 = len(v2)
if len1 != len2:
return None
else:
length = len1
avg1 = 1.0 * sum(v1) / len(v1)
avg2 = 1.0 * sum(v2) / len(v2)
dxy = [(v1[i] - avg1) * (v2[i] - avg2) for i in ra... | 98e5f3cc304a5d844be479d65ab7eeb760a34ba3 | 3,636,989 |
from io import StringIO
def cypher_repr(obj):
""" Generate the Cypher representation of an object.
"""
string = StringIO()
writer = CypherWriter(string)
writer.write(obj)
return string.getvalue() | eae9e848076a4626a001e70b9cd925734864b3ae | 3,636,990 |
def firstlastmile_pipeline(**kwargs):
"""The first and last mile pipeline attaches any unattached elements to ensure a fully-connected graph"""
tags = ['flmile']
firstmile_nodes = [
node(
firstmile_edge,
['sjoin_oilfields_data','sjoin_edges_pipelines_oilfields','sjoin_po... | 545fda88458fb0266b0f4f98791de83759ba96f5 | 3,636,991 |
def photo_new(request, cast: Cast):
"""
Add a new Photo to a cast
"""
if request.method == 'POST':
form = CastPhotoForm(request.POST, request.FILES)
if form.is_valid():
photo = form.save(commit=False)
photo.cast = cast
photo.save()
messages... | cf9aac5f0ea49e48e571d89227c69f8ff382162a | 3,636,992 |
def decode(argument: str) -> tuple[list[int], ...]:
"""Decode argument string from command line
:param argument: argument string
:return: pair of list of digits
"""
char_lists = map(list, argument.split('-'))
range_ = tuple(list(map(int, clist)) for clist in char_lists)
return range_ | d3805396cab52fc09896ca9553f1ac3450f27e99 | 3,636,993 |
def generate_data(p=11, n=400):
"""
Generates non-linear multivariate data of dimension 'p'.
The data is linear in parameters of the type:
y = b0 + b1 * x + b2*x^2 + ... + bp * x^p
Args:
:param p: int
dimensions
:param n: int
number of samples
Return... | 98f4e1f661d8f21307115c1d1873bcf1c111ff85 | 3,636,994 |
def get_search_apps():
"""Gets all registered search apps."""
return tuple(_load_search_apps().values()) | 5287abce0a31e9eb2165aafb8a6cfbaabda85e48 | 3,636,995 |
def volume_tetrahedron(
point_a: array_like, point_b: array_like, point_c: array_like, point_d: array_like
) -> np.float64:
"""
Return the volume of a tetrahedron defined by four points.
The points are the vertices of the tetrahedron. They must be 3D or less.
Parameters
----------
point_a,... | 3369044cfe53762c9bbbf8363da5d385b14b51ba | 3,636,996 |
def lemmatizer(word):
"""Returns: lemmatized word if word >= length 5
"""
if len(word)<4:
return word
return wnl.lemmatize(wnl.lemmatize(word, "n"), "v") | f8e5020b85638464b261e1ec066a141ba4a202a0 | 3,636,997 |
def kolmogn(n, x, cdf=True):
"""Computes the CDF for the two-sided Kolmogorov-Smirnov distribution.
The two-sided Kolmogorov-Smirnov distribution has as its CDF Pr(D_n <= x),
for a sample of size n drawn from a distribution with CDF F(t), where
D_n &= sup_t |F_n(t) - F(t)|, and
F_n(t) is the Empiri... | 132672a1bf45bb0b675c3ce503d47ed4f740184b | 3,636,998 |
import os
def join_legacy_read_path(sample_path: str, suffix: int) -> str:
"""
Create a path string for a sample read file using the old file name convention (eg. reads_1.fastq).
:param sample_path: the path to the sample directory
:param suffix: the read file suffix
:return: the read path
"... | b6e12de4edfec05fb8a5fa2363dce284dcfdd5f0 | 3,636,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.