content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_abstract_guessing():
"""Test abstract guessing property."""
class _CustomPsychometric(DiscriminationMethod):
def psychometric_function(self, d):
return 0.5
with pytest.raises(TypeError, match="abstract method"):
_CustomPsychometric() | 5,345,500 |
def remove_repeats(msg):
"""
This function removes repeated characters from text.
:param/return msg: String
"""
# twitter specific repeats
msg = re.sub(r"(.)\1{2,}", r"\1\1\1", msg) # characters repeated 3 or more times
# laughs
msg = re.sub(r"(ja|Ja)(ja|Ja)+(j)?", r"jaja", msg) # span... | 5,345,501 |
def _legend_main_get(project, row):
"""
forma la leyenda de la serie principal del gráfico
input
project: es el tag project del proyecto seleccionado
en fichero XYplus_parameters.f_xml -en XYplus_main.py-
row: es fila activa devuelta por select_master) de donde se
... | 5,345,502 |
def prop_elliptical_obscuration(wf, xradius, yradius, xc = 0.0, yc = 0.0, **kwargs):
"""Multiply the wavefront by an elliptical obscuration.
Parameters
----------
wf : obj
WaveFront class object
xradius : float
X ellipse radius in meters, unless norm is specified
... | 5,345,503 |
def gen_queen_moves_quiet(queen_bitboard, opponents_pieces, blockers):
"""
generate capturing queen moves
Args:
queen_bitboard (int): Bitboard of positions of queens
all_pieces (int): Bitboard of all other pieces on the board
Returns:
generator for all capturing queen moves giv... | 5,345,504 |
def contrast_jwst_num(coro_floor, norm, matrix_dir, rms=50*u.nm):
"""
Compute the contrast for a random segmented OTE misalignment on the JWST simulator.
:param coro_floor: float, coronagraph contrast floor
:param norm: float, normalization factor for PSFs: peak of unaberrated direct PSF
:param mat... | 5,345,505 |
def ordinal_mapper(fh, coords, idmap, fmt=None, n=1000000, th=0.8,
prefix=False):
"""Read an alignment file and match reads and genes in an ordinal system.
Parameters
----------
fh : file handle
Alignment file to parse.
coords : dict of list
Gene coordinates table... | 5,345,506 |
def modify_tilt(path, bin_factor, exclude_angles=[]):
"""
Modifies the bin-factor and exclude-angles of a given tilt.com file.
Note: This will overwrite the file!
Parameters
----------
path : str
Path to the tilt.com file.
bin_factor : int
The new bin-factor.
exclude_an... | 5,345,507 |
def file_lines(filename):
"""
>>> file_lines('test/foo.txt')
['foo', 'bar']
"""
return text_file(filename).split() | 5,345,508 |
def repr_should_be_defined(obj):
"""Checks the obj.__repr__() method is properly defined"""
obj_repr = repr(obj)
assert isinstance(obj_repr, str)
assert obj_repr == obj.__repr__()
assert obj_repr.startswith("<")
assert obj_repr.endswith(">")
return obj_repr | 5,345,509 |
def read_tiff(tiff_path):
"""
Args:
tiff_path: a tiff file path
Returns:
tiff image object
"""
if not os.path.isfile(tiff_path) or not is_tiff_file(tiff_path):
raise InvalidTiffFileError(tiff_path)
return imread(tiff_path) | 5,345,510 |
def changePassword():
"""
Change to a new password and email user.
URL Path:
URL Args (required):
- JSON structure of change password data
Returns:
200 OK if invocation OK.
500 if server not configured.
"""
@testcase
def changePasswordWorker():
try:
... | 5,345,511 |
def parallel_for(
loop_callback: Callable[[Any], Any],
parameters: List[Tuple[Any, ...]],
nb_threads: int = os.cpu_count()+4
) -> List[Any]:
"""Execute a for loop body in parallel
.. note:: Race-Conditions
Code executation in parallel can cause into an "race-condition"
... | 5,345,512 |
def indexName():
"""Index start page."""
return render_template('index.html') | 5,345,513 |
def on_vlc_closed(to_watch_folder, watched_folder, ml_xspf, trigger):
"""
Checks if modified event trigger was ml.xspf. If yes then finds movie in
to_watch_folder that returns true from is_movie_watched(), and calls ask_and_move
with the movie folder as source and the watched folder as destination.
... | 5,345,514 |
def translate_http_code():
"""Print given code
:return:
"""
return make_http_code_translation(app) | 5,345,515 |
def _def_tconst(pattern, _):
"""Temporal constraints for the energy interval abstraction pattern"""
deflection = pattern.hypothesis
pattern.last_tnet.add_constraint(deflection.start, deflection.end, DEF_DUR) | 5,345,516 |
def delete_directory(a_dir):
""" Delete a directory tree recursively """
shutil.rmtree(a_dir, onerror=on_remove_error) | 5,345,517 |
def test_colossus_vmax_consistency_z1():
"""
"""
try:
from colossus.cosmology import cosmology
from colossus.halo.profile_nfw import NFWProfile as ColossusNFW
except ImportError:
return
_cosmo = cosmology.setCosmology('planck15')
masses_to_check = 10**np.array((11., 12, ... | 5,345,518 |
def interactive(python):
""" Main entrypoint into dbmp interactive mode """
args = ''
if not os.path.exists(HISTORY):
io.open(HISTORY, 'w+').close()
try:
while True:
pt.shortcuts.clear()
pt.shortcuts.set_title("Datera Bare-Metal Provisioner")
print("We... | 5,345,519 |
def dose_rate(sum_shielding, isotope, disable_buildup = False):
"""
Calculate the dose rate for a specified isotope behind shielding
behind shielding barriers. The dose_rate is calculated for 1MBq
Args:
sum_shielding: dict with shielding elements
isotope: isotope name (st... | 5,345,520 |
def parmap(f, X, nprocs=1):
"""
parmap_fun() and parmap() are adapted from klaus se's post
on stackoverflow. https://stackoverflow.com/a/16071616/4638182
parmap allows map on lambda and class static functions.
Fall back to serial map when nprocs=1.
"""
if nprocs < 1:
raise ValueErr... | 5,345,521 |
def is_char_token(c: str) -> bool:
"""Return true for single character tokens."""
return c in ["+", "-", "*", "/", "(", ")"] | 5,345,522 |
def pre_commit(session_: Session) -> None:
"""Lint using pre-commit."""
args = session_.posargs or ["run", "--all-files", "--show-diff-on-failure"]
_export_requirements(session_)
poetry_install(session_)
session_.install("pre-commit")
session_.run("pre-commit", *args)
if args and args[0] == ... | 5,345,523 |
def _float_arr_to_int_arr(float_arr):
"""Try to cast array to int64. Return original array if data is not representable."""
int_arr = float_arr.astype(numpy.int64)
if numpy.any(int_arr != float_arr):
# we either have a float that is too large or NaN
return float_arr
else:
return ... | 5,345,524 |
def test_bernese_koordinat_kovarians():
"""Test at den samlede løsnings kovariansmatrix læses korrekt."""
BUDP = BerneseSolution(ADDNEQ2096, CRD2096, COV2096)["BUDP"]
skalering = 0.001 ** 2
assert BUDP.kovarians.xx == 0.9145031116e-01 * skalering
assert BUDP.kovarians.yx == 0.1754111808e-01 * skale... | 5,345,525 |
def latest(scores: Scores) -> int:
"""The last added score."""
return scores[-1] | 5,345,526 |
def get_dp_2m(wrfin, timeidx=0, method="cat", squeeze=True,
cache=None, meta=True, _key=None, units="degC"):
"""Return the 2m dewpoint temperature.
This functions extracts the necessary variables from the NetCDF file
object in order to perform the calculation.
Args:
... | 5,345,527 |
def fit_uncertainty(points, lower_wave, upper_wave, log_center_wave, filter_size):
"""Performs fitting many times to get an estimate of the uncertainty
"""
mock_points = []
for i in range(1, 100):
# First, fit the points
coeff = np.polyfit(np.log10(points['rest_wavelength']),
... | 5,345,528 |
def from_dateutil_rruleset(rruleset):
"""
Convert a `dateutil.rrule.rruleset` instance to a `Recurrence`
instance.
:Returns:
A `Recurrence` instance.
"""
rrules = [from_dateutil_rrule(rrule) for rrule in rruleset._rrule]
exrules = [from_dateutil_rrule(exrule) for exrule in rruleset.... | 5,345,529 |
def error_038_italic_tag(text):
"""Fix the error and return (new_text, replacements_count) tuple."""
backup = text
(text, count) = re.subn(r"<(i|em)>([^\n<>]+)</\1>", "''\\2''", text, flags=re.I)
if re.search(r"</?(?:i|em)>", text, flags=re.I):
return (backup, 0)
else:
return ... | 5,345,530 |
def create_user():
""" Method that will create an user .
Returns:
user.id: The id of the created user
Raises:
If an error occurs it will be displayed in a error message.
"""
try:
new_user = User(name=login_session['username'], email=login_session[
'emai... | 5,345,531 |
def store_relation(
self,
relation_name,
persist_type,
relation_persist_type,
validate = False,
force_persist = False,
raise_exception = False,
store_relations = True,
entity_manager = None
):
"""
Stores a relation with the given name in the entity
using the ... | 5,345,532 |
def buildStartAndEndWigData(thisbam, LOG_EVERY_N=1000, logger=None):
"""parses a bam file for 3' and 5' ends and builds these into wig-track data
Returns a dictionary of various gathered statistics."""
def formatToWig(wigdata):
""" take in the read position data and output in... | 5,345,533 |
def time_series_h5(timefile: Path, colnames: List[str]) -> Optional[DataFrame]:
"""Read temporal series HDF5 file.
If :data:`colnames` is too long, it will be truncated. If it is too short,
additional column names will be deduced from the content of the file.
Args:
timefile: path of the TimeSe... | 5,345,534 |
def decode_jwt(token):
"""decodes a token and returns ID associated (subject) if valid"""
try:
payload = jwt.decode(token.encode(), current_app.config['SECRET_KEY'], algorithms=['HS256'])
return {"isError": False, "payload": payload["sub"]}
except jwt.ExpiredSignatureError as e:
curr... | 5,345,535 |
def _validate_image_info(ext, image_info=None, **kwargs):
"""Validates the image_info dictionary has all required information.
:param ext: Object 'self'. Unused by this function directly, but left for
compatibility with async_command validation.
:param image_info: Image information dictiona... | 5,345,536 |
def show(nodes, print_groups):
"""Show generic information on node(s)."""
from aiida.cmdline.utils.common import get_node_info
for node in nodes:
# pylint: disable=fixme
#TODO: Add a check here on the node type, otherwise it might try to access
# attributes such as code which are no... | 5,345,537 |
def format_point(point: Point) -> str:
"""Return a str representing a Point object.
Args:
point:
Point obj to represent.
Returns:
A string representing the Point with ° for grades, ' for minutes and " for seconds.
Latitude is written before Longitude.
Example Output: 30... | 5,345,538 |
def handle_get_authentication_groups_db(self, handle, connection, match, data, hdr):
"""
GET /authentication/groups_db
Get user database on this runtime
Response status code: OK or INTERNAL_ERROR
Response:
{
"policies": {
<policy-id>: policy in JSON format,
...
... | 5,345,539 |
def families_horizontal_correctors():
"""."""
return ['CH'] | 5,345,540 |
def test_viewmodel():
"""Get a data manager instance for each test function."""
# Create the device under test (dut) and connect to the database.
dut = RAMSTKHardwareBoMView()
yield dut
# Unsubscribe from pypubsub topics.
pub.unsubscribe(dut.on_insert, "succeed_insert_hardware")
pub.unsubs... | 5,345,541 |
def variable_select_source_data_proxy(request):
"""
@summary: 获取下拉框源数据的通用接口
@param request:
@return:
"""
url = request.GET.get('url')
try:
response = requests.get(
url=url,
verify=False
)
except Exception as e:
logger.exception('variable se... | 5,345,542 |
def test_directed_valid_paths():
""" antco.ntools.getValidPaths() (directed) testing unit """
# Initial position (0) -> Valid paths: (1)
adj_matrix = np.array([
[0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 1],
[0, 0, 0, 0, 0, 0],
[1, 0, 1, 0, 0, 0],
[1, 0, 0, 1, 0, 0],
... | 5,345,543 |
async def select_guild_lfg_events(guild_id: int) -> list[asyncpg.Record]:
"""Gets the lfg messages for a specific guild ordered by the youngest creation date"""
select_sql = f"""
SELECT
id, message_id, creation_time, voice_channel_id
FROM
lfgmessages
WHERE
... | 5,345,544 |
def ValueToString(descriptor, field_desc, value):
"""Renders a field value as a PHP literal.
Args:
descriptor: The descriptor module from the protobuf package, e.g.
google.protobuf.descriptor.
field_desc: The type descriptor for the field value to be rendered.
value: The value of the field to b... | 5,345,545 |
def get_checkpoints(run_dir, from_global_step=None, last_only=False):
"""Return all available checkpoints.
Args:
run_dir: Directory where the checkpoints are located.
from_global_step (int): Only return checkpoints after this global step.
The comparison is *strict*. If ``None``, ret... | 5,345,546 |
def ssget_p() -> selection_result:
"""
选择上一个选择集
""" | 5,345,547 |
def write_env_file(env_dict):
""" Write the env_file information to a temporary file
If there is any error, return None;
otherwise return the temp file
"""
try:
temp_file = tempfile.NamedTemporaryFile(mode='w')
for key in env_dict.keys():
val = env_dict[key]
... | 5,345,548 |
def __load_txt_resource__(path):
"""
Loads a txt file template
:param path:
:return:
"""
txt_file = open(path, "r")
return txt_file | 5,345,549 |
def parse_cpu_spec(spec):
"""Parse a CPU set specification.
:param spec: cpu set string eg "1-4,^3,6"
Each element in the list is either a single
CPU number, a range of CPU numbers, or a
caret followed by a CPU number to be excluded
from a previous range.
:returns: a set of CPU indexes
... | 5,345,550 |
def _IterStringLiterals(path, addresses, obj_sections):
"""Yields all string literals (including \0) for the given object path.
Args:
path: Object file path.
addresses: List of string offsets encoded as hex strings.
obj_sections: List of contents of .rodata.str sections read from the given
obje... | 5,345,551 |
def distance_fit_from_transits() -> typing.List[float]:
"""
This uses the observers position from full transits and then the runway positions from all
the transit lines fitted to a
"""
((x_mean, x_std), (y_mean, y_std)) = observer_position_mean_std_from_full_transits()
transits = transit_x_axis_... | 5,345,552 |
def collate_fn_synthesize(batch):
"""
Create batch
Args : batch(tuple) : List of tuples / (x, c) x : list of (T,) c : list of (T, D)
Returns : Tuple of batch / Network inputs x (B, C, T), Network targets (B, T, 1)
"""
local_conditioning = len(batch[0]) >= 2
if local_conditioning:
... | 5,345,553 |
def max_(context, mapping, args, **kwargs):
"""Return the max of an iterable"""
if len(args) != 1:
# i18n: "max" is a keyword
raise error.ParseError(_("max expects one argument"))
iterable = evalwrapped(context, mapping, args[0])
try:
return iterable.getmax(context, mapping)
... | 5,345,554 |
def dict_to_duration(time_dict: Optional[Dict[str, int]]) -> Duration:
"""Convert a QoS duration profile from YAML into an rclpy Duration."""
if time_dict:
try:
return Duration(seconds=time_dict['sec'], nanoseconds=time_dict['nsec'])
except KeyError:
raise ValueError(
... | 5,345,555 |
def gen_ex_tracking_df(subj_dir):
"""Generate subject tracking error data frames from time series CSVs.
This method generates tracking error (Jaccard distance, CSA, T, AR) data
frames from raw time series CSV data for a single subject.
Args:
subj_dir (str): path to subject data directory, incl... | 5,345,556 |
def getCentral4Asics(evt, type, key):
"""Adds a one-dimensional stack of its 4 centermost asics
to ``evt["analysis"]["central4Asics"]``.
Args:
:evt: The event variable
:type(str): The event type (e.g. photonPixelDetectors)
:key(str): The event key (e.g. CCD)
:Authors:
... | 5,345,557 |
def mse(y_true: np.ndarray, y_pred: np.ndarray) -> float:
"""Compute the MSE (Mean Squared Error)."""
return sklearn.metrics.mean_squared_error(y_true, y_pred) | 5,345,558 |
def run_single_thread(experiment: Experiment, thread_ids: list,
distances: dict, times: dict, matchings: dict,
printing: bool) -> None:
""" Single thread for computing distances """
for election_id_1, election_id_2 in thread_ids:
if printing:
print... | 5,345,559 |
def test_insert_empty_tree(empty_ktree):
"""Test insert into empty tree."""
empty_ktree.insert(1, None)
assert empty_ktree.root.val == 1 | 5,345,560 |
def test_ar_raw():
"""Test fitting AR model on raw data."""
raw = io.read_raw_fif(raw_fname).crop(0, 2).load_data()
raw.pick_types(meg='grad')
# pick MEG gradiometers
for order in (2, 5, 10):
coeffs = fit_iir_model_raw(raw, order)[1][1:]
assert_equal(coeffs.shape, (order,))
a... | 5,345,561 |
def test_known_good() -> None:
"""Test to see if known good strings pass verification."""
data = [
'HELLOW'
'TFSI4JR',
'JDLULAG',
'BMQRZPX',
'V6B4ORO',
'BMRJXQ7',
'LZYMFSV',
'7JWZVIK',
'UZI5F4A',
'AWCWP3K',
'PQCFBLJ',
... | 5,345,562 |
def policy_improvement(env, V, gamma):
"""
Obtain an improved policy based on the values
@param env: OpenAI Gym environment
@param V: policy values
@param gamma: discount factor
@return: the policy
"""
n_state = env.observation_space.n
n_action = env.action_space.n
policy = torch... | 5,345,563 |
def loudness_zwst_freq(spectrum, freqs, field_type="free"):
"""Zwicker-loudness calculation for stationary signals
Calculates the acoustic loudness according to Zwicker method for
stationary signals.
Normatice reference:
ISO 532:1975 (method B)
DIN 45631:1991
ISO 532-1:2017 (met... | 5,345,564 |
def func(back=2):
"""
Returns the function name
"""
return "{}".format(sys._getframe(back).f_code.co_name) | 5,345,565 |
def normU(u):
"""
A function to scale Uranium map. We don't know what this function should be
"""
return u | 5,345,566 |
def test_save_topic_figures():
"""Writes out images for topics.
"""
model_file = join(get_test_data_path(), 'gclda_model.pkl')
temp_dir = join(get_test_data_path(), 'temp')
model = Model.load(model_file)
model.save_topic_figures(temp_dir, n_top_words=5)
figures = glob(join(temp_dir, '*.png'... | 5,345,567 |
def exact_riemann_solution(q_l, q_r, gamma=1.4, phase_plane_curves=False):
"""Return the exact solution to the Riemann problem with initial states
q_l, q_r. The solution is given in terms of a list of states, a list of
speeds (each of which may be a pair in case of a rarefaction fan), and a
fu... | 5,345,568 |
def check_admin():
"""
This function prevents non-admins from accessing this page and is called on every route
"""
if not current_user.is_admin:
abort(403) | 5,345,569 |
def show_edge_scatter(N, s1, s2, t1, t2, d, dmax=None, fig_ax=None):
"""Draw the cell-edge contour and the displacement vectors.
The contour is drawn using a scatter plot to color-code the displacements."""
if fig_ax is None:
fig, ax = plt.subplots()
else:
fig, ax = fig_ax
plt.f... | 5,345,570 |
def aiobotocore_client(service, tracer):
"""Helper function that creates a new aiobotocore client so that
it is closed at the end of the context manager.
"""
session = aiobotocore.session.get_session()
endpoint = LOCALSTACK_ENDPOINT_URL[service]
client = session.create_client(
service,
... | 5,345,571 |
def get_A2_const(alpha1, alpha2, lam_c, A1):
"""Function to compute the constant A2.
Args:
alpha1 (float): The alpha1 parameter of the WHSCM.
alpha2 (float): The alpha2 parameter of the WHSCM.
lam_c (float): The switching point between the
two exponents of the dou... | 5,345,572 |
def dark(app):
""" Apply Dark Theme to the Qt application instance.
Args:
app (QApplication): QApplication instance.
"""
darkPalette = QtGui.QPalette()
# base
darkPalette.setColor(QtGui.QPalette.WindowText, QtGui.QColor(180, 180, 180))
darkPalette.setColor(QtGui.QPalette.B... | 5,345,573 |
def test_contract_manager_json(tmpdir):
""" Check the ABI in contracts.json """
precompiled_path = Path(str(tmpdir)).joinpath('contracts.json')
ContractManager(contracts_source_path()).compile_contracts(precompiled_path)
# try to load contracts from a precompiled file
contract_manager_meta(precompil... | 5,345,574 |
def args_parser():
"""
Parese command line arguments
Args:
opt_args: Optional args for testing the function. By default sys.argv is used
Returns:
args: Dictionary of args.
Raises:
ValueError: Raises an exception if some arg values are invalid.
"""
# Constr... | 5,345,575 |
def _parse_seq_tf_example(example, uint8_features, shapes):
"""Parse tf.Example containing one or two episode steps."""
def to_feature(key, shape):
if key in uint8_features:
return tf.io.FixedLenSequenceFeature(
shape=[], dtype=tf.string, allow_missing=True)
else:
return tf.io.FixedLen... | 5,345,576 |
def unique_list(a_list, unique_func=None, replace=False):
"""Unique a list like object.
- collection: list like object
- unique_func: the filter functions to return a hashable sign for unique
- replace: the following replace the above with the same sign
Return the unique subcollection of collectio... | 5,345,577 |
def update_topics (graph, frags, known_topics, topic_id, phrase, pub_id, rank, count):
"""
update the known topics
"""
if topic_id not in known_topics:
t = {
"uuid": topic_id,
"label": phrase,
"used": False,
"pubs": []
}
known_... | 5,345,578 |
def airflow_runtime_instance():
"""Creates an airflow RTC and removes it after test."""
instance_name = "valid_airflow_test_config"
instance_config_file = Path(__file__).parent / "resources" / "runtime_configs" / f"{instance_name}.json"
with open(instance_config_file, "r") as fd:
instance_config... | 5,345,579 |
def calculate_attitude_angle(eccentricity_ratio):
"""Calculates the attitude angle based on the eccentricity ratio.
Parameters
----------
eccentricity_ratio: float
The ratio between the journal displacement, called just eccentricity, and
the radial clearance.
Returns
-------
... | 5,345,580 |
def enc_obj2bytes(obj, max_size=4094):
"""
Encode Python objects to PyTorch byte tensors
"""
assert max_size <= MAX_SIZE_LIMIT
byte_tensor = torch.zeros(max_size, dtype=torch.uint8)
obj_enc = pickle.dumps(obj)
obj_size = len(obj_enc)
if obj_size > max_size:
raise Exception(
... | 5,345,581 |
def featCompression (feats, deltas, deltas2):
"""
Returns augmented feature vectors for all cases.
"""
feats_total = np.zeros (78)
for i in range (len (feats)):
row_total = np.array ([])
feat_mean = np.mean (np.array (feats[i]), axis = 0)
delt_mean = np.mean (np.array (deltas... | 5,345,582 |
def _array_indexing(array, key, key_dtype, axis):
"""Index an array or scipy.sparse consistently across NumPy version."""
if np_version < parse_version('1.12') or issparse(array):
# Remove the check for NumPy when using >= 1.12
# check if we have an boolean array-likes to make the proper indexin... | 5,345,583 |
def retryable(fun: Callable[[Any], None], re_init_func: Callable[[], Any], max_tries: int, *args: Dict[str, Any]):
"""
Retries the function multiple times, based on the max_tries
:param max_tries:
max number of tries
:type max_tries: ``int``
:param fun:
main function to retry
:ty... | 5,345,584 |
def get_stock_ledger_entries(previous_sle, operator=None,
order="desc", limit=None, for_update=False, debug=False, check_serial_no=True):
"""get stock ledger entries filtered by specific posting datetime conditions"""
conditions = " and timestamp(posting_date, posting_time) {0} time... | 5,345,585 |
def test_binary(test_data, model, criterion, batch_size, device, generate_batch=None):
"""Calculate performance of a Pytorch binary classification model
Parameters
----------
test_data : torch.utils.data.Dataset
Pytorch dataset
model: torch.nn.Module
Pytorch Model
criterion: fun... | 5,345,586 |
def linear_imputer(y, missing_values=np.nan, copy=True):
"""
Replace missing values in y with values from a linear interpolation on their position in the array.
Parameters
----------
y: list or `numpy.array`
missing_values: number, string, np.nan or None, default=`np.nan`
The placeholder... | 5,345,587 |
def dump_json(gto, k, verbose=False):
"""
Print out the json representation of some data
:param gto: the json gto
:param k: the key to dump (none for everything)
:param verbose: more output
:return:
"""
if k:
if k in gto:
print(json.dumps(gto[k], indent=4))
e... | 5,345,588 |
def gap2d_cx(cx):
"""Accumulates complexity of gap2d into cx = (h, w, flops, params, acts)."""
cx["h"] = 1
cx["w"] = 1
return cx | 5,345,589 |
def test_is_not_healthy(requests_mock):
"""
Test is not healthy response
"""
metadata = Gen3Metadata("https://example.com")
def _mock_request(url, **kwargs):
assert url.endswith("/_status")
mocked_response = MagicMock(requests.Response)
mocked_response.status_code = 500
... | 5,345,590 |
def kernelTrans(X, A, kTup):
"""
通过核函数将数据转换更高维的空间
Parameters:
X - 数据矩阵
A - 单个数据的向量
kTup - 包含核函数信息的元组
Returns:
K - 计算的核K
"""
m,n = np.shape(X)
K = np.mat(np.zeros((m,1)))
if kTup[0] == 'lin': K = X * A.T #线性核函数,只进行内积。
elif kTup[0] == 'rbf': #高斯核函数,根据高斯核函数公式进行计算
for j i... | 5,345,591 |
def getBusEquipmentData(bhnd,paraCode):
"""
Retrieves the handle of all equipment of a given type (paraCode)
that is attached to bus [].
Args :
bhnd : [bus handle]
nParaCode : code data (BR_nHandle,GE_nBusHnd...)
Returns:
[][] = [len(bhnd)] [len(all equ... | 5,345,592 |
def build_and_register(
client: "prefect.Client",
flows: "List[FlowLike]",
project_id: str,
labels: List[str] = None,
force: bool = False,
) -> Counter:
"""Build and register all flows.
Args:
- client (prefect.Client): the prefect client to use
- flows (List[FlowLike]): the ... | 5,345,593 |
def helper_reset_page_retirements(handle, gpuId=0, reset_sbe=False):
"""
Helper function to reset non volatile page retirements.
"""
ret = dcgm_internal_helpers.inject_field_value_i64(handle, gpuId, dcgm_fields.DCGM_FI_DEV_RETIRED_DBE,
0, -30) # set the injected data to 30 seconds ago
assert... | 5,345,594 |
def generate_path_to_bulk_roms(
roms: List[models.BulkSystemROMS]) -> List[models.BulkSystemROMS]:
"""Creates the absolute path to where each rom should be downloaded"""
for system in roms:
for section in system.Sections:
if not 'number' in section.Section:
path: str ... | 5,345,595 |
def parse_args(args=sys.argv[1:]):
""" Get the parsed arguments specified on this script.
"""
parser = argparse.ArgumentParser(description="")
parser.add_argument(
'path_to_xml',
action='store',
type=str,
help='Ful path to tei file.')
parser.add_argument(
'o... | 5,345,596 |
def send_voting_location_sms(email, phone, fields):
"""Opts-in to SMS and sends caucus/polling location address text message.
We do two Mobile Commons API calls:
1. Create or update profile, with a state-specific opt-in path.
If the number is new to our national Mobile Commons campaign,
... | 5,345,597 |
def creer_element_xml(nom_elem,params):
"""
Créer un élément de la relation qui va donner un des attributs.
Par exemple, pour ajouter le code FANTOIR pour une relation, il faut que le code XML soit <tag k='ref:FR:FANTOIR' v='9300500058T' />"
Pour cela, il faut le nom de l'élément (ici tag) et un diction... | 5,345,598 |
def get_display():
"""Getter function for the display keys
Returns:
list: list of dictionary keys
"""
return data.keys() | 5,345,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.