content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_label_metadata(
app: App,
label: LabelRef,
state_machine: StateMachine,
) -> Tuple[Dict[str, Any], bool]:
"""Get the metadata and whether the label has been deleted."""
return app.session.query(Label.metadata, Label.deleted).filter_by(
name=label.name,
state_machine=state_mac... | 77,600 |
def copy_of_xml_element(elem):
"""
This method returns a shallow copy of a XML-Element.
This method is for compatibility with Python 2.6 or earlier..
In Python 2.7 you can use 'copyElem = elem.copy()' instead.
"""
copyElem = ET.Element(elem.tag, elem.attrib)
for child in elem:
cop... | 77,601 |
def get_arrivals(knots: dict, func=None, *func_args, **func_kwargs) -> list :
"""
Generate a sequence from a nonhomogeneous Poisson process
specified by a piecewise linear function determined from
the knots parameter. The knots should specify the (domain, range)
of each segment's knot.
knots: dictionary where ke... | 77,602 |
def align_trajectory(traj, traj_ref, correct_scale=False,
correct_only_scale=False, n=-1, return_parameters=False):
"""
align a trajectory to a reference using Umeyama alignment
:param traj: the trajectory to align
:param traj_ref: reference trajectory
:param correct_scale: set ... | 77,603 |
def generate_introspector_index():
"""Generate index.html for successful Fuzz Introspector projects"""
status_bucket = get_storage_client().get_bucket(STATUS_BUCKET)
status = json.loads(
status_bucket.blob(INTROSPECTOR_STATUS_FILENAME).download_as_string())
introspector_bucket = get_storage_client().get_... | 77,604 |
def from_array(flwdir, _mv=_mv, dtype=np.intp):
"""convert 2D LDD data to 1D next downstream indices"""
nrow, ncol = flwdir.shape
flwdir_flat = flwdir.ravel()
# get downsteam indices
pits_lst = []
idxs_ds = np.full(flwdir.size, core._mv, dtype=dtype)
n = 0
for idx0 in range(flwdir.size):... | 77,605 |
def get_checks_by_status(api_key, status='new'):
"""
Возвращает JsonResponse с чеками соответствующего статуса status.
:param api_key: str: Ключ доступа API
:param status: str: Статус получаемых чеков
:return: :class:`Response <Response>` serialized to JSON
:rtype: http.JsonResponse"""
try... | 77,606 |
def current_time():
""" Current UTC datetime """
return datetime.datetime.utcnow() | 77,607 |
def _run_task_internal(jobname, taskid, nTask,
ReqArgs, KwArgs, UnkArgs,
dataName, allocModelName, obsModelName, algName,
doSaveToDisk, doWriteStdOut):
""" Internal method (should never be called by end-user!)
Executes learning for a parti... | 77,608 |
def value_and_multigrad(fun, argnums=[0]):
"""Returns a function that returns both value and gradients wrt multiple
arguments simultaneously."""
def combined_arg_fun(multi_arg, *args, **kwargs):
extra_args_list = list(args)
for argnum_ix, arg_ix in enumerate(argnums):
extra_args_... | 77,609 |
def day_of_year(t=None):
"""Returns the day of year."""
SECONDS_IN_DAY = 60 * 60 * 24.0
time = parse_time(t)
time_diff = parse_time(t) - datetime(time.year, 1, 1, 0, 0, 0)
result = time_diff.days + time_diff.seconds / SECONDS_IN_DAY
return result | 77,610 |
def dump_json(
obj: Any,
file: str,
formatting: bool = False,
ensure_ascii: bool = False,
format_postfix: bool = True,
**kwargs,
) -> NoReturn:
"""
写入json文件
:param obj: 任意对象
:param file: 存入文件
:param formatting: dump with data-interchange format
:pa... | 77,611 |
def show_object_id_by_date(
move_data: 'PandasMoveDataFrame' | 'DaskMoveDataFrame',
kind: list | None = None,
figsize: tuple[float, float] = (21, 9),
return_fig: bool = False,
save_fig: bool = False,
name: str = 'shot_points_by_date.png',
) -> figure | None:
"""
Generates four visualizat... | 77,612 |
def retrieve_experiment_name_and_path(experiment_name: Optional[str]) -> Tuple[Path, str]:
"""
Retrieve the experiment_path and experiment_name from the cwd and parameters given.
"""
path = Path.cwd()
if experiment_name is not None:
validate_path_name("Experiment", experiment_name)
e... | 77,613 |
def option_sse_list_sina(symbol: str = "50ETF", exchange: str = "null") -> List[str]:
"""
新浪财经-期权-上交所-50ETF-合约到期月份列表
https://stock.finance.sina.com.cn/option/quotes.html
:param symbol: 50ETF or 300ETF
:type symbol: str
:param exchange: null
:type exchange: str
:return: 合约到期时间
:rtype:... | 77,614 |
async def login(user_data: UserLoginIn):
"""Login Users
Endpoint for users login
Args:
- user_data (UserLoginIn): user_data with fields email and password. This user_data
corresponds a UserLoginIn schema
Returns:
string: Returns jwt token wich the user can navigate for anothers endpoints (i... | 77,615 |
def plot_x_y(name, x, y, x_i, y_i, xlabel, ylabel, ylim=(None, None)):
"""plot x vs y"""
plt.clf()
plt.plot(x, y)
plt.scatter(x_i, y_i)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.ylim(ylim)
plt.savefig(name) | 77,616 |
def validate_encryption_services(cmd, namespace):
"""
Builds up the encryption services object for storage account operations based on the list of services passed in.
"""
if namespace.encryption_services:
t_encryption_services, t_encryption_service = get_sdk(cmd.cli_ctx, CUSTOM_MGMT_STORAGE,
... | 77,617 |
def S_stat(data, data_label, refdata, refdata_label, obj_prop=True,
lsmask=None):
"""
Function to calculate the structure component (S). The basic idea is to
compare the volume of the normalized precipitation objects. This property
captures information of the geometrical characteristics (siz... | 77,618 |
def fix_bad_next_statements(vba_code):
"""
Change things like "Next x,y" to "Next x\nNext y"
"""
uni_vba_code = None
try:
uni_vba_code = vba_code.decode("utf-8")
except UnicodeDecodeError:
# Punt.
return vba_code
pat = "Next +(?:\w+ *, *)+\w+ *\n"
r = vba_co... | 77,619 |
def test_pandas_matrix_types(X, test_fun, *args, **kwargs):
"""Test a function across all dense matrix types
Parameters
----------
X : matrix input
test_fun : Function(X, *args, **kwargs) for testing
*args : positional arguments for test_fun
**kwargs : keyword arguments for test_fun
"""... | 77,620 |
def read_wave(path):
"""Reads a .wav file.
Takes the path, and returns (PCM audio data, sample rate).
"""
print(path)
with contextlib.closing(wave.open(path, "rb")) as wf:
num_channels = wf.getnchannels()
assert num_channels == 1
sample_width = wf.getsampwidth()
asser... | 77,621 |
def copy_metrics_and_parameters(report_file=REPORT_FILE):
"""
Returns Parameters and Metrics from the report_file.
:param report_file:
"""
metrics = {}
parameters = {}
with open(report_file) as f_in:
result_json = json.load(f_in)
if 'Metrics' in result_json:
... | 77,622 |
def test_atomic_id_min_length_4_nistxml_sv_iv_atomic_id_min_length_5_2(mode, save_output, output_format):
"""
Type atomic/ID is restricted by facet minLength with value 64.
"""
assert_bindings(
schema="nistData/atomic/ID/Schema+Instance/NISTSchema-SV-IV-atomic-ID-minLength-5.xsd",
instan... | 77,623 |
def MnistLI2(list_x,list_y, n_sec=20):
"""
Linear interpolation function for up sampling
"""
FinerArray = np.array([]).reshape(0,2)
for i in range(len(list_x)-1):
if list_x[i]<list_x[i+1]:
xvals = np.linspace(list_x[i], list_x[i+1], n_sec)
xvals = np.delete(xv... | 77,624 |
def log_prior(theta):
"""
Priors, limit the values to a range but otherwise flat.
"""
#limit the values to 0 < theta < 256
if (all(theta > 0) and all(theta < 256)):
return 0
else:
return -np.inf | 77,625 |
def cdf(x, mean=0.0, stdev=1.0):
""" Returns the cumulative distribution function at x.
"""
return min(1.0, 0.5 * erfc((-x + mean) / (stdev * 2**0.5))) | 77,626 |
def binarize(img_gray,
diameter=10,
sigmaColor=150,
sigmaSpace=150,
a_thresh_type=2,
a_thresh_blocksize=20,
a_thresh_offset=0,
a_thresh_offset2=0):
"""Binarize an image
Binarize an image using OpenCV library
Args:
... | 77,627 |
def random_SBM(n_nodes, block_sizes, p_in_min, p_out_max):
"""
Full random SBM
"""
nb_communities = len(block_sizes)
outmat = np.random.uniform(low=0, high=p_out_max, size=(nb_communities,nb_communities))
W = 0.5 * (outmat + outmat.T)
inmat = np.random.uniform(low=p_in_min, high=1, size=(nb_... | 77,628 |
def add_meta(match):
"""return a dict from the match"""
attr_name, attr_value = match.groups()
return {attr_name: strip_quotes(attr_value)} | 77,629 |
def remap_labels(labels, mappings):
"""
:param labels:
:param mappings:
:return:
"""
for source, target in mappings.items():
labels[labels == int(source)] = target
return labels | 77,630 |
def mean_absolute_deviation(array):
"""
Calculate the mean_absolute_deviation on EEG data
input:
array: numpy array. The temporal signal for feature extraction. 1d or with multiple dimensions
return
de: int or numpy array, depends on the input shape
"""
def cal_mad(s):
... | 77,631 |
def polychart(data):
"""
Description: generates a timeseries for a given point and given variable defined by the user.
Arguments: A dictionary object from the AJAX-ed JSON object that contains coordinates and the variable name.
Author: Riley Hales
Dependencies: netcdf4, numpy, datetime, os, calendar... | 77,632 |
def render(context, file='index.html', template_name='aquarius'):
"""Render a template in a string, by file.
A webloft template is often much more than a file. Each file is a
django template. Rendering all the files in the template directory
gives a full render of the website.
The template name is... | 77,633 |
def save_image(image_numpy: np.ndarray, image_path: str, aspect_ratio: float = 1.0) -> None:
"""Save a numpy image to the disk.
Args:
image_numpy (np.ndarray): input numpy array
image_path (str): the path of the image
aspect_ratio (float): the aspect ratio of the resulting image
"""... | 77,634 |
def get_data(symbols, dates):
"""Read stock data (adjusted close) for given symbols from CSV files."""
get_csv(symbols)
df = pd.DataFrame(index=dates)
if 'SPY' not in symbols: #add SPY for reference, if absent
symbols.insert(0,'SPY')
for symbol in symbols:
get_csv(symbol)
df_temp = pd.read_csv(symbol_to_pat... | 77,635 |
def load_network(path, weighted=False, directed=False):
"""
Load the edgelist as a networkx.Graph() object.
Input:
path::string: path to the edgelist
weighted::bool: whether the network has edge weights
directed::bool: whether the network is directed
Return:
::networkx.... | 77,636 |
def test_1d_sill():
"""test_1d_sill
tests against expected classic solution of shallow water equations over
a sill."""
from . import sill
def verify_expected(expected):
""" given an expected value, returns a verification function """
def sill_verify(claw):
from clawpac... | 77,637 |
def integrations_create(response):
"""Creates an integration. Link"""
return validate_response(response) | 77,638 |
def select_from_multiple_candidates(transcripts, refseqscan, appris_principal, selected, missing, log, hgncid, build, cartseries, cartidx):
"""Select from multiple transcript candidates"""
if not all_have_same_cds(transcripts):
to_missing_list(missing, log, hgncid, 'coding_mismatch', 'Not all of these ... | 77,639 |
def str_date(dt):
"""datetime to ISO 8601 str"""
if not dt or not isinstance(dt, (datetime, date, time)):
raise TypeError('dt should be date object, and not a %s' % type(dt))
if not dt.tzinfo:
# update dt with utc zone
dt = pytz.utc.localize(dt)
return dt.date.isoformat() | 77,640 |
def cli(ctx, config):
"""{{ cookiecutter.project_title }}."""
ctx.meta["config"] = settings.load(config) | 77,641 |
def locate_file(refname, mode=None):
"""Given a valid reffilename in CDBS or CRDS format, return a cache path for the file.
The aspect of this which is complicated is determining instrument and an instrument
specific sub-directory for it based on the filename alone, not the file contents.
The mode=No... | 77,642 |
def main(args=None):
"""the main entry point"""
parser = argparse.ArgumentParser(
prog=__package__,
epilog=(f'%(prog)s {otp2289.__version__} by Simeon Simeonov '
'(sgs @ Freenode)'),
description='The following options are available')
group = parser.add_mutually_exclus... | 77,643 |
def templates():
"""InvenioMarc21 templates commands."""
pass | 77,644 |
def get_bprop_l2_loss(self):
"""Grad definition for `L2Loss` operation."""
def bprop(x, out, dout):
dx = x * dout
return (dx,)
return bprop | 77,645 |
def change_dimension_shape_resolution(changed_dimension_shape_conflict):
"""Create a resolution for a changed shape prior"""
return changed_dimension_shape_conflict.ChangeDimensionResolution(
changed_dimension_shape_conflict
) | 77,646 |
def process_atbat(atbat_elem, atbat):
"""
Call process_pitch for every pitch in that atbat
"""
balls = 0
strikes = 0
pitches = []
for pitch_elem in atbat_elem:
if pitch_elem.tag == 'pitch':
pitch = process_pitch(pitch_elem, atbat, balls, strikes)
pitches.app... | 77,647 |
def extract_tracklist_begin_num(content):
"""Return list of track names extracted from messy web content.
The name of a track is defined as a line which begins with a number
(excluding whitespace).
"""
tracklist = []
for line in content.splitlines():
# Empty line
if not line:
... | 77,648 |
def weather(searchterm):
"""Get the weather for a place given by searchterm
Returns a title and a list of forecasts.
The title describes the location for the forecast (i.e. "Portland, ME USA")
The list of forecasts is a list of dictionaries in slack attachment fields
format (see https://api.sl... | 77,649 |
def main():
"""Does general setup and calls exploit."""
if len(sys.argv) < 2:
print(f'Usage: {sys.argv[0]} <mode>')
sys.exit(0)
try:
context.binary = ELF(BINARY)
except IOError:
print(f'Failed to load binary ({BINARY})')
libc = None
try:
libc = ELF(LIB)
... | 77,650 |
def post_image(conn, image, image_name, description=None, dataset_id=None,
source_image_id=None, channel_list=None):
"""Create a new OMERO image from numpy array.
Parameters
----------
conn : ``omero.gateway.BlitzGateway`` object
OMERO connection.
image : ``numpy.ndarray``
... | 77,651 |
def save_to_mongo(data, mongo_db, mongo_db_coll, **mongo_conn_kw):
"""Saves data to Mongo"""
client = pymongo.MongoClient(**mongo_conn_kw)
db = client[mongo_db]
coll = db[mongo_db_coll]
return coll.insert(data) | 77,652 |
def _append_autopep8_lint_command_if_module_updated(
lint_commands: List[LintCommand],
module_paths: List[str]) -> List[str]:
"""
Append the autopep8 lint command to the list if the
modules have been updated.
Parameters
----------
lint_commands : list of LintCommand
... | 77,653 |
async def test_unload_entry(hass: HomeAssistant) -> None:
"""Test unload."""
config_entry = MockConfigEntry(
data=CONFIG,
domain=DOMAIN,
unique_id="airzone_unique_id",
)
config_entry.add_to_hass(hass)
with patch(
"homeassistant.components.airzone.AirzoneLocalApi.val... | 77,654 |
def rgb2hsv(rgb:np.ndarray):
"""Compute luminance of an RGB image.
Args:
rgb (tensor): rgb image (shape:(H,W,C))
Returns:
gray(tensor): gray-scale image(shape:(H,W))
Examples:
>>> import cv2
>>> from skimage import color
>>> img=cv2.cvtColor(cv2.imread('../../... | 77,655 |
def net_solar_radiation(rs, albedo=0.23):
"""
Calculate the fraction of the solar radiation that is not reflected from
the surface (Allen et al. 1998).
Parameters
----------
rs : float
Solar radiation (MJ m-2 day-1).
albedo : float, optional
Albedo (-), default is 0.23 (valu... | 77,656 |
def resolve_nodes(fn: Callable, config: Dict[str, Any]) -> Collection[node.Node]:
"""Gets a list of nodes from a function. This is meant to be an abstraction between the node
and the function that it implements. This will end up coordinating with the decorators we build
to modify nodes.
Algorithm is as... | 77,657 |
def request_from_dict(d, processor=None):
"""Create Request object from a dict.
If a spider is given, it will try to resolve the callbacks looking at the
spider for methods with the same name.
"""
cb = d['callback']
if cb and processor:
cb = _get_method(processor, cb)
eb = d['errbac... | 77,658 |
def assert_equal(actual: Literal["converged"], desired: Literal["converged"]):
"""
usage.statsmodels: 1
"""
... | 77,659 |
def text_color(message='{}', color_code='\033[0;37m'):
"""Set text to a color, default color is White"""
no_color = '\033[0m'
return f'{color_code}{message}{no_color}' | 77,660 |
def masked_max(
vector: torch.Tensor,
mask: torch.BoolTensor,
dim: int,
keepdim: bool = False,
) -> torch.Tensor:
"""
To calculate max along certain dimensions on masked values
# Parameters
vector : `torch.Tensor`
The vector to calculate max, assume unmasked parts are already z... | 77,661 |
def count_correct_correspondences(
keypoints_i1: Keypoints,
keypoints_i2: Keypoints,
intrinsics_i1: Cal3Bundler,
intrinsics_i2: Cal3Bundler,
i2Ti1: Pose3,
epipolar_dist_threshold: float,
) -> int:
"""Checks the correspondences for epipolar distances and counts ones which are below the thresh... | 77,662 |
def get_max_elements_in_row(row: list) -> int:
"""
Loops through the dataset and gets the max elements in a list if
one is found in the list or 1 if all strings.
"""
max_array_count = 0
# get the max height of the cells.
for item in row:
if isinstance(item, list) and len(item) > max... | 77,663 |
def coord_type_from_ctype(ctype):
"""
Determine whether a particular WCS ctype corresponds to an angle or scalar
coordinate.
"""
if ctype[:4] == 'RA--':
return 'longitude', u.hourangle, None
elif ctype[:4] == 'HPLN':
return 'longitude', u.arcsec, 180.
elif ctype[:4] == 'HPLT'... | 77,664 |
def swac()->(int,str):
"""run an analysis on a signle word based on a corpus"""
print('Available corpora:')
for c in corpora:
print(c)
while True:
corpus = input("Please enter an available corpus to refrence by index number: ")
try:
corpus = int(corpus)
if... | 77,665 |
def get_adventure(): # noqa: E501
"""Get all adventures
# noqa: E501
:rtype: List[Adventure]
"""
return "do some magic!" | 77,666 |
def return_pkl_files(pkl_dirs):
"""return pkl filenames"""
pkl_list = []
pkl_filenames = []
for pkl in pkl_dirs:
pkl_list.append(dataparser.load_pkl_file(pkl))
pkl_filenames.append(dataparser.get_filename(pkl))
return pkl_list, pkl_filenames | 77,667 |
def get_control_flow_graph(program):
"""Get a ControlFlowGraph for the provided AST node.
Args:
program: Either an AST node, source string, or a function.
Returns:
A ControlFlowGraph.
"""
control_flow_visitor = ControlFlowVisitor()
node = program_utils.program_to_ast(program)
control_flow_visitor... | 77,668 |
def rebuild_schemas(index):
"""
Resets the schema for all checkpoints to the latest version based off the
current document structure. Returns the number of checkpoints updated.
"""
db = ExportSchema.get_db()
all_checkpoints = ExportSchema.get_all_checkpoints(index)
config = ExportConfigurati... | 77,669 |
def warp_occupancy(info, cc, smem_config=None):
"""Returns a dictionary of {threadperblock: occupancy, factor}
Only threadperblock of multiple of warpsize is used.
Only threadperblock of non-zero occupancy is returned.
"""
ret = {}
try:
limits = PHYSICAL_LIMITS[cc]
except KeyError:
... | 77,670 |
def cst_efield_2freq_cut_healpix(cst_efield_2freq_cut_healpix_main):
"""Make function level cut down HEALPix 2-freq efield beam."""
return cst_efield_2freq_cut_healpix_main.copy() | 77,671 |
def is_an_iterable_type_hint(rel_type_hint) -> bool:
"""Check if typing.Iterable wraps the relationship type hint.
###### Parameters ######
* `rel_type_hint`: type hint to check
For a given class `C`, all following expressions are evaluated to `True`:
```python
is_an_iterable_type_hint(Itera... | 77,672 |
def gnmi_get(dut, xpath, **kwargs):
"""
API to do GNMI get operations
Author: Chaitanya Vella (chaitanya-vella.kumar@broadcom.com)
:param dut:
:param xpath:
:param kwargs:
:return:
"""
gnmi_debug(dut)
credentails = st.get_credentials(dut)
ip_address = kwargs.get('ip_address',... | 77,673 |
def shift_chord(chord, shift):
"""Shift chord"""
if chord < 12:
new_chord = (chord + shift) % 12
elif chord < 24:
new_chord = (chord - 12 + shift) % 12 + 12
else:
new_chord = chord
return new_chord | 77,674 |
def register_new_user(access, username, password):
""" Register a new user & handle duplicate detection """
if access.user_data(username) is not None:
raise ValueError("User '%s' already exists!" % username)
if username in access.pending_users():
raise ValueError("User '%s' has already regis... | 77,675 |
def player_strategy_from_argv(i):
""" Parses argv at the given index and returns strategy for user """
# Ensure we don't look out of range
if len(sys.argv) < i:
sys.exit(USAGE_ERROR)
if sys.argv[i].lower() == "human":
return human_strategy
elif sys.argv[i].lower() == "minimax":
... | 77,676 |
def get_sources_plot_dir(cybershake_root, realisation):
"""
Gets the folder for storing plots that can be generated
before installing a cybershake. eg. srf square & map plots.
"""
return os.path.join(
cybershake_root,
"Data",
"Sources",
get_fault_from_realisation(real... | 77,677 |
def main():
"""
This function is called from the main block. The purpose of this function is to contain all the calls to
business logic functions
:return: int - Return 0 or 1, which is used as the exist code, depending on successful or erroneous flow
"""
# Wrap in a try block so ... | 77,678 |
def drawOutput():
"""
Parses the text on the code editor into the BitTune language, then loads the
parsed file onto the user's draw canvas.
"""
global lastPlayedCoordinates
notes = notes_text.get("1.0", "end-1c")
tempDir = ".bt_temp"
# Create the directory only if it does not exist
try:
... | 77,679 |
def setup_logging(args):
"""Configures the logging/reporting
Args:
args <args>: Command line arguments
"""
global logger
# Setup the logging level
logging_level = logging.INFO
if args.debug:
logging_level = logging.DEBUG
handler = logging.StreamHandler(sys.stdout)
... | 77,680 |
def report_3ware(line, log, controller):
"""Report findings in 3ware pipeline, return BOOL of health check."""
success = True
progress = None
data_type = None
if line[0] == "u":
data_type = "Unit"
status = line.split()[2]
if status == "REBUILDING":
progress = li... | 77,681 |
def load_properties():
"""
Load yaml file containing program's properties. Check the ReadMe.md file of the directory for a complete list of
the possible configuration properties and their values.
Returns:
dict: the properties dictionary
"""
properties_folder = join(app_dir, "properties"... | 77,682 |
def cdf_to_pdf(cdf):
"""Compute a pdf (probability distribution function) from its cdf (cumulative distribution function)."""
pdf = deepcopy(cdf)
pdf[1:] -= pdf[:-1].copy()
return pdf | 77,683 |
def stardist_polygon(data_config):
"""Build DSA annotation json from stardist geojson classification results
Args:
data_config (string): path to your data config file that includes input/output parameters.
input (string): path to stardist geojson classification results
output_folder (s... | 77,684 |
def normalize_code(code):
"""
归一化证券代码
:param code 如000001
:return 证券代码的全称 如000001.XSHE
"""
return JQDataClient.instance().normalize_code(**locals()) | 77,685 |
def get_not_constant_species(model):
"""
get species of the model that are not constant
@param model: libsbml.model
@type model: libsbml.model
@return: list of species
@rtype: list[libsbml.species]
"""
def not_const(s): return not( s.getConstant() or s.getBoundaryCondition() )
return... | 77,686 |
def HandleCommonOptions(options):
"""Handle common command-line options after parsing.
Args:
options: the result of parse_args() on the parser returned by
ResourceArgsParser(). This function updates a few common fields.
"""
options.include_resources = [build_utils.ParseGnList(r) for r in
... | 77,687 |
def remap_document_keys(document, key_map, inplace=True):
"""Remap keys in given JSON document.
>>> remap_keys({'foo': 1}, {'foo': 'bar'})
{'bar': 1}
"""
assert isinstance(document, dict)
if inplace:
# modify given document
for key in document.keys():
new_key = key_m... | 77,688 |
def clientcompressionsupport(proto):
"""Returns a list of compression methods supported by the client.
Returns a list of the compression methods supported by the client
according to the protocol capabilities. If no such capability has
been announced, fallback to the default of zlib and uncompressed.
... | 77,689 |
def preprocess_pbt_df(df: pd.DataFrame, x_tag: str) -> pd.DataFrame:
"""Align the x_tag index used in plot_progress before plotting.
Args:
----
df (pd.DataFrame): Dataframe of the progress.csv file
x_tag (str): Desired tag in df to use as index of plot
Return:
------
df (pd... | 77,690 |
def open_instance_public_ports(portInfo=None, instanceName=None):
"""
Adds public ports to an Amazon Lightsail instance.
See also: AWS API Documentation
:example: response = client.open_instance_public_ports(
portInfo={
'fromPort': 123,
'toPort': 123,
... | 77,691 |
def standard_deviation(xs: List[float]) -> float:
"""The standard deviation is the square root of the variance"""
return math.sqrt(variance(xs)) | 77,692 |
async def test_unschedule_active_program_2(startup_and_shutdown_uvicorn, host, port, tmp_path):
""" test unscheduling the active elements of a program. """
client = ClientAsync(host=host, port=port)
await reset_dispatcher(client, str(tmp_path))
action1 = file_x.FileAppend(
relative_to_output_di... | 77,693 |
def ssd_512_resnet50_v1_coco(pretrained=False, pretrained_base=True, **kwargs):
"""SSD architecture with ResNet v1 50 layers for COCO.
Parameters
----------
pretrained : bool or str
Boolean value controls whether to load the default pretrained weights for model.
String value represents ... | 77,694 |
def test_asksCompare() -> None:
"""asksCompare() returns a bool, so I'm asserting directly"""
assert asksCompare(-1, -1) is False
assert asksCompare(-1, 0)
assert asksCompare(-1, 1)
assert asksCompare(0, -1) is False
assert asksCompare(0, 0) is False
assert asksCompare(0, 1)
assert asksC... | 77,695 |
def filter_otsu_threshold(np_img):
"""
Compute Otsu threshold on image as a NumPy array and return binary image based on pixels above threshold.
Args:
np_img: Image as a NumPy array.
output_type: Type of array to return (bool, float, or uint8).
Returns:
NumPy array (bool, float, ... | 77,696 |
def update(private=False, pre=False, link=None, additional_components=None):
""" Update the CLI and all installed components """
_raise_error("Components cannot be updated.") | 77,697 |
def cache_timestamped_validation_result(doc_id, validation_type, report, timestamp):
"""Caching for ethercalc-based validation types, currently ether and export.
For xml and meta we are able to maintain the cache because Gitdox knows when
xml or meta has changed, but with ethercalc, Gitdox is not informed o... | 77,698 |
def get_default_build_presets(default_run_config):
""" Read the build presets from the config """
return dict(default_run_config[ue4_constants.UNREAL_BUILD_SETTINGS_STRUCTURE]) | 77,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.