content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def mo_tch_asy_ts(gps, anc_data):
""" Returns a recommendation via TS with Tchebychev Scalarization in the
asynchronous setting for MOO """
anc_data = copy(anc_data)
# Always use a random optimiser with a vectorised sampler for TS.
if anc_data.acq_opt_method != 'rand':
anc_data.acq_opt_method = 'rand'
... | 5,288,500 |
def preprocess(inputs, seeds = []):
"""
Function that produces a list of FuncInput objects with respect to each input.
To be used within forward() to process inputs.
PARAMETERS
==========
inputs : iterable type (list, np.array(), etc.)
Iterable containing the input values to the fun... | 5,288,501 |
def trajectory_derivatives(etas, es):
"""
given an eta-trajectory es(etas)
compute the first derivative and its absolute value
as well as the second derivatives
these are logarithmic derivatives: dE/dln(eta)
returns:
corrs: corrected trajectory, corr = E - dE/dln(eta)
absd1, absd... | 5,288,502 |
def ensure_correct_degeneracies(reaction_isotopomer_list, print_data = False, r_tol_small_flux=1e-5, r_tol_deviation = 0.0001):
"""
given a list of isotopomers (reaction objects), returns True if the correct
degeneracy values are detected. False if incorrect degeneracy values
exist.
This method ass... | 5,288,503 |
def run_io_in_bg(pod_obj, expect_to_fail=False):
"""
Run I/O in the background
Args:
pod_obj (Pod): The object of the pod
expect_to_fail (bool): True for the command to be expected to fail
(disruptive operations), False otherwise
Returns:
Thread: A thread of the I/O... | 5,288,504 |
async def _giveaway_reroll_slash(ctx, message_id: str) -> None:
""" Rerolls a giveaway. """
try:
message_id: int = int(message_id)
except ValueError:
await ctx.respond(f"**This is not a valid message ID, {ctx.author.mention}!**", ephemeral=True)
else:
await client.get_cog('Givea... | 5,288,505 |
def glexsort(
keys: numpy.typing.ArrayLike,
graded: bool = False,
reverse: bool = False,
) -> numpy.ndarray:
"""
Sort keys using graded lexicographical ordering.
Same as ``numpy.lexsort``, but also support graded and reverse
lexicographical ordering.
Args:
keys:
Val... | 5,288,506 |
def vector_norm(x):
"""computes the L2-norm along axis 1
(e.g. genes or embedding dimensions) equivalent to np.linalg.norm(A, axis=1)
"""
return np.sqrt(np.einsum("i, i -> ", x, x)) | 5,288,507 |
def _validate_node(node):
"""Validate the local, or username, portion of a JID.
:raises InvalidJID:
:returns: The local portion of a JID, as validated by nodeprep.
"""
try:
if node is not None:
node = nodeprep(node)
if not node:
raise InvalidJID('Lo... | 5,288,508 |
def get_blogs(keywords, client_id, client_secret):
"""
Naver 검색-블로그 api를 사용해서 특정 키워드에 대한 Blog 정보 수집
:Params list keywords : 키워드 리스
:Params str client_id : Api 사용 아이디
:Params str client_pw : Api 사용 비밀번호
:return blogs_items : Api 검색 결과 중 블로그 아이템들
:rtype list
"""
blog_items = []
f... | 5,288,509 |
def get_unique(label=''):
"""Save unique models in a separate file"""
sampler = np.load('../data/samples{}.npz'.format(label))
models, ind = np.unique(sampler['chain'], axis=0, return_index=True)
ifinite = np.isfinite(sampler['lnp'][ind])
np.savez('../data/unique_samples{}'.format(label), ... | 5,288,510 |
def async_add_entities_discovery(hass, discovery_info, async_add_entities):
"""Set up lights for KNX platform configured via xknx.yaml."""
entities = []
for device_name in discovery_info[ATTR_DISCOVER_DEVICES]:
device = hass.data[DATA_XKNX].xknx.devices[device_name]
entities.append(KNXLight(... | 5,288,511 |
def pull_team_ids(game_id: str) -> Union[int, int, bool, List]:
""" This function pulls the JSON file for a
game's play-by-play data and converts it into
a Pandas DataFrame
@param game_id (str): 10-digit string \
that represents a unique game. The format is two leading zeroes, \
followed by a seaso... | 5,288,512 |
def generate_full2vc(model, times, icell=None, set_parameters=None,
return_parameters=False, return_voltage=False,
add_linleak=False, transform=None, fakedatanoise=20.0):
"""
Generate synthetic data
Input
=====
model: Pints forward model
times: time points for synthetic data
... | 5,288,513 |
def get_lazy_args(argval, request_or_item):
"""
Possibly calls the lazy values contained in argval if needed, before returning it.
Since the lazy values cache their result to ensure that their underlying function is called only once
per test node, the `request` argument here is mandatory.
:param re... | 5,288,514 |
def load_envvars(logger):
""" Load the environment variables for Kaggle authentication.
"""
# find .env automagically by walking up directories until it's found, then
# load up the .env entries as environment variables
logger.info("Loading envvars...")
load_dotenv(find_dotenv())
logger.i... | 5,288,515 |
def parse_scan_interval(scan_interval: Union[timedelta, str]) -> timedelta:
"""Parse and validate scan_interval."""
if isinstance(scan_interval, str):
if isinstance(scan_interval, str):
if scan_interval.lower() == "none":
scan_interval = None
else:
... | 5,288,516 |
def test_empty_table():
"""Test RPC methods with empty routing table"""
peer_id, peer_proc, peer_peer_id, peer_maddrs = launch_protocol_listener()
loop = asyncio.get_event_loop()
p2p = loop.run_until_complete(P2P.create(initial_peers=peer_maddrs))
protocol = loop.run_until_complete(
DHTProt... | 5,288,517 |
def test_trig_function_radians(name, postgresql_engine):
"""Test trig functions that expect radians."""
angle = random.uniform(-math.pi, math.pi)
func = getattr(math, name)
sql_func = getattr(sql_math, name)
(result,), = postgresql_engine.execute(select([sql_func(angle)]))
assert result == pytes... | 5,288,518 |
def test_integ_delete_force(source, target, default_transfer_config):
"""Test for forced integrate of a delete being required."""
inside_file1 = source.local_path("inside/inside_file1")
inside_file2 = source.local_path("inside/inside_file2")
inside_file1.write_bytes(b"Test content")
source.p4("add",... | 5,288,519 |
def closest_point(geom1,geom2):
"""
Use the PostGIS function ST_ClosestPoint() to return the 2-dimensional point on geom1 that is closest to geom2. This requires
PostGIS 1.5 or newer.
"""
cursor = connection.cursor()
query = "select st_asewkt(ST_ClosestPoint('%s'::geometry, '%s'::geomet... | 5,288,520 |
def prepare_arguments_for_callable(combination_of_reactant_species, reactant_string_list, rate_function_arguments):
"""
This function prepares the requested arguments to the rate function for a given reaction by creating objects
of the Specific_Species_Operator class
Parameters:
... | 5,288,521 |
def set_context(args, rank_size):
"""set context"""
if rank_size > 1:
if args.device_target == "Ascend":
device_id = int(os.getenv('DEVICE_ID'))
context.set_context(
mode=context.GRAPH_MODE,
device_target=args.device_target,
device_... | 5,288,522 |
def image_tag():
"""used to deploy a particular tag of a Docker image.
May return:
- a commit
- a branch name such as `approved`
- the conventional `latest`"""
revision = cfg('project.revision')
if revision == 'master':
return 'latest' # conventionally stable Docker tag
if n... | 5,288,523 |
def cosmoScale(redshift, WMAP9=True, H0=69.3, Om0=0.287,
Planck15=True):
"""
Get the Angular Scale (kpc/") at redshift=z.
This is simply a wrapper of astropy.cosmology
The input redsfhit can be an array
"""
if WMAP9:
from astropy.cosmology import WMAP9 as cosmo
elif P... | 5,288,524 |
def getUserInterfaceHandlers():
""" Parse the UI handlers and create routes. Assert that the route is specified. """
NO_ROUTE_SPECIFIED = "The class {0} did not specify its route."
handlers = []
for func in [eval("user_interface." + f) for f in dir(user_interface)
if "Handler" in f an... | 5,288,525 |
def prepare_const():
"""
Using a function to prepare the const we need.
:return: this file's const
"""
const = Const()
const.SRC_FILE_NAME = ''
const.DES_FILE_NAME = ''
return const | 5,288,526 |
def _write_function(schema):
"""Add a write method for named schema to a class.
"""
def func(
data,
filename=None,
schema=schema,
id_col='id',
sequence_col='sequence',
extra_data=None,
mtype=None,
**kwargs):
# Use generic write class to... | 5,288,527 |
def is_valid_tag(tag):
"""Only some tags are acceptable in the whoosh schema, this function checks if
the tag is acceptable.
"""
try:
Schema(**{tag: TEXT})
except FieldConfigurationError as e:
return False, e.args[0]
else:
return True, 'OK' | 5,288,528 |
def test_cray_hsmV2_locks_status_create(cli_runner, rest_mock):
""" Test `cray hsm locks status create` with valid params """
runner, cli, config = cli_runner
url_template = '/apis/smd/hsm/v2/locks/status'
compIDs = "x0c1s2b0n0,x0c1s2b0n1"
result = runner.invoke(
cli,
['hsm', 'locks... | 5,288,529 |
def plot_trend(timeSeries, **kwargs):
""" Plot trand of a time series
Parameters:
--------------------------------------------------------------------
* timeSeries: list of float data
* `ax` [`Axes`, optional]:
The matplotlib axes on which to draw the plot, or `None` to create
a ne... | 5,288,530 |
def validate_id(value):
"""Validate Id"""
regexObj = re.compile('^[1-9]+[0-9]*$')
obj = RegexValidator(regexObj, _('Validation error. Id expected.'))
obj.__call__(value) | 5,288,531 |
def parse_pr(pr_txt: str) -> Dict[str, Union[dt.date, int, Dict[str, Any]]]:
"""Parses each section of the daily COVID-19 report and places everything
in a single object.
"""
new_cases, new_deaths = _get_new_cases_deaths(pr_txt)
hd_cases_deaths = _parse_hd_cases_deaths(pr_txt)
return {
... | 5,288,532 |
def np_linspace(start: float = 0, stop: float = 0, num: int = 50, endpoint: bool = True,
retstep: bool = False, dtype: np.dtype = None):
"""
returns a numpy linear space.
Refer to numpy linspace function for argument description
Parameters
----------
start : float
stop : float
n... | 5,288,533 |
def read_image(image_path: str):
"""
Loads image as numpy array from given path.
"""
# read image
image = cv2.imread(image_path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# return image
return image | 5,288,534 |
async def fetch_posts(names_dict):
"""Fetch dict of posts."""
results = {}
async with httpx.AsyncClient(timeout=DEFAULT_TIMEOUT) as async_client:
async with trio.open_nursery() as nursery:
for label, name in names_dict.items():
assembler = partial(_assemble.assemble_post,... | 5,288,535 |
def check_config():
""" Check config variables are valid for exection """
check_llvm_config(LLVMCONFIG)
check_clang(CLANG)
check_llvmlink(LLVMLINK)
check_opt(LLVMOPT)
check_opt_delete(LLVMOPT, OPTDELETE) | 5,288,536 |
def area(box):
"""Calculates area of a given bounding box."""
return float((box[1][0]-box[0][0]) * (box[1][1] - box[0][1])) | 5,288,537 |
def get_world_transform(axes):
"""
Get the transformation to world coordinates.
If the axes is a `wcaxes.WCSAxes` instance this returns the transform to
the ``'world'`` coordinates, otherwise it returns the transform to the
matplotlib data coordinates, which are assumed to be in world coordinates.
... | 5,288,538 |
def save_data(frame, file_name, path, suffix='', cut_ext=False):
"""
Primary function to save data to csv.
If file name contains an extension, can be cut by setting cut_ext to True.
"""
if cut_ext:
name = cut_extension(file_name) + suffix + '.csv'
else:
name = file_name... | 5,288,539 |
def main():
"""Make a jazz noise here"""
state = State()
while state.repeat and not state.quit:
# i can't really understand why state = State() is not sufficient to
# clear the state: the board remains the last of the previous game
state = State(board=list('.' * 9))
while n... | 5,288,540 |
def validate_can_run():
"""
Returns False if CI_PROJECT_DIR exists and platform is Windows, and
True otherwise.
"""
if 'CI_PROJECT_DIR' in os.environ and platform.system() == 'Windows':
return True
return True | 5,288,541 |
def get_symbol(x):
"""
Return an appropriate symbol to use for MyBayes, always returning the
same symbol for the same input.
"""
if x in _sym_map:
return _sym_map[x]
else:
sym = _possible_symbols.pop(0)
_sym_map[x] = sym
return sym | 5,288,542 |
def retrieve_shared_secret(service, attempts=3):
"""
Retrieve the shared secret for a service from the distributed
key value store. If it can't be retrieved or is empty, retry
it a couple of times just in case there is no consensus in
the cluster. If we re-create a new secret we split the
networ... | 5,288,543 |
def test_generator(scenario, seed):
"""Tests generating all generated benchmark scenarios using a range of
seeds, checking for any errors
"""
nasim.make_benchmark(scenario, seed=seed) | 5,288,544 |
def densecrf3d(I, P, param):
"""
input parameters:
I: a numpy array of shape [D, H, W, C], where C is the channel number
type of I should be np.uint8, and the values are in [0, 255]
P: a probability map of shape [D, H, W, L], where L is the number of classes
type of P shoul... | 5,288,545 |
def isolated_40():
"""
Real Name: b'Isolated 40'
Original Eqn: b'INTEG ( isolation rate symptomatic 40+isolation rate asymptomatic 40-isolated recovery rate 40\\\\ -isolated critical case rate 40, init Isolated 40)'
Units: b'person'
Limits: (None, None)
Type: component
b''
"""
retur... | 5,288,546 |
def _make_html(dates, observer_id=None, region_name=None, data_description=None, html_folder=env.output_folder + 'views/'):
"""Method serves both plots for selected observers or selected regions.
:param dates:
:param observer_id:
:param region_name: If doing observers: region_name=None else: we... | 5,288,547 |
def intersect_bed(file_a, file_b, u=False, v=False):
"""
function intersect bed files and return
new intersection bed file
paramenters:
file_a=path to a bed (str)
file_b=path to b bed (str)
u=unique intervals (bool)
v=not matching intervals (bool)
"""
a_obj = BedTool(file_a)
... | 5,288,548 |
def test_dbus_interface_oom(dev, apdev):
"""D-Bus CreateInterface/GetInterface/RemoveInterface OOM error cases"""
(bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
wpas = dbus.Interface(wpas_obj, WPAS_DBUS_SERVICE)
with alloc_fail_dbus(dev[0], 1, "wpa_dbus_dict_get_entry;wpas_dbus_handler_create_interf... | 5,288,549 |
def funequal(x, y):
"""Utility for `equal_dimensions`.
# Arguments
x: Tensor or variable.
y: Tensor or variable.
# Returns
A tensor
"""
new_y = zeros([1, 1, 1, 1])
new_y = set_subtensor(new_y[:, :, :-1, :-1], y)
return new_y | 5,288,550 |
def visualize_combined_rboxes(sess_outputs, save_dir):
"""
Visualize joined rboxes.
"""
fig.clear()
ax = fig.add_subplot(111)
images = sess_outputs['images']
rboxes = sess_outputs['combined_rboxes']
counts = sess_outputs['combined_counts']
n_images = images.shape[0]
for i in range(n_images):
l... | 5,288,551 |
def sentence_to_token_ids(sentence, word2id):
""" Gets token id's of each word in the sentence and returns a list of
those words. Is called by data_to_token_ids and the Lexer.
Args:
sentence: A list of word tokens.
word2id: A dictionary that maps words to its given id. This c... | 5,288,552 |
def garbage_collect_games():
"""
Check for games that are still in the database after 24 hours
"""
delta_24_hours = datetime.timedelta(days=1)
with sqlite3.connect(moosic_db) as c:
#check for all games that haven't been monitored for 24 hrs
disconnected_games = c.execute('''SELECT... | 5,288,553 |
def drawxband(refval,
xlims=None,
color='gray',
bandwidths=[-0.1, 0.1],
ua=None):
"""
draw a shaded band of color color of certain width around a single
reference value refval
Parameters
----------
refval : float , mandatory
scalar... | 5,288,554 |
def check_zxid_consistency(zk_client):
"""
"""
raise NotImplementedError() | 5,288,555 |
def change_control_mode(requested_mode):
"""
Change the controller mode of the DP controller.
Although this is technically breaking the design
idea that FSM and controller should not talk to
eachother, it makes sense to keep it for now, seeing
as some guidance systems may rely on one of the con... | 5,288,556 |
def test_s3_download_file( moto_boto, path, url, ftype, expected, fs, caplog):
"""
Checking for successful/failed file download from Object storage server
"""
with S3Transput(path, url, ftype) as trans:
assert trans.download_file() == expected
if expected:
assert "Not Found" ... | 5,288,557 |
def _treat_outliers(data: "DataFrame", n_quantiles: int = 4) -> "DataFrame":
"""Find and edit outliers based on quantiles."""
q_low = data.quantile(1 / n_quantiles)
q_high = data.quantile((n_quantiles - 1) / n_quantiles)
iqr = q_high - q_low # interquartile range
# Either: Flooring and capping.
... | 5,288,558 |
def load_word_embedding(vectors_file):
""" Load the word vectors"""
vectors= np.genfromtxt(vectors_file, delimiter='\t', comments='#--#',dtype=None,
names=['Word']+['EV{}'.format(i) for i in range(1,51)]) #51 is embedding length + 1, change accoridngly if the size of embedding is n... | 5,288,559 |
def dtype_to_ome_type(npdtype: np.dtype) -> PixelType:
"""
Convert numpy dtype to OME PixelType
Parameters
----------
npdtype: numpy.dtype
A numpy datatype.
Returns
-------
ome_type: PixelType
One of the supported OME Pixels types
Raises
------
ValueError
... | 5,288,560 |
def get_fps_points():
"""key is str(obj_id) generated by
core/gdrn_modeling/tools/hb/hb_1_compute_fps.py."""
fps_points_path = osp.join(model_dir, "fps_points.pkl")
assert osp.exists(fps_points_path), fps_points_path
fps_dict = mmcv.load(fps_points_path)
return fps_dict | 5,288,561 |
def Generate_Raven_Timeseries_rvt_String(
outFolderraven, outObsfileFolder, obsnm, Model_Name
): # Modify_template_rvt(outFolderraven,outObsfileFolder,obsnm):
"""Generate a string in Raven time series rvt input file format
Function that used to modify raven model timeseries rvt file (Model_Name.rvt)
... | 5,288,562 |
def insert_clause(table_name, keys):
""" Create a insert clause string for SQL.
Args:
table_name: The table where the insertion will happen.
keys: An iterator with strings specifying the fields to change.
Returns:
The query as a string
"""
fields... | 5,288,563 |
async def discordRemoveAllReactions(message):
""" Removes all Reactions on a Message. """
for reaction in message.reactions:
await reaction.clear() | 5,288,564 |
def knn_graph_quantile(mat, self_loops=False, k=8, symmetric=True):
"""
Takes an input correlation matrix and returns a k-Nearest
Neighbour weighted undirected adjacency matrix.
"""
if not (mat.shape[0] == mat.shape[1]):
raise ValueError("Adjacency matrix must be square.")
dim = mat.sh... | 5,288,565 |
def createLocalRealm(user, domain):
""" Administra localmente las claves publicas/privadas """
try:
print("[] Generating pair keys...")
publicKey, privateKey = crypto.PairKey(plain=True)
print("[] Saving keys ...")
save(constant.USER_PUBLIC_KEY.format(user), publicKey.exportKey('... | 5,288,566 |
def strip_non_alpa(text):
"""
Strip string from non alpha caracters
"""
letters = []
for let in list(text):
if let.isalpha():
letters.append(let)
return letters | 5,288,567 |
def uniform_weight(labels, inputs):
"""apply same weight to every voxel/example"""
return tf.constant(1.0) | 5,288,568 |
def handler(event, context):
"""
Returns all of the Vulnerabilities
"""
vulnerabilities = dynamodb.query(
table_name=table_name,
query=Key('category').eq('vuln'),
)
if vulnerabilities:
vulnerabilities = sorted(vulnerabilities, key = lambda i: i['count'], reverse=True)
... | 5,288,569 |
def Normal_logZ(mu, cov): #tested
"""
compute the log normalizing constant of a normal distribution given a mean vector and a covariance *vector
arguments
mu : jnp.array(Dx)
mean vector
cov : jnp.array(Dx)
covariance vector
returns
logZ : float
... | 5,288,570 |
def implicit_euler(xs, h, y0, f, **derivatives):
"""Implicit Euler"""
ys = [y0]
for k in range(len(xs) - 1):
subsidiary_y = ys[k] + f(xs[k], ys[k]) * h
next_y = ys[k] + f(xs[k + 1], subsidiary_y) * h
ys.append(next_y)
return ys | 5,288,571 |
def test3():
"""
https://medium.com/%E9%B3%A5-crl/python%E9%9A%A8%E7%AD%86-requests-lxml%E5%9F%BA%E6%9C%AC%E7%88%AC%E8%9F%B2-%E4%BB%A5%E5%8D%9A%E5%AE%A2%E4%BE%86%E5%8D%B3%E6%99%82%E6%8E%92%E8%A1%8C%E6%A6%9C%E7%82%BA%E4%BE%8B-f9c67de0644e
"""
# headers = {
# "User-Agent": "Mozilla/5.0 (Windows N... | 5,288,572 |
def getSampleStory(depth=3):
"""Makes a story with lots of paragraphs. Uses the random
TOC data and makes paragraphs to correspond to each."""
from reportlab.platypus.doctemplate import randomText
from random import randint
styles = getSampleStyleSheet()
TOCData = getSampleTOCData(depth... | 5,288,573 |
def gen_pca_system(l, q):
"""make random PCA linear system
Parameters
----------
l : {int}
dimension of observations
q : {int}
dimension of PC system
Returns
-------
:class:`~numpy:numpy.ndarray`
shape `(l, )` array of eigenvalues
:class:`~numpy:numpy.nd... | 5,288,574 |
def autoconfirm(*param_decls, **kwargs):
"""Add a ``--yes`` option which shows a prompt before continuing if not passed. If the prompt is declined, the program will exit.
:param param_decls: One or more option names. Defaults to the single
value ``"--yes"``.
:param kwargs: Extra arguments are passe... | 5,288,575 |
def hidden_shift(nbits=6, expected_output=None, measure=True):
"""
Nbits should always be even.
This is a nbit hiddenshift algorithm that finds the hidden shift string "s" for
which f(x) = f(x + s) reference: https://www.pnas.org/content/114/13/3305.full
"""
if expected_output is Non... | 5,288,576 |
def getEdgeMask(match_array, hull_concavity=0.5, crop=None,
res=None, min_data_cluster=1000):
"""
Return an array masking ON bad edges on a mass
of good data (see Notes) in a matchtag array.
Parameters
----------
match_array : ndarray, 2D
Binary array to mask containing ... | 5,288,577 |
def resnet3d50(num_classes=339, pretrained=True, **kwargs):
"""Constructs a ResNet3D-50 model."""
model = modify_resnets(ResNet3D(Bottleneck, [3, 4, 6, 3], num_classes=num_classes, **kwargs))
if pretrained:
model.load_state_dict(load_checkpoint(weights['resnet3d50']))
return model | 5,288,578 |
def get_encrypted_picture_from_string(encrypted_picture_str):
"""
:param user: str, ID of the user who ask for authentication for retrieving the linked encrypted picture
:return: numpy.ndarray, ecnrypted picture linked to the user account
"""
if isinstance(encrypted_picture_str, str) is False:
... | 5,288,579 |
def start():
"""
Start the active MarkLogic version.
"""
is_activated = all([p.exists() and p.is_symlink() for p in INSTALLED_PATHS])
if not is_activated:
raise RuntimeError('Please activate a MarkLogic version before starting.')
subprocess.run(['service', 'MarkLogic', 'start']) | 5,288,580 |
def _graham_scan(points):
"""Returns points on convex hull of an array of points in CCW order."""
points.sort()
lh = reduce(_keep_left, points, [])
uh = reduce(_keep_left, reversed(points), [])
return lh.extend(uh[i] for i in xrange(1, len(uh) - 1)) or lh | 5,288,581 |
def coin_partitions(n, coin_types=COINS_AMOUNT) -> Iterator[list[int]]:
"""
Yields number n partitions using 1, 2, 5, 10, 20, 50, 100 and 200.
Partition i represented as 8 element array showing amount of every cons:
[0, 1, 2, 0, 0, 0, 0, 1] = 207.
"""
def update_partition(value, k=COINS_AMOUNT)... | 5,288,582 |
def _update_font_defaults(setting: str) -> None:
"""Update all fonts if fonts.default_family/_size was set."""
if setting not in {'fonts.default_family', 'fonts.default_size'}:
return
configtypes.FontBase.set_defaults(config.val.fonts.default_family,
config.val... | 5,288,583 |
def resnet18(pretrained=False, **kwargs):
"""Constructs a ResNet-18 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs)
return model if pretrained is False else load_pretrained(model, 'resnet18') | 5,288,584 |
def get_the_content(url, date):
""" 컴퓨터 공학과 홈페이지 내용들 가져오기. """
ret = []
res = requests.get(url)
soup = BeautifulSoup(res.content, "html.parser")
update = soup.select('div.total-wrap > span')
ret.append("오늘 업데이트 된 게시글 : " + update[1].text)
files = soup.select('tbody > tr')
for item in ... | 5,288,585 |
def contractual_lccsd(
qc_module: str, driver: str, reference: str, method: str, corl_type: str, fcae: str
) -> Tuple[str, str, bool]:
"""Of the list of QCVariables an ideal LCCSD should produce, returns whether or
not each is expected, given the calculation circumstances (like QC program).
Parameters
... | 5,288,586 |
def MergeBaseClass(cls, base):
"""Merge a base class into a subclass.
Arguments:
cls: The subclass to merge values into. pytd.Class.
base: The superclass whose values will be merged. pytd.Class.
Returns:
a pytd.Class of the two merged classes.
"""
bases = tuple(b for b in cls.bases if b != base)... | 5,288,587 |
def chart_data_to_df(func):
"""获取df"""
@wraps(func)
def inner(self, *args, **kwargs):
if self.df.empty:
columns = ["datetime", "open", "high", "low", "close", "volume"].extend(self.extend_field)
self.df = pd.DataFrame(self.list_dict, columns=columns)
return func(self,... | 5,288,588 |
def meeus(date, planet='earth', dformat='jd', rtn=None, ref_rtn='sun'):
"""Meeus algorithm to determine planet ephemerides in ECLIPJ2000 frame
:param date: calendar date (yyyy-mm-dd hh:mm:ss.ss)
:param planet: planet to get state from
:param dformat: date format; jd or utc; default is jd
:param rtn:... | 5,288,589 |
def choose_pivot_first(_: list[int], left: int, __: int) -> int:
"""Choose first element as pivot"""
return left | 5,288,590 |
def __virtual__():
"""
Check dependencies
"""
if has_depends is False:
msg = "jks unavailable: {0} execution module cant be loaded ".format(
__virtualname__
)
return False, msg
return __virtualname__ | 5,288,591 |
def limit(
limit_results: fit.LimitResults,
*,
figure_folder: Union[str, pathlib.Path] = "figures",
close_figure: bool = True,
save_figure: bool = True,
) -> mpl.figure.Figure:
"""Visualizes observed and expected CLs values as a function of the POI.
Args:
limit_results (fit.LimitRes... | 5,288,592 |
def custom_callback(stopping_rounds, metric, fevals, evals=(), log_file=None,
maximize=False, verbose_eval=True, skip_every=5):
"""Callback function for xgboost to support multiple custom evaluation functions"""
from xgboost.core import EarlyStopException
from xgboost.callback import _fm... | 5,288,593 |
def retag_from_strings(string_tag) :
"""
Returns only the final node tag
"""
valure = string_tag.rfind('+')
if valure!= -1 :
tag_recal =string_tag [valure+1:]
else :
tag_recal = string_tag
return tag_recal | 5,288,594 |
def voronoi(obj, tol=0.0, bounds=None):
"""
Computes a Voronoi diagram.
*obj* is a :class:`Geometry <geoscript.geom.Geometry>` or a ``list`` of
geometries.
*tol* is the snapping tolerance used to improved the robustness of the
*bounds* is an optional :class:`Bounds <geoscript.geom.Bounds>` used to
c... | 5,288,595 |
def get_base_model(model_name, weights_path, weight_decay=1e-4):
"""
Define base model used in transfer learning.
"""
if not weights_path:
weights_path = 'imagenet'
if model_name == 'VGG16':
base_model = VGG16(weights=weights_path, include_top=False)
elif model_name == 'VGG19... | 5,288,596 |
def test_breadth_first_traversal_small(small_tree):
"""test breadth-first traversal"""
assert small_tree.breadth_first_traversal() == [1, 2, 3] | 5,288,597 |
def audio_callback(indata, frames, time, status):
"""信号入力用コールバック
Arguments:
indata {numpy.array} -- 信号
frames {int} -- 信号のサイズ
time {CData} -- ADCキャプチャ時間
status {CallbackFlags} -- エラー収集用のフラグ
"""
if status:
print(status, file=sys.stderr)
# Fancy indexing with ma... | 5,288,598 |
def _select_config(conf,
root_node: str, child_node: str,
selection: str):
"""
Extract the list of step objects corresponding to
the list of names provided.
Parameters
----------
conf
step configuration object
root_node : str
node to sta... | 5,288,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.