content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def fake_categorize_file(tmpdir_factory):
"""Creates a simple categorize for testing."""
file_name = tmpdir_factory.mktemp("data").join("categorize.nc")
root_grp = netCDF4.Dataset(file_name, "w", format="NETCDF4_CLASSIC")
n_points = 7
root_grp.createDimension('time', n_points)
var = root_grp.cre... | 29,000 |
def safe_unsigned_div(a, b, eps=None):
"""Calculates a/b with b >= 0 safely.
a: A `float` or a tensor of shape `[A1, ..., An]`, which is the nominator.
b: A `float` or a tensor of shape `[A1, ..., An]`, which is the denominator.
eps: A small `float`, to be added to the denominator. If left as `None`, it... | 29,001 |
def create_helm(ioc_dict: Dict, entity_yaml: str, path: Path):
"""
create a boilerplate helm chart with name str in folder path
update the values.yml and Chart.yml by rendering their jinja templates
and insert the boot script whose text is supplied in script_txt
"""
helm_folder = path / ioc_dic... | 29,002 |
def load_unpack_npz(path):
"""
Simple helper function to circumvent hardcoding of
keyword arguments for NumPy zip loading and saving.
This assumes that the first entry of the zipped array
contains the keys (in-order) for the rest of the array.
Parameters
----------
path : string
P... | 29,003 |
def verify(message, expected, *args, **kwargs):
"""Verify target substitutions."""
actual = command_handler._inject(
MessagePacket(
*message if isinstance(message, list) else (message,)),
*args, **kwargs
).text
assert actual == expected | 29,004 |
def is_valid_email(email):
"""
Check if a string is a valid email.
Returns a Boolean.
"""
try:
return re.match(EMAIL_RE, email) is not None
except TypeError:
return False | 29,005 |
def test_field_upload_resp_fields(datapack_tar, svc_client_with_repo):
"""Check response fields."""
svc_client, headers, project_id, _ = svc_client_with_repo
headers.pop("Content-Type")
response = svc_client.post(
"/cache.files_upload",
data=dict(file=(io.BytesIO(datapack_tar.read_bytes... | 29,006 |
def _create_matcher(utterance):
"""Create a regex that matches the utterance."""
# Split utterance into parts that are type: NORMAL, GROUP or OPTIONAL
# Pattern matches (GROUP|OPTIONAL): Change light to [the color] {name}
parts = re.split(r'({\w+}|\[[\w\s]+\] *)', utterance)
# Pattern to extract nam... | 29,007 |
def loadTrainingData(path_to_follow):
"""
It loads the images, assuming that these are in the /IMG/ subfolder.
Also, the output is in the CSV file "steering.csv".
:param path_to_follow: is the full path where the images are placed.
:return: a list with (1) a numpy array with the... | 29,008 |
def configure_logging(log_level=None, log_file=None, simplified_console_logs=False):
"""
This should be called once as early as possible in app startup to configure logging handlers and formatting.
:param log_level: The level at which to record log messages (DEBUG|INFO|NOTICE|WARNING|ERROR|CRITICAL)
:t... | 29,009 |
def top_compartment_air_CO2(setpoints: Setpoints, states: States, weather: Weather):
"""
Equation 2.13 / 8.13
cap_CO2_Top * top_CO2 = mass_CO2_flux_AirTop - mass_CO2_flux_TopOut
"""
cap_CO2_Top = Coefficients.Construction.greenhouse_height - Coefficients.Construction.air_height # Note: line 46 / se... | 29,010 |
def test_zero_indexed(bucketer, df):
"""Test that bins are zero-indexed."""
BUCK = bucketer(n_bins=3)
x_t = BUCK.fit_transform(df.drop(columns=["pet_ownership"]))
assert x_t["MARRIAGE"].min() == 0
assert x_t["EDUCATION"].min() == 0
assert x_t["LIMIT_BAL"].min() == 0
assert x_t["BILL_AMT1"].m... | 29,011 |
def coning_sculling(gyro, accel, order=1):
"""Apply coning and sculling corrections to inertial readings.
The algorithm assumes a polynomial model for the angular velocity and the
specific force, fitting coefficients by considering previous time
intervals. The algorithm for a linear approximation is we... | 29,012 |
def add():
"""Add a task.
:url: /add/
:returns: job
"""
job = scheduler.add_job(
func=task2,
trigger="interval",
seconds=10,
id="test job 2",
name="test job 2",
replace_existing=True,
)
return "%s added!" % job.name | 29,013 |
def magnitude(x: float, y: float, z: float) -> float:
""" Magnitude of x, y, z acceleration √(x²+y²+z²)
Dispatch <float>
Args:
x (float): X-axis of acceleration
y (float): Y-axis of acceleration
z (float): Z-axis of acceleration
Returns:
float: Magnitude of acceleratio... | 29,014 |
def save_images(images: List[np.array],
path: str,
name: str
) -> None:
"""
This function takes an array of np.array images, an output path
and an ID for the name generation and saves the images as png files
("$name_$index.png).
Args:
images (... | 29,015 |
def test_extract_phrase_returns_correctly(test_input_sentences, test_input_merge_inplace, test_expected):
"""Test that the extract_phrase method returns correctly."""
# Invoke the `extract_phrase` method of `ChunkParser`
test_output = ChunkParser().extract_phrase(test_input_sentences, test_input_merge_inpl... | 29,016 |
def dauth( bot, input ):
"""Toggle whether channel should be auth enabled by default"""
if not input.admin:
return False
if not input.origin[0] == ID.HON_SC_CHANNEL_MSG:
bot.reply("Run me from channel intended for the default auth!")
else:
cname = bot.id2chan[input.origin[2]]
... | 29,017 |
def write_to_disk(func):
"""
decorator used to write the data into disk during each checkpoint to help us to resume the operation
Args:
func:
Returns:
"""
def wrapper(*args, **kwargs):
func(*args, **kwargs)
with open("checkpoint.json", "r") as f:
f.write(... | 29,018 |
def _get_partition(device, uuid):
"""Find the partition of a given device."""
LOG.debug("Find the partition %(uuid)s on device %(dev)s",
{'dev': device, 'uuid': uuid})
try:
_rescan_device(device)
lsblk = utils.execute('lsblk', '-PbioKNAME,UUID,PARTUUID,TYPE', device)
r... | 29,019 |
def get_hourly_total_exchange_volume_in_period_from_db_trades(tc_db, start_time, end_time):
"""
Get the exchange volume for this exchange in this period from our saved version
of the trade history.
"""
# Watch this query for performance.
results = tc_db.query(
func.hour(EHTrade.time... | 29,020 |
def test_case_1():
"""
If we add new choice, which changes the max length, we should have a migration,
plus the column in postgres should be affected.
"""
print('Running test case 1')
database = Database()
setuper = Setuper(database, 'TEST_1')
setuper.before_setup()
assert databas... | 29,021 |
async def action(bot, msg):
"""**!dice** _dice_**d**_sides_[+|-_modifier_]
Simulate a dice roll. _Dice_ is the number of dice to roll and _sides_ is the number of sides each die has. Optionally you can specify _modifier_, prefixed with + or -.
`!dice 1d20+3`
"""
match = match_pattern.match(msg.clean_content... | 29,022 |
def descending(sorting_func: typing.Any) -> typing.Any:
"""
Modify a sorting function to sort in descending order.
:param sorting_func: the original sorting function
:return: the modified sorting function
"""
def modified_sorting_func(current_columns, original_columns, sorting_func=sorting_func... | 29,023 |
def circleColor(renderer, x, y, rad, color):
"""Draws an unfilled circle to the renderer with a given color.
If the rendering color has any transparency, blending will be enabled.
Args:
renderer (:obj:`SDL_Renderer`): The renderer to draw on.
x (int): The X coordinate of the center of the ... | 29,024 |
def _get_ref_init_error(dpde, error, **kwargs):
"""
Function that identifies where the continuous gyro begins, initiates and
then carries the static errors during the continuous modes.
"""
temp = [0.0]
for coeff, inc in zip(dpde[1:, 2], error.survey.inc_rad[1:]):
if inc > kwargs['header'... | 29,025 |
def get_free_hugepages(socket=None):
"""Get the free hugepage totals on the system.
:param socket: optional socket param to get free hugepages on a socket. To
be passed a string.
:returns: hugepage amount as int
"""
hugepage_free_re = re.compile(r'HugePages_Free:\s+(?P<free_hp>\d... | 29,026 |
def setup_logger(
log_filename: Pathlike, log_level: str = "info", use_console: bool = True
) -> None:
"""Setup log level.
Args:
log_filename:
The filename to save the log.
log_level:
The log level to use, e.g., "debug", "info", "warning", "error",
"critical"
"""
... | 29,027 |
def get_extrainfo_descriptors(start = None, end = None, cache_to = None, bridge = False, timeout = None, retries = 3):
"""
Shorthand for
:func:`~stem.descriptor.collector.CollecTor.get_extrainfo_descriptors`
on our singleton instance.
"""
for desc in get_instance().get_extrainfo_descriptors(start, end, cac... | 29,028 |
async def loop(reader: asyncio.StreamReader, writer: asyncio.StreamWriter, my_id: int):
"""The main event loop. Gets the current world and returns the decision made."""
data = await next_state(reader)
while data["state"] == "playing":
choice = decision(my_id, World(data["map"]))
writer.write... | 29,029 |
def umount(path, bg=False):
"""Umount dfuse from a given path"""
if bg:
cmd = ['fusermount3', '-uz', path]
else:
cmd = ['fusermount3', '-u', path]
ret = subprocess.run(cmd, check=False)
print('rc from umount {}'.format(ret.returncode))
return ret.returncode | 29,030 |
def assert_allclose(actual: List[int], desired: numpy.ndarray):
"""
usage.scipy: 4
usage.statsmodels: 1
"""
... | 29,031 |
def parse_internal_ballot(line):
"""
Parse an internal ballot line (with or without a trailing newline).
This function allows leading and trailing spaces. ValueError is
raised if one of the values does not parse to an integer.
An internal ballot line is a space-delimited string of integers of the... | 29,032 |
def get_fratio(*args):
"""
"""
cmtr = get_cmtr(*args)
cme = get_cme(*args)
fratio = cmtr / cme
return fratio | 29,033 |
def log_progress(is_first_update, total, current, message):
"""Log progress of the issues or PRs processing.
Args:
is_first_update (bool): This is the first update of this repo.
total (int): Number of issues/PRs.
current (int): Last processed issue/PR number.
message (str): Stri... | 29,034 |
def _select_by_property(peak_properties, pmin, pmax):
"""
Evaluate where the generic property of peaks confirms to an interval.
Parameters
----------
peak_properties : ndarray
An array with properties for each peak.
pmin : None or number or ndarray
Lower interval boundary for `p... | 29,035 |
def from_period_type_name(period_type_name: str) -> PeriodType:
"""
Safely get Period Type from its name.
:param period_type_name: Name of the period type.
:return: Period type enum.
"""
period_type_values = [item.value for item in PeriodType]
if period_type_name.lower() not in period_type_... | 29,036 |
def scale_down_all_workloads(wait_time: int):
"""Kill all workloads"""
command = "kubectl scale sts --all --replicas=0 && sleep {wait_time}".format(
wait_time=wait_time)
default_shell_run(command) | 29,037 |
def randomInt(length=4, seed=None):
"""
Returns random integer value with provided number of digits
>>> random.seed(0)
>>> randomInt(6)
874254
"""
if seed is not None:
_ = getCurrentThreadData().random
_.seed(seed)
choice = _.choice
else:
choice = random... | 29,038 |
def matchatleastone(text, regexes):
"""Returns a list of strings that match at least one of the regexes."""
finalregex = "|".join(regexes)
result = re.findall(finalregex, text)
return result | 29,039 |
def safe_string_equals(a, b):
""" Near-constant time string comparison.
Used in order to avoid timing attacks on sensitive information such
as secret keys during request verification (`rootLabs`_).
.. _`rootLabs`: http://rdist.root.org/2010/01/07/timing-independent-array-comparison/
"""
if le... | 29,040 |
def DFS_complete(g):
"""Perform DFS for entire graph and return forest as a dictionary.
forest maps each vertex v to the edge that was used to discover it.
(Vertices that are roots of a DFS tree are mapped to None.)
:param g: a Graph class object
:type g: Graph
:return: A tuple of dicts summar... | 29,041 |
def get_keys(mapping, *keys):
"""Return the values corresponding to the given keys, in order."""
return (mapping[k] for k in keys) | 29,042 |
def test_initialize_physical_parameters():
"""
Checks function SolveDiffusion2D.initialize_domain
"""
solver = SolveDiffusion2D()
w = 22.
h = 3.
dx = 0.5
dy = 0.86
solver.initialize_domain(w, h, dx, dy)
d = 7.0
solver.initialize_physical_parameters(d)
actual_dt_rounde... | 29,043 |
def accents_dewinize(text):
"""Replace Win1252 symbols with ASCII chars or sequences
needed when copying code parts from MS Office, like Word...
From the book "Fluent Python" by Luciano Ramalho (O'Reilly, 2015)
>>> accents_dewinize('“Stupid word • error inside™ ”')
'"Stupid word - error inside(TM) ... | 29,044 |
def spiral_trajectory(base_resolution,
spiral_arms,
field_of_view,
max_grad_ampl,
min_rise_time,
dwell_time,
views=1,
phases=None,
ordering='lin... | 29,045 |
def total_examples(X):
"""Counts the total number of examples of a sharded and sliced data object X."""
count = 0
for i in range(len(X)):
for j in range(len(X[i])):
count += len(X[i][j])
return count | 29,046 |
def convert_and_save(model,
input_shape,
weights=True,
quiet=True,
ignore_tests=False,
input_range=None,
filename=None,
directory=None):
"""
Conversion between PyTor... | 29,047 |
def no_afni():
""" Checks if AFNI is available """
if Info.version() is None:
return True
return False | 29,048 |
def delta_eta_plot_projection_range_string(inclusive_analysis: "correlations.Correlations") -> str:
""" Provides a string that describes the delta phi projection range for delta eta plots. """
# The limit is almost certainly a multiple of pi, so we try to express it more naturally
# as a value like pi/2 or ... | 29,049 |
def select_gpu(gpu_ids=None, gpu_mem_frac=None):
"""
Find the GPU ID with highest available memory fraction.
If ID is given as input, set the gpu_mem_frac to maximum available,
or if a memory fraction is given, make sure the given GPU has the desired
memory fraction available.
Currently only sup... | 29,050 |
def load_classification_dataset(
fname,
tokenizer,
input_field_a,
input_field_b=None,
label_field='label',
label_map=None,
limit=None
):
"""
Loads a dataset for classification
Parameters
==========
tokenizer : transformers.PretrainedTokenizer
Maps text to id tens... | 29,051 |
def test_mnist(args):
""" Calculates error rate on MNIST for a previously saved MulticlassClassifier instance.
Parameters
----------
args : argparse.Namespace
Arguments from command line.
Returns
-------
error_rate : float
The calculated error rate.
Raises
------
... | 29,052 |
def has_content_in(page, language):
"""Fitler that return ``True`` if the page has any content in a
particular language.
:param page: the current page
:param language: the language you want to look at
"""
if page is None:
return False
return Content.objects.filter(page=page, languag... | 29,053 |
def public_encrypt(key, data, oaep):
"""
public key encryption using rsa with pkcs1-oaep padding.
returns the base64-encoded encrypted data
data: the data to be encrypted, bytes
key: pem-formatted key string or bytes
oaep: whether to use oaep padding or not
"""
if isinstance(key, str):
key = key.en... | 29,054 |
def newton_method(f, x_init = 0, epsilon = 1e-10):
"""
Newton Raphson Optimizer
...
Parameters
---
f: Function to calculate root for
x_init(optional) : initial value of x
epsilon(optional): Adjustable precision
Returns
---
x: Value of root
"""
prev_value = x_init +... | 29,055 |
def create_preference_branch(this, args, callee):
"""Creates a preference branch, which can be used for testing composed
preference names."""
if args:
if args[0].is_literal:
res = this.traverser.wrap().query_interface('nsIPrefBranch')
res.hooks['preference_branch'] = args[0]... | 29,056 |
def circle(
gdf,
radius=10,
fill=True,
fill_color=None,
name="layer",
width=950,
height=550,
location=None,
color="blue",
tooltip=None,
zoom=7,
tiles="OpenStreetMap",
attr=None,
style={},
):
"""
Convert Geodataframe to geojson and plot it.
Parameters
... | 29,057 |
def draw_rectangle(turtle):
"""
This function draws the Guitar handle
:param turtle: The name of the turtle
:return: None
"""
turtle.color(139,69,19)
turtle.penup()
turtle.setpos(30, -45)
turtle.begin_fill()
turtle.pendown()
for i in range(2):
turtle.forw... | 29,058 |
def no_recurse(f):
"""Wrapper function that forces a function to return True if it recurse."""
def func(*args, **kwargs):
for i in traceback.extract_stack():
if i[2] == f.__name__:
return True
return f(*args, **kwargs)
return func | 29,059 |
def get_tap_number(distSys: SystemClass, names: List[str]) -> pandas.DataFrame:
"""
Get the tap number of regulators.
Args:
distSys : An instance of [SystemClass][dssdata.SystemClass].
names : Regulators names
Returns:
The tap number of regulators.
"""
def get_one(reg... | 29,060 |
def status(app: str) -> dict:
"""
:param app: The name of the Heroku app in which you want to change
:type app: str
:return: dictionary containing information about the app's status
"""
return Herokron(app).status() | 29,061 |
def GetIPv4Interfaces():
"""Returns a list of IPv4 interfaces."""
interfaces = sorted(netifaces.interfaces())
return [x for x in interfaces if not x.startswith('lo')] | 29,062 |
def merge_dicts(source, destination):
"""
Recursively merges two dictionaries source and destination.
The source dictionary will only be read, but the destination dictionary will be overwritten.
"""
for key, value in source.items():
if isinstance(value, dict):
# get node or creat... | 29,063 |
def format_code(session):
"""Run code reformatter"""
# session.install("-e", ".[lint]")
session.install(
"isort==4.3.21", "seed-isort-config==2.1.0", "black==19.10b0"
)
session.run("seed-isort-config", success_codes=[0, 1])
session.run("isort", "-rc", *files_to_format)
session.run("b... | 29,064 |
def create_hive_connection():
"""
Create a connection for Hive
:param username: str
:param password: str
:return: jaydebeapi.connect or None
"""
try:
conn = jaydebeapi.connect('org.apache.hive.jdbc.HiveDriver',
hive_jdbc_url,
... | 29,065 |
def main():
"""
The main function to execute upon call.
Returns
-------
int
returns integer 0 for safe executions.
"""
print('Hello World')
return 0 | 29,066 |
def brightness(image, magnitude, name=None):
"""Adjusts the `magnitude` of brightness of an `image`.
Args:
image: An int or float tensor of shape `[height, width, num_channels]`.
magnitude: A 0-D float tensor or single floating point value above 0.0.
name: An optional string for name of... | 29,067 |
def sitemap_xml():
"""Sitemap XML"""
sitemap = render_template("core/sitemap.xml")
return Response(sitemap, mimetype="text/xml") | 29,068 |
def build_editable(location, expose=None, hide=None):
"""Generate files that can be added to a wheel to expose packages from a directory.
By default, every package (directory with __init__.py) in the supplied
location will be exposed on sys.path by the generated wheel.
Optional arguments:
expose:... | 29,069 |
def get_CM():
"""Pertzの係数CMをndarrayとして取得する
Args:
Returns:
CM(ndarray[float]):Pertzの係数CM
"""
# pythonは0オリジンのため全て-1
CM = [0.385230, 0.385230, 0.385230, 0.462880, 0.317440,#1_1 => 0_0
0.338390, 0.338390, 0.221270, 0.316730, 0.503650,
0.235680, 0.235680, 0.24128... | 29,070 |
def remove_sleepEDF(mne_raw, CHANNELS):
"""Extracts CHANNELS channels from MNE_RAW data.
Args:
raw - mne data strucutre of n number of recordings and t seconds each
CHANNELS - channels wished to be extracted
Returns:
extracted - mne data structure with only specified channels
"""
extra... | 29,071 |
def zip(zipfilename, srcdirs): # , recursive=True):
"""
Last element of srcdir is considered root of zip'd content. E.g.,
srcdir="doc/Java" gives zip file with Java as the root element.
srcdir might expand to /Volumes/SSD2/Users/parrt/antlr/code/antlr4/doc/Java
"""
if isinstance(srcdirs, bases... | 29,072 |
def save_email_schedule(request, action, schedule_item, op_payload):
"""
Function to handle the creation and edition of email items
:param request: Http request being processed
:param action: Action item related to the schedule
:param schedule_item: Schedule item or None if it is new
:param op_p... | 29,073 |
def MutipleClouds_LOS_example():
"""Example spectrum from a LOS of multiple clouds"""
# Define input wavenelgth array
wavelength_array = WavelengthArray(1000,1560,7.5)
# All physical parameters become arrays
lognHs = [-4,-4.1,-3.6]
logZs = [0, 0, 0]
logTs = [4.3,4.2,4.0]
# The... | 29,074 |
def show_colored_canvas(color):
"""Show a transient VisPy canvas with a uniform background color."""
from vispy import app, gloo
c = app.Canvas()
@c.connect
def on_draw(e):
gloo.clear(color)
show_test(c) | 29,075 |
def slice(
_data: DataFrame,
*rows: NumericOrIter,
_preserve: bool = False,
base0_: bool = None,
) -> DataFrame:
"""Index rows by their (integer) locations
Original APIs https://dplyr.tidyverse.org/reference/slice.html
Args:
_data: The dataframe
rows: The indexes
... | 29,076 |
def get_random_color():
"""
Get random color
:return: np.array([r,g,b])
"""
global _start_color, _color_step
# rgb = np.random.uniform(0, 25, [3])
# rgb = np.asarray(np.floor(rgb) / 24 * 255, np.uint8)
_start_color = (_start_color + _color_step) % np.array([256, 256, 256])
rgb = np.a... | 29,077 |
def test_del_list() -> None:
"""Remove element(s) from a list."""
nums: List[int] = [1, 2, 3, 4, 5]
del nums[0]
assert nums == [2, 3, 4, 5]
del nums[1:3]
assert nums == [2, 5]
del nums[:]
assert nums == []
# Delete entire variable
del nums | 29,078 |
async def test_delete_start_entry_not_found(
event_loop: Any,
mocker: MockFixture,
start_entry_mock: dict,
) -> None:
"""Should raise StartEntryNotFoundException."""
mocker.patch(
"race_service.adapters.start_entries_adapter.StartEntriesAdapter.get_start_entry_by_id",
return_value=No... | 29,079 |
def test_handler_issue_pr_mentioned(monkeypatch):
""" handler_issue_pr_mentioned にサンプル入力を入れて動作確認 """
mentioned_header_path = SCRIPT_PATH.parent / "testdata/mentioned-header.json"
mentioned_body_path = SCRIPT_PATH.parent / "testdata/mentioned-body.json"
header = json.loads(mentioned_header_path.read_text... | 29,080 |
def CNN2d(CNN=None, second=10, saveable=True, name='cnn', fig_idx=3119362):
"""Display a group of RGB or Greyscale CNN masks.
Parameters
----------
CNN : numpy.array
The image. e.g: 64 5x5 RGB images can be (5, 5, 3, 64).
second : int
The display second(s) for the image(s), if savea... | 29,081 |
def get_client_ip(request):
"""
Simple function to return IP address of client
:param request:
:return:
"""
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0] # pylint: disable=invalid-name
else:
ip = reque... | 29,082 |
def entropy(wair,temp,pres,airf=None,dhum=None,dliq=None,chkvals=False,
chktol=_CHKTOL,airf0=None,dhum0=None,dliq0=None,chkbnd=False,
mathargs=None):
"""Calculate wet air entropy.
Calculate the specific entropy of wet air.
:arg float wair: Total dry air fraction in kg/kg.
:arg float te... | 29,083 |
def get_list_item(view, index):
"""
get item from listView by index
version 1
:param view:
:param index:
:return:
"""
return var_cache['proxy'].get_list_item(view, index) | 29,084 |
def test_update_user_ensures_request_data_id_matches_resource_id(client, auth):
"""If request data contains an (optional) "id" then it has to match the resource id."""
auth.login()
assert client.put("/api/users/{}".format(auth.id), headers=auth.headers, json={"id": auth.id, "name": "??", "password": "????"}... | 29,085 |
def interquartile_range_checker(train_user: list) -> float:
"""
Optional method: interquatile range
input : list of total user in float
output : low limit of input in float
this method can be used to check whether some data is outlier or not
>>> interquartile_range_checker([1,2,3,4,5,6,7,8... | 29,086 |
def pause(args):
"""Pause all the swift services.
@raises Exception if any services fail to stop
"""
for service in args.services:
stopped = service_pause(service)
if not stopped:
raise Exception("{} didn't stop cleanly.".format(service))
with HookData()():
kv().... | 29,087 |
def make_linear_colorscale(colors):
"""
Makes a list of colors into a colorscale-acceptable form
For documentation regarding to the form of the output, see
https://plot.ly/python/reference/#mesh3d-colorscale
"""
scale = 1.0 / (len(colors) - 1)
return [[i * scale, color] for i, color in enum... | 29,088 |
def background(image_size: int, level: float=0, grad_i: float=0, grad_d: float=0) -> np.array:
"""
Return array representing image background of size `image_size`.
The image may have an illimination gradient of intensity `I` and direction `grad_d`.
The `image_size` is in pixels. `grad_i` expected to be ... | 29,089 |
def _warn_if_uri_clash_on_same_marshaled_representation(uri_schema_mappings, marshal_uri):
"""
Verifies that all the uris present on the definitions are represented by a different marshaled uri.
If is not the case a warning will filed.
In case of presence of warning please keep us informed about the is... | 29,090 |
def mapTypeCategoriesToSubnetName(nodetypecategory, acceptedtypecategory):
"""This function returns a name of the subnet that accepts nodetypecategory
as child type and can be created in a container whose child type is
acceptedtypecategory.
Returns None if these two categories are the same (i... | 29,091 |
def sorted_unique(series):
"""Return the unique values of *series*, correctly sorted."""
# This handles Categorical data types, which sorted(series.unique()) fails
# on. series.drop_duplicates() is slower than Series(series.unique()).
return list(pd.Series(series.unique()).sort_values()) | 29,092 |
def create_query_from_request(p, request):
"""
Create JSON object representing the query from request received from Dashboard.
:param request:
:return:
"""
query_json = {'process_type': DVAPQL.QUERY}
count = request.POST.get('count')
generate_tags = request.POST.get('generate_tags')
... | 29,093 |
def create_cxr_transforms_from_config(config: CfgNode,
apply_augmentations: bool) -> ImageTransformationPipeline:
"""
Defines the image transformations pipeline used in Chest-Xray datasets. Can be used for other types of
images data, type of augmentations to use and str... | 29,094 |
def is_compiled_with_npu():
"""
Whether paddle was built with WITH_ASCEND_CL=ON to support Ascend NPU.
Returns (bool): `True` if NPU is supported, otherwise `False`.
Examples:
.. code-block:: python
import paddle
support_npu = paddle.device.is_compiled_with_npu()
"... | 29,095 |
def odd_occurrence_parity_set(arr):
"""
A similar implementation to the XOR idea above, but more naive.
As we iterate over the passed list, a working set keeps track of
the numbers that have occurred an odd number of times.
At the end, the set will only contain one number.
Though th... | 29,096 |
def write_directory_status(directory_status, run_id=None):
"""
Writes a status to the status file:
Overwrites anything that is in the file
Writes a timestamp to the time of last written
:param directory_status: DirectoryStatus object containing status to write to directory
:param run_id: optio... | 29,097 |
def larmor_step_search(step_search_center=cfg.LARMOR_FREQ, steps=200, step_bw_MHz=5e-3, plot=False,
shim_x=cfg.SHIM_X, shim_y=cfg.SHIM_Y, shim_z=cfg.SHIM_Z, delay_s=1, gui_test=False):
"""
Run a stepped search through a range of frequencies to find the highest signal response
Used to find a starting po... | 29,098 |
def get_role_tempalte(context: Optional[str] = None,
name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetRoleTempalteResult:
"""
Use this data source to access information about an existing resource.
"""
pulumi.log.warn("""g... | 29,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.