content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_deleting_inexistant_component(tmp_path: P):
"""
Trying to delete a component that does not exist results in a non-0 exit
code.
"""
setup_directory(tmp_path)
component_name = "i-dont-exist"
exit_status = call(
f"commodore -d {tmp_path} -vvv component delete --force {componen... | 74,900 |
def get_database_output(instance_id: Optional[pulumi.Input[str]] = None,
name: Optional[pulumi.Input[str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetDatabaseResult]:
"""
Gets information about a RDB database.
## Example Usage
... | 74,901 |
def draw_self_loop(
point: np.array,
ax: Optional[plt.Axes] = None,
padding: float = 1.5,
width: float = 0.3,
plot_size: int = 10,
linewidth: float = 0.2,
color: str = "pink",
) -> plt.Axes:
"""Draw a loop from `point` to itself
!Important! By "center" we assume a (0, 0) point. If y... | 74,902 |
def verify_arguments(target, method_name, args, kwargs):
"""Verifies that the provided arguments match the signature of the provided method.
:param Target target: A ``Target`` object containing the object with the method to double.
:param str method_name: The name of the method to double.
:param tuple ... | 74,903 |
def mock_query_classes(monkeypatch):
"""Monkeypatch query classes for testing."""
from rptk import RptkAPI
from rptk.query import BaseQuery
class _MockQuery(BaseQuery):
def query(self, *objects):
objects = super(self.__class__, self).query(*objects)
result = dict()
... | 74,904 |
def _get_routine_reference(self, routine_id):
"""Constructs a RoutineReference.
Args:
routine_id (str): the ID of the routine.
Returns:
google.cloud.bigquery.routine.RoutineReference:
A RoutineReference for a routine in this dataset.
"""
return RoutineReference.from_api... | 74,905 |
def reply_to_all_posts():
"""
Replies in rickroll to all possible comments which match criteria
"""
for post in subreddit.hot(limit=5):
if check_if_app_suggestion_needed(post.selftext.lower()):
post.reply(generate_message())
print("Replied to https://www.reddit.com" + pos... | 74,906 |
def file(file_path: str) -> File:
"""
Returns a File object for a specified file path.
:param file_path:
:return File: a ReadableFile or ConvertibleFile object.
"""
if not is_found(file_path):
raise FileNotFoundError(file_path)
elif check_ext(file_path, Extensions.HISTOGRAM) and is... | 74,907 |
def get_bias_offset(nnet):
"""
returns the offset to balance the polynomial parameters possible by the bias
terms of the network.
"""
offset = 0
L = len(nnet.trainable_layers)
for l in range(L-1):
layer = nnet.trainable_layers[l]
if layer.b is not None:
W_prod ... | 74,908 |
def export_liaison(request):
"""导出所有联系人信息"""
response = HttpResponse(content_type='application/ms-excel')
response['Content-Disposition'] = 'attachment; filename="liaison.xls"'
# 创建一个workbook,设置编码
wb = xlwt.Workbook(encoding='utf-8')
# 创建一个worksheet,对应excel中的sheet,表名称
ws = wb.add_shee... | 74,909 |
def get_percentage(df, filename=None, dropna=True):
"""
Normalise results to be plotted
"""
if len(df.columns) > 1 and len(df.index) > 1:
by_row, by_col = True, False
else:
by_row, by_col = True, True
if dropna is True:
# get nan Percentage
# 'Percentage NaN'
... | 74,910 |
def third_octaves(p, fs, density=False,
frequencies=NOMINAL_THIRD_OCTAVE_CENTER_FREQUENCIES,
ref=REFERENCE_PRESSURE):
"""Calculate level per 1/3-octave in frequency domain using the FFT.
:param x: Instantaneous signal :math:`x(t)`.
:param fs: Sample frequency.
:param... | 74,911 |
def convert_to_one_hot(
targets: torch.Tensor,
num_class: int,
label_smooth: float = 0.0,
) -> torch.Tensor:
"""
This function converts target class indices to one-hot vectors, given the number of classes.
Args:
targets (torch.Tensor): Index labels to be converted.
num_class (in... | 74,912 |
def close_conn():
"""
Closes database connection
"""
if conn is not None:
conn.close()
print('Database connection closed') | 74,913 |
def temperature(
fire_time,
fire_temperature,
beam_rho,
beam_cross_section_area,
protection_k,
protection_rho,
protection_c,
protection_thickness,
protection_protected_perimeter,
terminate_when_cooling=False,
terminate_max_temperatu... | 74,914 |
def flow_schema(dps):
"""Return schema used in config flow."""
return {
vol.Optional(CONF_FAN_SPEED_CONTROL): vol.In(dps),
vol.Optional(CONF_FAN_OSCILLATING_CONTROL): vol.In(dps),
vol.Optional(CONF_FAN_DIRECTION): vol.In(dps),
vol.Optional(CONF_FAN_DIRECTION_FWD, default="forward... | 74,915 |
def fast_rcnn_inference_single_image(
boxes,
scores,
image_shape: Tuple[int, int],
score_thresh: float,
nms_thresh: float,
topk_per_image: int,
aps_thresh: float,
):
"""
Single-image inference. Return bounding-box detection results by thresholding
on scores and applying non-maxim... | 74,916 |
def make_feasible_supervisor(plant_fname, sup_fname, feas_fname):
"""
Construct a supervisor containing observable transitions and non-observable
self-loops.
@param plant_fname: Filename of the plant automaton.
@type plant_fname: C{str}
@param sup_fname: Filename of the supervisor.
@type ... | 74,917 |
async def test_internal_session(event_loop, aresponses):
"""Test JSON response is handled correctly."""
aresponses.add(
"example.com:3000",
"/",
"GET",
aresponses.Response(
status=200,
headers={"Content-Type": "application/json"},
text='{"statu... | 74,918 |
def parse_config(data, tag='!ENV'):
"""
https://medium.com/swlh/python-yaml-configuration-with-environment-variables-parsing-77930f4273ac
Load a yaml configuration file and resolve any environment variables
The environment variables must have !ENV before them and be in this format
to be parsed: ${V... | 74,919 |
async def test_setup_tracker(opp, opp_admin_user):
"""Test set up person with one device tracker."""
opp.state = CoreState.not_running
user_id = opp_admin_user.id
config = {
DOMAIN: {
"id": "1234",
"name": "tracked person",
"user_id": user_id,
"dev... | 74,920 |
def StrSubstr(start_idx, count, initial_string):
"""
Create a concrete version of the substring
:param start_idx : starting index of the substring
:param end_idx : last index of the substring
:param initial_string
:return : a concrete version of the substring
"""
new_value = initial_str... | 74,921 |
def plot_value_counts(df, col, condition=False):
"""Plot value counts of a column, optionally with only the heads of a household"""
# apply condition here if required
if condition:
# define condition below <>
df = df.loc[df[col] == condition].copy()
plt.figure(figsize = (8, 6))
... | 74,922 |
def delete_segment(seq, start, end):
"""Return the sequence with deleted segment from ``start`` to ``end``."""
return seq[:start] + seq[end:] | 74,923 |
def placeNodesInLevels(nodes, edge_function):
"""Given a node "N" and an edge function, divide nodes into a sequence of groups
so that nodes never flow into their own group or an ealier group. Throw
if this has a cycle
"""
all_nodes = findAllNodes(nodes, edge_function)
reverse_edges = {c: set()... | 74,924 |
def voronoi_coloring(
points: List[complex],
centers: List[complex],
colors: List[Color]) -> Frame:
"""Convert the list of complex points to color output frame.
Args:
points (List[complex]): Input "image".
centers (List[complex]): Region centers to compare to.
co... | 74,925 |
def plot_children(df):
""" Plots number of children per person as a histogram. """
sns.histplot(df.children,
kde=False,
bins=list(range(0, 10, 1)),
color="darkorchid")
plt.title("Children Distribution", y=1.05, fontsize=15)
plt.xlabel("Children", label... | 74,926 |
def get_directions(i0, i1, i2, i3):
""" get list of directions in a certain sequence """
return [directions_list[i0], directions_list[i1], directions_list[i2], directions_list[i3]] | 74,927 |
def press_valve_route(action):
"""Route for press valve
Arguments:
action {string} -- Define the state change for the LOX and FUEL
Returns:
string -- Returns the valve controllers message
"""
if ser.is_open == True:
if action == 'FUEL-PRESS-OPEN':
ser.write(b'O1\n')
message = ser... | 74,928 |
def triangleSum(n):
"""
Finding the sum of 1+2+...+n
:param n: the last interger to be added
:return: the sum
"""
n = math.floor(n)
if n > 1 :
return n+triangleSum(n-1)
return 1 | 74,929 |
def replace_database_in_url(db_url: str, db_name: str) -> str:
"""
replaces the database portion of a database connection URL with db_name
@param db_name database name to replace with
"""
db_url_parsed = urlparse(db_url)
db_url_parsed = db_url_parsed._replace(path=f"/{db_name}")
return db... | 74,930 |
def main(connection, info, args, world) :
"""Decides heads or tails based on the coinchance variable. Adds or removes appropriate amount of money"""
money = shelve.open("money-%s.db" % (connection.networkname), writeback=True)
if money.has_key(info["sender"]) :
bet = int(args[1])
if bet <=... | 74,931 |
def main( argv ):
"""
Parses the supplied command line arguments and renders IWP data as on-disk
images for labeling via an external tool.
See print_usage() for details on execution and command line arguments.
Takes 1 argument:
argv - List of command line arguments and options, including th... | 74,932 |
def detect_arxiv(txt):
"""
Extract an arXiv ID from text data
"""
regex = r'arXiv:[0-9]{4,4}\.[0-9]{5,5}(v[0-9]+)?'
m = re.search(regex, txt)
if m is not None:
return m.group(0)
else:
return None | 74,933 |
async def get_contributor_by_username(
*,
username: str,
session: Session = Depends(dal.get_session)
) -> contributor_schemas.Details:
""" Get contributor record from DB """
conditions = and_(
User.username == username,
)
db_contributor = contributor_ops.query_contributors_by_(
... | 74,934 |
def display(image, title=' ', resolution=(960, 540)):
"""Uses cv2 to display an image then wait for a button press
pts is either None or an integer specifying the number of point
and click events you'd like to capture"""
cv2.namedWindow(title, cv2.WINDOW_KEEPRATIO)
cv2.resizeWindow(title, *... | 74,935 |
def test_str_to_seconds():
"""
Test procedure for get_hours
"""
print('Testing str_to_seconds')
# Put your tests below this line
result = funcs.str_to_seconds('00:00:00')
introcs.assert_equals(0,result)
result = funcs.str_to_seconds('00:00:59')
introcs.assert_equals(59,result)
... | 74,936 |
def test_binary_operator_expression():
"""
Test parsing binary-operator expressions
"""
reset_counter()
for ws, ws_sep in iter_whitespace():
for op1 in 'b2':
for op2 in 'c3':
for binop in [' + ', ' - ', ' * ', ' / ', ' // ', ' ^ ', ' % ',
'... | 74,937 |
def get_current_dir_path():
"""获取当前执行文件的目录路径"""
return Path(sys.argv[0]).parent if is_exe() else "{}".format(os.getcwd()) | 74,938 |
def get_narrative_cell_counts(wsadmin, narrative_ref):
"""
Gets the number of App Cells and Code Cells in the narrative
See documentation for WS administer here
https://github.com/kbase/workspace_deluxe/blob/02217e4d63da8442d9eed6611aaa790f173de58e/docsource/administrationinterface.rst
"""
app_c... | 74,939 |
def calculate_emotions(labeled_emotions, labeled_intensities):
"""
Calculate the emotions that are present in each sentence taking into consideration the values given
by the different annotators.
Args:
labeled_emotions (np.ndarray): Emotions labeled as list of string numbers.
labeled_int... | 74,940 |
def xiang_dsp_kernel(X: ndarray, y: ndarray) -> Tuple[ndarray, ndarray, ndarray, ndarray]:
"""dsp algorihtm based on paper[1].
Parameters
----------
X : ndarray
EEG data assuming removing mean, shape (n_trials, n_channels, n_samples)
y : ndarray
labels, shape (n_trials, )
R... | 74,941 |
def test_market_provider_epics_list(config, make_broker):
"""
Test the MarketProvider configured to fetch markets from an epics list
"""
# Configure TradingBot to use an epic list
config["general"]["market_source"]["value"] = "list"
config["general"]["epic_ids_filepath"] = "test/test_data/epics_... | 74,942 |
def get_free_remote_ports(count: int, node: Node) -> List[int]:
"""Returns several free remote ports.
See :func:`.get_free_remote_port`.
:param count: Free port count.
:param node: Node to find a port on.
"""
result = {get_free_remote_port(node=node) for _ in range(count)}
... | 74,943 |
def precipitation():
"""Return dictionary using date as the key and prcp as the value."""
# Create our session (link) from Python to the database
session = Session(engine)
# Query all prcp and dates
results = session.query(Measurement.prcp, Measurement.date).all()
# Close out our link
... | 74,944 |
def check_and_copy_tables(project_id, dataset_id):
"""
Will check that all the required tables exist and if not, they will be created
or copied from another table.
:param project_id: Project where the dataset resides
:param dataset_id: Dataset where the required lab table needs to be created
:r... | 74,945 |
def canonical_source(spec, filter_multimethods=True, source=None):
"""Get canonical source for a spec's package.py by unparsing its AST.
Arguments:
filter_multimethods (bool): By default, filter multimethods out of the
AST if they are known statically to be unused. Supply False to disable.
... | 74,946 |
def pointsEqual(a, b):
"""
checks if 2 [x, y] points are equal
"""
for i in range(0, len(a)):
if a[i] != b[i]:
return False
return True | 74,947 |
def move(directions):
"""Meh
>>> move(parse_directions(EXAMPLE))
[100 10] [10 1]
[100 10] [10 4]
[170 38] [10 4]
[170 38] [ 4 -10]
[214 -72] [ 4 -10]
286
"""
wpt = np.array((10, 1), dtype=int)
pos = np.array((0, 0), dtype=int)
for where, count in directions:
... | 74,948 |
def test_constrained_layout19():
"""Test twiny"""
fig, ax = plt.subplots(constrained_layout=True)
ax2 = ax.twiny()
example_plot(ax)
example_plot(ax2, fontsize=24)
ax2.set_title('')
ax.set_title('')
fig.canvas.draw()
assert all(ax.get_position().extents == ax2.get_position().... | 74,949 |
def _choose_convolve(z_i, ds):
"""Choose between _dense_convolve and _sparse_convolve with a heuristic
on the sparsity of z_i, and perform the convolution.
z_i : array, shape(n_atoms, n_times_valid)
Activations
ds : array, shape(n_atoms, n_times_atom)
Dictionary
"""
assert z_i.s... | 74,950 |
def find_and_test_all(root_dir: Path, file_templates: Sequence,
timeout: Optional[float] = None) -> bool:
"""Run standard sanity tests on all files.
Args:
root_dir: Find all files that satisfy the template in this directory.
file_tempaltes: A list of templates that we tell... | 74,951 |
def healthy2_check_in(token, custom_id, post_dict):
"""
第二类健康打卡
:param token: 用户令牌
:param custom_id: 健康打卡id
:param post_dict: 健康打卡数据
:return:
"""
if not post_dict.get("whereabouts"):
errmsg = f"完美校园第二类健康打卡方式错误,请选第一类健康打卡"
log.warning(errmsg)
return {'status': 0, 'e... | 74,952 |
def app(monkeypatch, tmpdir):
"""
Sets environment variables before importing the app.
"""
monkeypatch.setenv("DTALEDESKTOP_ROOT_DIR", tmpdir.strpath)
from dtale_desktop import app
return app | 74,953 |
async def remove_subscriber(request):
"""Handler to remove subscriber."""
subscribers = request.app['subscribers']
subscriber_id = (request.match_info['subscriber_id'])
_logger.debug('API: DELETE /subscribers/{}'.format(subscriber_id))
# Check if subscriber is already present
if subscribers.is... | 74,954 |
def allowed_file(filename):
"""
Return true if a file is allowed.
Args:
filename: (str): write your description
"""
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS | 74,955 |
def refine(window_priors, window_info, null_variance=0.42 ** 2, cs_val=0.95,
cs_merge_buffer=200000, cov_df=None, jac_cutoff=0.8):
"""
Refines a set of windows given their prior probability and effect size estimates
Inputs:
window_priors : dict of windows with prior probabilities
... | 74,956 |
def signup(request, template='signup.html', login_url=''):
"""
Processes original signup to create a user on the site
once validated successfully logs the user in and redirects to default user page
"""
response_dict = {}
response_dict['error_message'] = ''
response_dict['debug'] = 'yes'
... | 74,957 |
def test_list_researchusers_not_in_proj_by_researchuser(client):
"""Researchuser in not project should not be able to list researchusers"""
token = tests.UserAuth(tests.USER_CREDENTIALS["researchuser2"]).token(client)
response = client.get(tests.DDSEndpoint.LIST_PROJ_USERS, query_string=proj_query, headers... | 74,958 |
def get_google_client(credentials_file):
"""
Return this module's Google API client, creating a connection is one
does not already exist.
"""
global _client
if not _client:
# Connecting to google's API
logger.info("Connecting to Google API using credentials file {}".format(creden... | 74,959 |
def cut_sentences(text):
"""
将文本切成句子
:param text: 待切分文本
:return: 句子列表
"""
text = text.translate(str.maketrans('!?!?\r\n', '。。。。 '))
return [sen for sen in text.split('。') if len(sen.strip()) > 1] | 74,960 |
def _setup_conduction_constants(rr, ht_consts):
"""Set up numpy arrays to accelerate conduction calculation
Notes
-----
Creates dictionary attribute "_cond" which has keys "adj"
and "const". Usage is as follows:
dT_conduction = (self._cond['const']
* (self.temp['coolant_in... | 74,961 |
def full_justify(*args, **kwargs):
"""
Usage: $full_justify(<text>)
Returns <text> filling up screen width by adding extra space.
"""
if args:
return base_justify(args[0], align='f')
return "" | 74,962 |
def fetch_ranks_from_azureml():
"""Look up distributed arguments from Azure ML environment variables.
Assumes OpenMPI image.
Note:
Sets up NCCL environment variables used by Azure ML:
- NCCL_SOCKET_IFNAME
- NCCL_IB_DISABLE
"""
ranks = DistributedTrainingArguments()
ran... | 74,963 |
def translation(translation):
""" Construct a homogeneous 2D translation matrix.
# Arguments
translation: the translation 2D vector
# Returns
the translation matrix as 3 by 3 numpy array
"""
return np.array([
[1, 0, translation[0]],
[0, 1, translation[1]],
[0,... | 74,964 |
def get_pairs(self, data, linked_clusters):
"""
Return pairs of linked clusters and establish which can be merged and which
cannot
"""
_linked_clusters = [_cluster.antecessor for _cluster in linked_clusters]
pairs = [pair for pair in itertools.combinations(_linked_clusters, r=2)]
do_not_me... | 74,965 |
def list_files(directory, reverse_sort=False, smart_sort=None, relative=False,
extension=None):
"""
Returns all the files from a directory.
Can set the filetype using extension.
Parameters
----------
directory : str
Filepath pointing to the directory with th... | 74,966 |
def SubjectArgs(*args, **kwargs):
"""
Decorator that overrides the default arguments to the subject
initialiser.
:param args: The positional arguments to the subject initialiser.
:param kwargs: The keyword arguments to the subject initialiser.
"""
def applicator(method):
... | 74,967 |
def compensate(count=5):
"""take ``count`` measurements, then average them together """
for i, vector in enumerate(vectors):
idle_vectors[i] = 0
for _ in range(count):
result = struct.unpack(
"h",
tpad.measure_adc(vector.toggle, vector.polarity)
... | 74,968 |
def convert_words_to_chars(tokens: list) -> list:
"""
:param tokens:
:return:
"""
return list(set(chain.from_iterable(tokens))) | 74,969 |
def create(file_path):
"""Create a default .sciunit config file if one does not already exist."""
if os.path.exists(file_path):
raise IOError("There is already a configuration file at %s" %
file_path)
with open(file_path, 'w') as f:
config = configparser.ConfigParser()
... | 74,970 |
def handler_supports_service(handler, service=None):
""" Convenience method to check whether or not a handler supports a service.
"""
if isinstance(handler.service, basestring):
return handler.service.upper() == service
else:
return service in handler.service | 74,971 |
def test_upgrade_db_7_to_8(user_data_dir):
"""Test upgrading the DB from version 7 to version 8.
Test that the SAI to DAI upgrade and renaming is done succesfully.
"""
msg_aggregator = MessagesAggregator()
_use_prepared_db(user_data_dir, 'v7_rotkehlchen.db')
db = _init_db_with_target_version(
... | 74,972 |
def add_text_in_group(dwg, elem, x, y, text, **kwargs):
"""
Add the text to the elem within a group. This allows text rotations to work smoothly
"""
grp = elem.add(dwg.g(transform=f"translate({rnd(x)}, {rnd(y)})"))
grp.add(dwg.text(text, **kwargs)) | 74,973 |
def bind_int(stmt, parno, data):
"""
See bind_blob for description
"""
stmt.errhandler(_dll.sqlite3_bind_int(stmt._stmtpointer, parno, c_int(data))) | 74,974 |
def solution(input_str):
""" Solution to the problem """
inputstr = str(input_str)
rotated = inputstr+inputstr[0]
result = reduce(reducer, zip(rotated, rotated[1:]), 0)
return result | 74,975 |
def weather_history(): # ANCHOR
"""shows 5 days weather history of selected location"""
api_request_city = requests.get("https://api.openweathermap.org/data/2.5/weather?q="
+ city_name.get() + "&units=metric&appid="+api_key)
api_city = json.loads(api_request_city.con... | 74,976 |
def create_nerf(args):
"""Instantiate NeRF's MLP model."""
embed_fn, input_ch = get_embedder(args.multires, args.i_embed)
input_ch_views = 0
embeddirs_fn = None
if args.use_viewdirs:
embeddirs_fn, input_ch_views = get_embedder(
args.multires_views, args.i_embed)
output_ch =... | 74,977 |
def test_put():
"""### Content
* Put an image to another image.
### Comment.
Consider the situation where simply you would like to display an image,
with the background.
"""
from fairyimage import make_logo, put
from PIL import Image
logo = make_logo("Hello")
background = Image... | 74,978 |
def get_persona_page(persona):
"""Obtains the html of the page for `peronsa`."""
# using firefox-geckodriver
driver = webdriver.Firefox()
# Persona 5 Royal Fusion Calculator website
driver.get(
"https://chinhodado.github.io/persona5_calculator/indexRoyal.html#/list")
searchbox = driver.f... | 74,979 |
def parse_signature_file(sig_file):
"""
Parses signatures from a file of signatures
:param sig_file: file-like object to pares
:return: list of signatures
"""
res = []
part_sig = ""
for signature in sig_file:
signature = part_sig + signature
part_sig = ""
if not s... | 74,980 |
def single_format(func):
"""Manage format of dhcp response
"""
@functools.wraps(func)
def formatter(*args, **kwargs):
iface = args[0]
ans = func(*args, **kwargs)
#scapy stores all sequence of requests
#so ans[0][1] would be response to first request
return [format... | 74,981 |
def to_literal(typ, always_tuple=False):
"""Convert a typestruct item to a simplified form for ease of use."""
def expand(params):
return (to_literal(x) for x in params)
def union(params):
ret = tuple(sorted(expand(params), key=str))
if len(ret) == 1 and not always_tuple:
ret, = ret # pylint:... | 74,982 |
def powmod(a, b, m):
""" Returns the power a**b % m """
# a^(2b) = (a^b)^2
# a^(2b+1) = a * (a^b)^2
if b==0:
return 1
return ((a if b%2==1 else 1) * powmod(a, b//2, m)**2) % m | 74,983 |
def test_module(client: Client) -> str:
"""
If a client was made then an accesses token was successfully reached,
therefore the username and password are valid and a connection was made
additionally, checks if not using all the optional quota
:param client: the client object with an access token
... | 74,984 |
def str_to_array(s):
"""
Simplistic converter of strings from repr to float NumPy arrays.
If the repr representation has ellipsis in it, then this will fail.
Parameters
----------
s : str
The repr version of a NumPy array.
Examples
--------
>>> s = "array([ 0.3, inf, nan... | 74,985 |
def check_cores(func):
"""
Checks how many cores the search has been configured to
use and then returns None instead of calling the pool
creation function in the case that only one core has
been set.
Parameters
----------
func
A function that creates a pool
Retu... | 74,986 |
def get_potential_versions(servicename, **_):
"""
List the different versions of a service stored in the system
Variables:
servicename => Name of the service to get the versions
Arguments:
None
Data Block:
None
Result example:
['3.1.0', '3.2.0', '3.3.0', '4.0.0', ...] ... | 74,987 |
def generate_decorator(exception):
"""Ddecorator generator"""
def expected_error(test):
@functools.wraps(test)
def inner(*args, **kwargs):
try:
test(*args, **kwargs)
except exception:
assert True
else:
raise Asse... | 74,988 |
def __refresh() -> None:
"""
刷新 车票session
:return:
"""
http_session = session()
http_session.headers = {'user-agent': get_user_agent()}
url = 'http://nfuedu.zftcloud.com/campusbus_index/ticket_checked/index'
params = {
'school_code': 11557,
'alipay_user_id': g.bus_user.al... | 74,989 |
def app_env():
"""
Create a dict of environment variables.
Mirrors the testing environment for use in subprocesses.
"""
return {
'DB_HOST': TEST_DATABASE_CONFIG.host,
'DB_PORT': str(TEST_DATABASE_CONFIG.port),
'DB_NAME': TEST_DATABASE_CONFIG.name,
'DB_USER': TEST_DAT... | 74,990 |
def json_dump(data, filename):
"""
Dump `FontManager` *data* as JSON to the file named *filename*.
Notes
-----
File paths that are children of the Matplotlib data path (typically, fonts
shipped with Matplotlib) are stored relative to that data path (to remain
valid across virtualenvs).
... | 74,991 |
async def send_report(bot: Bot, event: Event, contents: str) -> None:
"""
发送反馈报告。
参数:
- `bot: nonebot.adapter.cqhttp.Bot`:Bot 对象。
- `event: nonebot.adapter.cqhttp.Event`:上报事件。
- `contents: str`:反馈内容。
"""
info = await _get_feedback_info(bot, event)
report = ''.join([
'收到一则用户... | 74,992 |
def determine_key_type(bucket, key, profile):
"""Return values : 'File', 'Folder' or 'Does not exist'"""
if profile:
s3 = boto3.session(profile_name=profile).client('s3')
else:
s3 = boto3.client('s3')
if not key:
raise Exception("Cannot determine key type - no key is specified")
... | 74,993 |
def correct_brenda_dtypes(r: pd.DataFrame):
"""Make sure the columns have the right dtypes.
:param r: dataframe of reports
"""
df_out = r.copy()
float_cols = ["ph", "mols", "temperature", "km", "kcat"]
for col in float_cols:
if col in r.columns:
df_out[col] = r[col].astype(f... | 74,994 |
def vmtkmarchingcubes(image, level=0.0):
"""Generate an isosurface of given level from a 3D image.
Args:
image: vtkImageData object.
level: Graylevel at which to generate the isosurface.
Returns:
Surface mesh of the isosurface.
"""
marcher = vmtkscripts.vmtkMarc... | 74,995 |
def pipe(bot, msg):
"""Pipe the output of a command to the input of the next command."""
commands = filter(None, [s.strip() for s in msg.match.group(1).split('|')])
stream = ''
for command in commands:
if stream:
command += ' ' + stream
try:
stream = run_command(c... | 74,996 |
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the g... | 74,997 |
def _update_dict(d, **kwargs):
"""little helper to modify and return a dict in one line"""
d.update(kwargs)
return d | 74,998 |
def configure_task_generator(ctx, target, kw):
"""
Helper function to apply default configurations and to set platform/configuration dependent settings
* Fork of ConfigureTaskGenerator
"""
# Ensure we have a name for lookup purposes
kw.setdefault('name', target)
# Lookup the PlatformConfig... | 74,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.