content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def optimise_sdss_features(sdss, scaler_path):
""" Apply the W14 reddening correction and compute key colours in the SDSS dataset.
Parameters
----------
sdss : DataFrame
The DataFrame containing photometric features.
"""
# compute the three sets of reddening correction
... | 5,327,300 |
def test_makecondenserloop():
"""pytest for makecondenserloop"""
tdata = (
(
"",
"c_loop",
["sb0", ["sb1", "sb2", "sb3"], "sb4"],
["db0", ["db1", "db2", "db3"], "db4"],
"""BRANCH, sb0, 0.0, , Pipe:Adiabatic, sb0_pipe,
c_loop Cond_Supply... | 5,327,301 |
def trailing_whitespace(text):
"""Gets trailing whitespace of text."""
trailing = ""
while text and text[-1] in WHITESPACE_OR_NL_CHARS:
trailing = text[-1] + trailing
text = text[:-1]
return trailing | 5,327,302 |
def rjust(a, width, fillchar=' '):
"""
Return an array with the elements of `a` right-justified in a
string of length `width`.
Calls `str.rjust` element-wise.
Parameters
----------
a : array_like of str or unicode
width : int
The length of the resulting strings
... | 5,327,303 |
async def test_setup_import(opp: OpenPeerPower, router: Mock):
"""Test setup of integration from import."""
await async_setup_component(opp, "persistent_notification", {})
entry = MockConfigEntry(
domain=DOMAIN,
data={CONF_HOST: MOCK_HOST, CONF_PORT: MOCK_PORT},
unique_id=MOCK_HOST,... | 5,327,304 |
def form_image_helper(caption_list, dummy=True, image_suffix='.jpg'):
"""
:param caption_list: <class 'list'>
:param dummy: <class 'bool'>
:param image_suffix: <class 'str'>
:return: <class 'dict'> [dict of dummy images for form submission in django unittest]
"""
try:
res = {}
... | 5,327,305 |
def test_calculate_part_stress():
"""calculate_part_stress() should return a the attributes dict updated with
calculated values."""
ATTRIBUTES["subcategory_id"] = 1
_attributes = integratedcircuit.calculate_part_stress(**ATTRIBUTES)
assert isinstance(_attributes, dict)
assert _attributes["piL"]... | 5,327,306 |
def is_complex_converter(obj: Any) -> bool:
"""Check if the object is a complex converter.`"""
return isinstance(obj, ComplexConverterABC) or inspect.isclass(obj) and issubclass(obj, ComplexConverterABC) | 5,327,307 |
def test_delete_unknown_secret(
corev1_api_client_with_user_secrets, user_secrets, no_db_user
):
"""Test delete a non existing secret."""
with patch(
"reana_commons.k8s.secrets." "current_k8s_corev1_api_client",
corev1_api_client_with_user_secrets(user_secrets),
) as api_client:
... | 5,327,308 |
def find_pool_or_vip_by_name(full_list, queried_name, fuzzy_search):
"""Wrapper function for searching the pools or VIPs."""
logger.debug(
"Performing search for %s in %s partition",
queried_name,
ARGS.partition,
)
if fuzzy_search:
matches = find_resource_by_fuzzysearch... | 5,327,309 |
def _get_spreadsheet_with_values(spreadsheet_id):
"""Gets all sheets and their cells."""
sheets = []
if not service:
return sheets
result = service.spreadsheets().get(spreadsheetId=spreadsheet_id, fields=FIELDS).execute()
for sheet in result["sheets"]:
if "merges" in sheet:
... | 5,327,310 |
def some_task():
""" Some task """
get_word_counts('python.txt')
get_word_counts('go.txt')
get_word_counts('erlang.txt')
get_word_counts('javascript.txt')
return "Task Done" | 5,327,311 |
def _accelerate(f, n_devices):
"""JIT-compiled version of `f` running on `n_devices`."""
if n_devices == 1:
return fastmath.jit(f)
return fastmath.pmap(f, axis_name='batch') | 5,327,312 |
def savemodel(model, epoch, trainloss, valloss, metric, optimizer, stopflag, name, scheduler, size):
"""Saves PyTorch model."""
torch.save({
'model': model.state_dict(),
'epoch': epoch,
'trainloss': trainloss,
'valloss': valloss,
'metric': metric,
'optimizer': opt... | 5,327,313 |
def plot_ranks(data,
rank_a,
rank_b,
label,
hue=None,
palette=None,
order=None,
ax=None,
offset=5,
xlim=(-0.5, 1.5),
label_kws=None,
legend_kws=None):
... | 5,327,314 |
def parse_shadowserver_time(time_string: Text) -> datetime.datetime:
"""Parse a date on the format '2018-10-17 20:36:23'"""
try:
return datetime.datetime.strptime(time_string[:19], '%Y-%m-%d %H:%M:%S')
except:
print(time_string)
raise | 5,327,315 |
def sample_along_rays(rng,
origins,
directions,
radii,
num_samples,
near,
far,
genspace_fn,
ray_shape,
single_jitter,
... | 5,327,316 |
def resize(img, size, interpolation=PIL.Image.BILINEAR):
"""Resize image to match the given shape.
This method uses :mod:`cv2` or :mod:`PIL` for the backend.
If :mod:`cv2` is installed, this function uses the implementation in
:mod:`cv2`. This implementation is faster than the implementation in
:mo... | 5,327,317 |
def build_punt():
""" Construye la ventana del registro del usuario"""
easy = PA.dividir_puntajes("facil")
medium = PA.dividir_puntajes("medio")
hard = PA.dividir_puntajes("dificil")
rows = len(max([easy, medium, hard], key=len))
def create_table(data, dif):
return sg.Table(
... | 5,327,318 |
def true_fov(M, fov_e=50):
"""Calulates the True Field of View (FOV) of the telescope & eyepiece pair
Args:
fov_e (float): FOV of eyepiece; default 50 deg
M (float): Magnification of Telescope
Returns:
float: True Field of View (deg)
"""
return fov_e/M | 5,327,319 |
def add_hooks():
"""
Adds the endpoint hooks to the application object.
"""
# Accounts hooks
APP.on_inserted_accounts += hooks.log_user_create # pylint: disable=E1101
APP.on_updated_accounts += hooks.log_user_modified # pylint: disable=E1101
APP.on_update_accounts += hooks.manage_user_upd... | 5,327,320 |
async def test_html_content_type_with_utf8_encoding(unused_tcp_port, postgres_db, database_name, async_finalizer):
"""Test whether API endpoints with a "text/html; charset=UTF-8" content-type work."""
configure(unused_tcp_port, database_name, postgres_db.port)
html_content = "<html><body>test</body></html>... | 5,327,321 |
def _increment_inertia(centroid, reference_point, m, mass, cg, I):
"""helper method"""
if m == 0.:
return mass
(x, y, z) = centroid - reference_point
x2 = x * x
y2 = y * y
z2 = z * z
I[0] += m * (y2 + z2) # Ixx
I[1] += m * (x2 + z2) # Iyy
I[2] += m * (x2 + y2) # Izz
I[... | 5,327,322 |
def enqueue_ide_stop(*args):
"""Reap theia session kube resources"""
rpc_enqueue(reap_theia_session_by_id, queue="theia", args=args) | 5,327,323 |
def token_addresses(
request,
token_amount,
number_of_tokens,
blockchain_services,
cached_genesis,
register_tokens):
""" Fixture that yields `number_of_tokens` ERC20 token addresses, where the
`token_amount` (per token) is distributed among the addresses behind `b... | 5,327,324 |
def threatExpertSearch(pyew):
""" Search in Threat Expert for the behavior's report """
baseurl = "http://www.threatexpert.com/report.aspx?md5="
buf = pyew.getBuffer()
url = baseurl + md5(buf).hexdigest()
webbrowser.open(url) | 5,327,325 |
def get_event_stream(ApplicationId=None):
"""
Returns the event stream for an app.
:example: response = client.get_event_stream(
ApplicationId='string'
)
:type ApplicationId: string
:param ApplicationId: [REQUIRED] ApplicationId
:rtype: dict
:return: {
... | 5,327,326 |
def saturating_sigmoid(x):
"""Saturating sigmoid: 1.2 * sigmoid(x) - 0.1 cut to [0, 1]."""
with tf.name_scope("saturating_sigmoid", [x]):
y = tf.sigmoid(x)
return tf.minimum(1.0, tf.maximum(0.0, 1.2 * y - 0.1)) | 5,327,327 |
def simulate_strategy(game, strategies, init_states, func):
"""
Harvest an accurate average payoff with the two strategies, considering traversing
all possible private cards dealt by nature
game : the pyspiel game
strategies : the index of player's strategy, a length two list
... | 5,327,328 |
def test_request_id(test_client, log_capture):
""" check if /foo endpoint will log something with request-id """
resp = test_client.get("/foo")
assert resp.json == {"bar": "BAR"}
last_record = log_capture.records[-1]
assert last_record.message == "some message logged in foo_endpoint"
assert las... | 5,327,329 |
def init_questionnaire_db():
"""Create a new questionnaire database."""
db = QuestionnaireDB()
with current_app.open_resource('util/schema_questionnaire.sql') as f:
db().executescript(f.read().decode('utf8')) | 5,327,330 |
async def is_nsfw_and_guild_predicate(ctx):
"""A predicate to test if a command was run in
an NSFW channel and inside a guild
:param ctx: The context of the predicate
"""
if not ctx.guild or not ctx.channel.is_nsfw():
raise NotNSFWOrGuild()
return True | 5,327,331 |
def get_account(opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetAccountResult:
"""
Get information on your DigitalOcean account.
## Example Usage
Get the account:
```python
import pulumi
import pulumi_digitalocean as digitalocean
example = digitalocean.get_account()
`... | 5,327,332 |
def get_partition_leaders(cluster_config):
"""Return the current leaders of all partitions. Partitions are
returned as a "topic-partition" string.
:param cluster_config: the cluster
:type cluster_config: kafka_utils.utils.config.ClusterConfig
:returns: leaders for partitions
:rtype: map of ("to... | 5,327,333 |
def xyzToAtomsPositionsWrapper(
xyzFileOrDir,
outDir=None,
outFileBaseName=None,
fileExt=None,
noOutFile=False):
"""
Wrapper for the xyzToAtomsPositions function.
Returns atom positions (order) given a molecule9s) in an xyz format.
The heavy atoms positions are b... | 5,327,334 |
def find_mod_names(file_path=__file__):
"""Find Ice module names that start with 'ice_test_'.
The returned names are without the extension '.ice'.
TODO: Needs to recurse in `test_` sub directories.
"""
directory = pathlib.Path(file_path).absolute().parent
# pylint: disable=no-member
return ... | 5,327,335 |
def WR(df, N=10, N1=6):
"""
威廉指标
:param df:
:param N:
:param N1:
:return:
"""
HIGH = df['high']
LOW = df['low']
CLOSE = df['close']
WR1 = 100 * (HHV(HIGH, N) - CLOSE) / (HHV(HIGH, N) - LLV(LOW, N))
WR2 = 100 * (HHV(HIGH, N1) - CLOSE) / (HHV(HIGH, N1) - LLV(LOW, N1))
... | 5,327,336 |
def make_fn_type(params):
"""Turn type parameters into corresponding internal type system object.
Returned object will represent the type of a function over the
parameters.
:param params: a list of type paramaters, e.g. from a type
signature. These should be instances of TypeOperator or
... | 5,327,337 |
def export(request, wid):
"""Export the logs from the given workflow
:param request: HTML request
:param pk: pk of the workflow to export
:return: Return a CSV download of the logs
"""
dataset = LogResource().export(
Log.objects.filter(user=request.user, workflow__id=wid)
)
# C... | 5,327,338 |
def record_params(setup_state):
"""
Copy config so we can easily work with it
"""
app = setup_state.app
worker_router_bp.config = dict(
[(key, value) for (key, value) in app.config.items()]
) | 5,327,339 |
def _validate_valid_xml(value):
"""
Checks whether the given value is well-formed and valid XML.
"""
try:
# Try to create an XML tree from the given String value.
_value = XML_DECL.sub(u'', value)
_ = etree.fromstring(_value.encode('utf-8'))
return True
... | 5,327,340 |
def import_submodules(package, recursive=True):
"""Import all submodules of a module, recursively, including subpackages
:param recursive: bool
:param package: package (name or actual module)
:type package: str | module
:rtype: dict[str, types.ModuleType]
"""
if isinstance(package, str):
... | 5,327,341 |
def seasonal_pattern(season_time):
"""Just an arbitrary pattern, you can change it if you wish"""
return np.where(season_time < 0.4,
np.sin(season_time * 2),
1 / np.exp(3 * season_time)) | 5,327,342 |
def prepare_files():
"""
Put all the lemmata to lexemes.txt. Put all the lexical
rules to lexical_rules.txt, if any. Create separate versions of
relevant files for diacriticless texts.
Put all grammar files to uniparser_turoyo/data_strict/
(original version) or uniparser_turoyo/data_nodiacritics... | 5,327,343 |
def dice(labels, predictions, axis, weights=1.0, scope=None, loss_collection=tf.GraphKeys.LOSSES, reduction=Reduction.SUM_BY_NONZERO_WEIGHTS):
"""Dice loss for binary segmentation. The Dice loss is one minus the Dice
coefficient, and therefore this loss converges towards zero.
The Dice loss between predict... | 5,327,344 |
def air_density(temp, patm, pw = 0):
"""
Calculates the density of dry air by means of the universal gas law as a
function of air temperature and atmospheric pressure.
m / V = [Pw / (Rv * T)] + [Pd / (Rd * T)]
where:
Pd: Patm - Pw
Rw: specific gas constant for wate... | 5,327,345 |
def index(dataset: Dataset, min_df=5, inplace=False, **kwargs):
"""
Indexes the tokens of a textual :class:`quapy.data.base.Dataset` of string documents.
To index a document means to replace each different token by a unique numerical index.
Rare words (i.e., words occurring less than `min_df` times) are... | 5,327,346 |
def login_principal(principal):
"""Start an interaction with `principal`."""
request = zope.publisher.browser.TestRequest()
request.setPrincipal(principal)
zope.security.management.newInteraction(request) | 5,327,347 |
def PerpendicularFrameAt(thisCurve, t, multiple=False):
"""
Return a 3d frame at a parameter. This is slightly different than FrameAt in
that the frame is computed in a way so there is minimal rotation from one
frame to the next.
Args:
t (double): Evaluation parameter.
Returns:
... | 5,327,348 |
def _attributes_cosmo2dict(cosmo):
"""
Converts CoSMoMVPA-like attributes to a dictionary form
Parameters
----------
cosmo: dict
Dictionary that may contains fields 'sa', 'fa', 'a'. For any of these
fields the contents can be a dict, np.ndarray (object array as returned
by l... | 5,327,349 |
def is_instrument_port(port_name):
"""test if a string can be a com of gpib port"""
answer = False
if isinstance(port_name, str):
ports = ["COM", "com", "GPIB0::", "gpib0::"]
for port in ports:
if port in port_name:
answer = not (port == port_name)
return answ... | 5,327,350 |
def test_irreg_topo_new(dans_grid2):
"""Test D4 routing on a toy irregular topo. 'method' passed to init."""
fr = FlowAccumulator(dans_grid2.mg, flow_director="D4")
fr.run_one_step()
assert_array_equal(dans_grid2.A_target_D4, dans_grid2.mg.at_node["drainage_area"])
assert_array_equal(
dans_g... | 5,327,351 |
def get_anvil_path():
"""Gets the anvil/ path.
Returns:
The full path to the anvil/ source.
"""
return os.path.normpath(os.path.dirname(__file__)) | 5,327,352 |
def share_data(value):
""" Take a value and use the same value from the store,
if the value isn't in the store this one becomes the shared version. """
# We don't want to change the types of strings, between str <=> unicode
# and hash('a') == hash(u'a') ... so use different stores.
# In theory... | 5,327,353 |
def gaussian_dropout(incoming, keep_prob, mc, scale_during_training = True, name=None):
""" Gaussian Dropout.
Outputs the input element multiplied by a random variable sampled from a Gaussian distribution with mean 1 and either variance keep_prob*(1-keep_prob) (scale_during_training False) or (1-keep_prob)/keep... | 5,327,354 |
def checkTimeStamp(op, graph, frm, to):
"""
Confirm the timestamp formats within the metadata did not change.
:param op:
:param graph:
:param frm:
:param to:
:return:
"""
edge = graph.get_edge(frm, to)
pred = graph.predecessors(to)
if pred<2:
ffile = os.path.join(grap... | 5,327,355 |
def bottom_up_low_space(N,K,ts):
"""
Recursive algorithm.
args:
N :: int
length of ts
K :: int
ts :: list of ints
returns:
res :: bool
True :: if a subset of ts sums to K
False :: otherwise
subset :: list of tuples
... | 5,327,356 |
def sincpt(method, target, et, fixref, abcorr, obsrvr, dref, dvec):
"""
Given an observer and a direction vector defining a ray, compute
the surface intercept of the ray on a target body at a specified
epoch, optionally corrected for light time and stellar
aberration.
This routine supersedes :f... | 5,327,357 |
def create_user_upload_path_if_not_exists(upload_path, user_id):
"""
Generates the upload path according to the user_id
:param upload_path:
:param user_id:
:return: nothing just creates the directory
"""
if not os.path.isdir(os.path.join(upload_path, str(user_id))):
os.makedirs(os.pa... | 5,327,358 |
def test_dahlquist_constructor_mr():
"""
Test constructor
"""
dahlquist = Dahlquist(t_start=0, t_stop=1, nt=11, method='MR')
np.testing.assert_equal('MR', dahlquist.method) | 5,327,359 |
def crumb_link(src_crumb: hansel.Crumb, dst_crumb: hansel.Crumb, exist_ok: bool=False, verbose: bool=False):
"""Will link the content of `src_crumb` into `dst_crumb` folder.
For this `src_crumb` and `dst_crumb` must have similar set of argument
names.
All the defined arguments of `src_crumb.ls()[0]` mus... | 5,327,360 |
def send_file(request, filepath_or_fp, mimetype=None, as_attachment=False,
attachment_filename=None, add_etags=True, cache_timeout=60 * 60 * 12,
conditional=False, use_x_sendfile=False, response_class=None):
"""Sends the contents of a file to the client. This will use the
most efficient method ... | 5,327,361 |
def getInfo(ID):
"""
get info from file
:param ID: meter ID
:return: info = {
"distance": 10,
"horizontal": 10,
"vertical": 20,
"name": "1_1",
"type": SF6,
"template": "template.jpg",
"ROI": {
"x": 200,
... | 5,327,362 |
def DO_run(wb, args: Union[list, None] = None, external: bool = False) -> RET:
"""run shell_command lfn|alien: tagged lfns :: download lfn(s) as a temporary file and run shell command on the lfn(s)"""
if args is None: args = []
if not args: return RET(1, '', 'No shell command specified')
if is_help(args... | 5,327,363 |
def get_keychain_pass(account=None, server=None):
"""
Gets the password for a given account from Apple's keychain
"""
params = {
'user': os.environ['USER'],
'security': '/usr/bin/security',
'command': 'find-internet-password',
'account': account,
'server': ser... | 5,327,364 |
def make_train_valid(labels_dir:Path, train:float=.8, valid:float=.2, test:float=0):
"""
usage: make_train_valid(labels_dir:Path, train:float=.8, valid:float=.2, test:float=0)
Make a train-valid directory and randomly copy files from labels_dir to sub-
directories
positional arguments:... | 5,327,365 |
def cast_tensor_by_spec(_input, spec):
"""
transform dtype & shape following spec
"""
try:
import tensorflow as tf
except ImportError:
raise MissingDependencyException(
"Tensorflow package is required to use TfSavedModelArtifact"
)
if not _isinstance_wrapper(... | 5,327,366 |
def StopRequestHook(ref, args, request):
"""Declarative request hook for TPU Stop command."""
del ref
del args
stop_request = GetMessagesModule().StopNodeRequest()
request.stopNodeRequest = stop_request
return request | 5,327,367 |
def get_bucket(
storage_bucket_name: str,
**kwargs,
) -> Bucket:
"""Get a storage bucket."""
client = get_client()
return client.get_bucket(storage_bucket_name, **kwargs) | 5,327,368 |
def furl_for(endpoint: str, filename: str=None, **kwargs: dict) -> str:
""" Replacement for url_for. """
return URL() + (url_for(endpoint, filename=filename) if filename != None else ("/" if endpoint == "" else url_for(endpoint, **kwargs))) | 5,327,369 |
def image_max_value(img, region=None, scale=None):
"""Retrieves the maximum value of an image.
Args:
img (object): The image to calculate the maximum value.
region (object, optional): The region over which to reduce data. Defaults to the footprint of the image's first band.
scale (float... | 5,327,370 |
def getblock(lst, limit):
"""Return first limit entries from list lst and remove them from the list"""
r = lst[-limit:]
del lst[-limit:]
return r | 5,327,371 |
def test_r53_policy_expected_aws_records(zone, boto_client):
"""
Tests a Policy builds the expected desired_records for the alias tree.
"""
policy = G(m.Policy, name='pol1')
policy_record = G(m.PolicyRecord, zone=zone, name='www', policy=policy)
ip1 = create_ip_with_healthcheck()
G(m.Policy... | 5,327,372 |
def run_gateway(gateway):
"""Run a sync gateway."""
gateway.start_persistence()
gateway.start()
try:
while True:
time.sleep(0.5)
except KeyboardInterrupt:
gateway.stop() | 5,327,373 |
def electrode_neighborhoods(mea='hidens', neighborhood_radius=HIDENS_NEIGHBORHOOD_RADIUS, x=None, y=None):
"""
Calculate neighbor matrix from distances between electrodes.
:param mea: (optional) type of the micro electrode array, default: 'hidens'
:param neighborhood_radius:(optional) depends on mea typ... | 5,327,374 |
def lat_from_meta(meta):
"""
Obtains a latitude coordinates array from rasterio metadata.
:param meta: dict rasterio metadata.
:return: numpy array
"""
try:
t, h = meta["transform"], meta["height"]
except KeyError as e:
raise e
lat = np.arange(t[5], t[5] + (t[4] * h), t[4... | 5,327,375 |
def get_test_class(dbcase):
"""Return the implementation class of a TestCase, or None if not found.
"""
if dbcase.automated and dbcase.valid:
impl = dbcase.testimplementation
if impl:
obj = module.get_object(impl)
if type(obj) is type and issubclass(obj, core.Test):
... | 5,327,376 |
def calc_dp(t_c, rh):
"""Calculate the dew point in Celsius.
Arguments:
t_c - the temperature in °C.
rh - the relative humidity as a percent, (0-100)
Returns:
The dew point in °C.
"""
sat_vp = vapor_pressure_liquid_water(t_c)
vp = sat_vp * rh / 100.0
a = log(vp / 6.... | 5,327,377 |
def getSlackMetar(input: flask.Request) -> Tuple[str, int, dict]:
"""
Endpoint handler for the slack_metar HTTP function trigger
"""
global _baseUrl
global _logger
_logger.debug("Entered metar")
station = _getStationName(input)
txt = _requestData('METAR', station)
return (_buildSlac... | 5,327,378 |
def conv_block(input_tensor, kernel_size, filters, stage, block, strides=(2, 2)):
"""conv_block is the block that has a conv layer at shortcut
# Arguments
input_tensor: input tensor
kernel_size: defualt 3, the kernel size of middle conv layer at main path
filters: list of integers, the f... | 5,327,379 |
def _fake_before_lines(first_line: str) -> List[str]:
"""Construct the fake lines that should go before the text."""
fake_lines = []
indent_levels = _indent_levels(first_line)
# Handle regular indent
for i in range(indent_levels):
prefix = SINGLE_INDENT * i
fake_lines.append(f"{pre... | 5,327,380 |
def normal_logpdf(x, mu, cov):
"""
Multivariate normal logpdf, numpy native implementation
:param x:
:param mu:
:param cov:
:return:
"""
part1 = 1 / (((2 * np.pi) ** (len(mu) / 2)) * (np.linalg.det(cov) ** (1 / 2)))
part2 = (-1 / 2) * ((x - mu).T.dot(np.linalg.inv(cov))).dot((x - mu)... | 5,327,381 |
def fork_workflow_step_context(
workflow_id: Optional[str] = _sentinel,
storage_url: Optional[str] = _sentinel,
workflow_scope: Optional[List[str]] = _sentinel,
outer_most_step_id: Optional[str] = _sentinel,
last_step_of_workflow: Optional[bool] = _sentinel,
checkpoint_context: CheckpointContext... | 5,327,382 |
def criteriarr(criteria):
"""Validate if the iterable only contains MIN (or any alias) and MAX
(or any alias) values. And also always returns an ndarray representation
of the iterable.
Parameters
----------
criteria : Array-like
Iterable containing all the values to be validated by the... | 5,327,383 |
def show_command(
*, login_manager: LoginManager, index_id: uuid.UUID, subject: str
) -> None:
"""Show the data for a given subject in an index
This is subject the visible_to access control list on the entries for that subject.
If there are one or more entries visible to the current user, they will be
... | 5,327,384 |
def integer_or_rational(entropy, signed, min_abs=0):
"""Returns a rational, with 50% probability of it being an integer."""
if random.choice([False, True]):
return integer(entropy, signed, min_abs=min_abs)
else:
return non_integer_rational(entropy, signed) | 5,327,385 |
def ignore_python_warnings(function):
"""
Decorator for ignoring *Python* warnings.
Parameters
----------
function : object
Function to decorate.
Returns
-------
object
Examples
--------
>>> @ignore_python_warnings
... def f():
... warnings.warn('This i... | 5,327,386 |
def runMetrics(
initWorkingSetName,
stepName,
requestInfo,
jobId,
outputFolder,
referenceFolder,
referencePrefix,
dtmFile,
dsmFile,
clsFile,
mtlFile,
):
"""
Run a Girder Worker job to compute metrics on output files.
Requirements:
- Danesfield Docker image is... | 5,327,387 |
def configure_logging(args):
"""Configures the default logger. This can be called only once and has to
be called before any logging is done.
"""
logging.TIMING = logging.ERROR + 5
logging.addLevelName(logging.TIMING, 'TIMING')
def timing(msg, *args, **kwargs):
logging.log(logging.TIMING... | 5,327,388 |
def terminal_bg():
"""Returns the first argument if the terminal has a light background, the second if it has a
dark background, and the third if it cannot determine."""
colorfgbg = os.environ.get('COLORFGBG', '')
if colorfgbg == '0;15':
return BGColor.LIGHT
if colorfgbg == '15;0':
r... | 5,327,389 |
def mkdir_p(path):
"""
Equivalent of mkdir -p on the commandline; wrapper around os.makedirs
@param path The path to create
"""
try:
os.makedirs(path)
except:
pass | 5,327,390 |
def matplotlib_kwarg_dealiaser(args, kind):
"""De-aliase the kwargs passed to plots."""
if args is None:
return {}
matplotlib_kwarg_dealiaser_dict = {
"scatter": mpl.collections.PathCollection,
"plot": mpl.lines.Line2D,
"hist": mpl.patches.Patch,
"bar": mpl.patches.Re... | 5,327,391 |
def volume():
"""
Get volume number
:return:
"""
return Scheduler.ret_volume | 5,327,392 |
def grid_grad(input, grid, interpolation='linear', bound='zero',
extrapolate=False):
"""Sample spatial gradients of an image with respect to a deformation field.
Notes
-----
{interpolation}
{bound}
Parameters
----------
input : ([batch], [channel], *inshape) tensor
... | 5,327,393 |
def delete_cart_item(quote_id, item_code):
"""Delete given item_codes from Quote if all deleted then delete Quote"""
try:
response = frappe._dict()
item_code = item_code.encode('utf-8')
item_list= [ i.strip() for i in item_code.split(",")]
if not isinstance(item_code, list):
item_code = [item_code]
if n... | 5,327,394 |
def list_methods(f):
"""Return a list of the multimethods currently registered to `f`.
The multimethods are returned in the order they would be tested by the dispatcher
when the generic function is called.
The return value is a list, where each item is `(callable, type_signature)`.
Each type signa... | 5,327,395 |
def load_CIFAR10(file_dir):
""" load all of cifar """
xs = []
ys = []
for filename in train_list:
file_path = os.path.join(file_dir, filename)
data, labels = load_CIFAR_batch(file_path)
xs.append(data)
ys.append(labels)
x_train = np.concatenate(xs)
y_train = np.co... | 5,327,396 |
def get_requirements(extra=None):
"""
Load the requirements for the given extra from the appropriate
requirements-extra.txt, or the main requirements.txt if no extra is
specified.
"""
filename = f"requirements-{extra}.txt" if extra else "requirements.txt"
with open(filename) as fp:
... | 5,327,397 |
def add_account_details(config):
"""add account details to config"""
# Get api client
client = get_api_client()
# Add accounts details
payload = {"length": 250, "filter": "state==VERIFIED;type!=nutanix"}
res, err = client.account.list(payload)
if err:
raise Exception("[{}] - {}".fo... | 5,327,398 |
def count_image_files(directory, montage_mode=False):
"""Counts all image files inside the directory.
If montage_mode, counts 1 level deep and returns the minimum count.
Else, counts all child images of directory.
Args:
directory (str): directory to look for child image files
montage_mo... | 5,327,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.