content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def swipe_left(times='1', start=None):
"""Swipes left on the screen.
Examples
--------
.. code-block:: robotframework
SwipeLeft # Swipes left once
SwipeLeft 5 # Swipes left five times
SwipeLeft 1 Qentinel Touch # Swipes left once, from the text "Qentinel Touch"
... | 5,334,700 |
def main():
"""main function"""
input_path = str(pathlib.Path(__file__).resolve().parent.parent) + "/inputs/" + str(pathlib.Path(__file__).stem)
start_time = time.time()
input_data = read_input(input_path)
entries = extract(input_data)
valid_tickets, invalid_fields_sum = part1(entries)
print... | 5,334,701 |
def sourceExtractImage(data, bkgArr=None, sortType='centre', verbose=False,
**kwargs):
"""Extract sources from data array and return enumerated objects sorted
smallest to largest, and the segmentation map provided by source extractor
"""
data = np.array(data).byteswap().newbyteord... | 5,334,702 |
def test_malformed_destinations():
"""WALE_SYSLOG_FACILITY contains bogus values"""
os.environ['WALE_SYSLOG_FACILITY'] = 'wat'
out, valid_facility = log_help.get_syslog_facility()
assert not valid_facility
assert out == handlers.SysLogHandler.LOG_USER
os.environ['WALE_SYSLOG_FACILITY'] = 'local... | 5,334,703 |
def nodes():
"""
get node list for the current lab
"""
server = VIRLServer()
client = get_cml_client(server)
current_lab = get_current_lab()
if current_lab:
lab = safe_join_existing_lab(current_lab, client)
if lab:
node_list_table(lab.nodes())
else:
... | 5,334,704 |
def make_pizza(size, *toppings):
"""概述要制作的pizza"""
print("\nMaking a " + str(size) + "-inch pizza with the following toppings:")
for topping in toppings:
print("- " + topping) | 5,334,705 |
def _check_resource(resource_path: str) -> bool:
"""
Checks if the resource is file and accessible, or checks that all resources in directory are files and accessible
:param resource_path: A path to the resource
:return: True if resource is OK to upload, False otherwise
"""
if os.path.isfile(res... | 5,334,706 |
def upload_log(blob_client, application):
"""
upload output.log to storage account
"""
log_file = os.path.join(os.environ["AZ_BATCH_TASK_WORKING_DIR"], os.environ["SPARK_SUBMIT_LOGS_FILE"])
upload_file_to_container(
container_name=os.environ["STORAGE_LOGS_CONTAINER"],
application... | 5,334,707 |
def convert_one_fmt_off_pair(node: Node) -> bool:
"""Convert content of a single `# fmt: off`/`# fmt: on` into a standalone comment.
Returns True if a pair was converted.
"""
for leaf in node.leaves():
previous_consumed = 0
for comment in list_comments(leaf.prefix, is_endmarker=False):
... | 5,334,708 |
def merge_tf_records(output_path: str, src_records: List[str]) -> None:
"""Merge multiple TFRecord files into one.
Args:
output_path: Where to write the merged TFRecord file.
src_records: A list of strings giving the location of the
input TFRecord files.
Returns:
N... | 5,334,709 |
def scale_down_deployments(node_name):
"""
Scale down the deployments of a node as described in the documents
of node replacement with LSO
Args:
node_name (str): The node name
"""
ocp = OCP(kind="node", namespace=defaults.ROOK_CLUSTER_NAMESPACE)
pods_to_scale_down = get_node_pods_t... | 5,334,710 |
def validate_uuid4(uuid_string):
"""
Source: https://gist.github.com/ShawnMilo/7777304
Validate that a UUID string is infact a valid uuid4. Luckily, the uuid module
does the actual checking for us. It is vital that the 'version' kwarg be
passed to the UUID() call, otherwise any 32-characterhex strin... | 5,334,711 |
def check_sp(sp):
"""Validate seasonal periodicity.
Parameters
----------
sp : int
Seasonal periodicity
Returns
-------
sp : int
Validated seasonal periodicity
"""
if sp is not None:
if not is_int(sp) or sp < 1:
raise ValueError("`sp` must be a p... | 5,334,712 |
def api_error_handler(func):
"""
Handy decorator that catches any exception from the Media Cloud API and
sends it back to the browser as a nicely formatted JSON error. The idea is
that the client code can catch these at a low level and display error messages.
"""
@wraps(func)
def wrapper(*a... | 5,334,713 |
def gen_data(data_format, dtype, shape):
"""Generate data for testing the op"""
input = random_gaussian(shape, miu=1, sigma=0.1).astype(dtype)
head_np = input
if data_format == "NC1HWC0":
channel_dims = [1, 4]
elif data_format == DEFAULT:
channel_dims = [1]
else:
channel_... | 5,334,714 |
def clean_value_name(value: Any) -> str:
"""Returns a string representation of an object."""
if isinstance(value, pydantic.BaseModel):
value = str(value)
elif isinstance(value, float) and int(value) == value:
value = int(value)
value = str(value)
elif isinstance(value, (np.int64,... | 5,334,715 |
def add_line_analyzer(func):
"""A simple decorator that adds a function to the list
of all functions that analyze a single line of code."""
LINE_ANALYZERS.append(func)
def wrapper(tokens):
return func(tokens)
return wrapper | 5,334,716 |
def decode_account(source_a):
"""
Take a string of the form "xrb_..." of length 64 and return
the associated public key (as a bytes object)
"""
assert len(source_a) == 64
assert source_a.startswith('xrb_') or source_a.startswith('xrb-')
number_l = 0
for character in source_a[4... | 5,334,717 |
def update_epics_order_in_bulk(bulk_data: list, field: str, project: object):
"""
Update the order of some epics.
`bulk_data` should be a list of tuples with the following format:
[{'epic_id': <value>, 'order': <value>}, ...]
"""
epics = project.epics.all()
epic_orders = {e.id: getattr(e, ... | 5,334,718 |
def calc_precision(output, target):
"""calculate precision from tensor(b,c,x,y) for every category c"""
precs = []
for c in range(target.size(1)):
true_positives = ((output[:, c] - (output[:, c] != 1).int()) == target[:, c]).int().sum().item()
# print(true_positives)
false_positives... | 5,334,719 |
def _move_files(files):
"""
Launches a window to select the new folder destinations for the files.
Parameters
----------
files : list
A nested list of lists of lists of strings corresponding
to file paths.
"""
text_layout = [[sg.Text(f'Dataset {i + 1}')] for i in range(len... | 5,334,720 |
def upper_credible_choice(self):
"""pick the bandit with the best LOWER BOUND. See chapter 5"""
def lb(a,b):
return a/(a+b) + 1.65*np.sqrt((a*b)/((a+b)**2*(a+b+1)))
a = self.wins + 1
b = self.trials - self.wins + 1
return np.argmax(lb(a,b)) | 5,334,721 |
def download(bell, evnt):
"""
Download the current event from the given doorbell.
If the video is already in the download history or
successfully downloaded then return True otherwise False.
"""
event_id = evnt.get("id")
event_time = evnt.get("created_at")
filename = "".join... | 5,334,722 |
def copytask(filename, num_seqs, len_min, len_max, num_vals):
"""
Generate sequences of random binary vectors for the copy task
and save as .tfrecords file
Args:
filename - the name of the file to save
num_seqs - the number of sequences to generate
len_min/max - the minimum and m... | 5,334,723 |
def get_unique_id():
"""
for unique random docname
:return: length 32 string
"""
_id = str(uuid.uuid4()).replace("-", "")
return _id | 5,334,724 |
def callback():
""" Step 3: Retrieving an access token.
The user has been redirected back from the provider to your registered
callback URL. With this redirection comes an authorization code included
in the redirect URL. We will use that to obtain an access token.
"""
# Grab the Refres... | 5,334,725 |
def load_azure_auth() -> AzureSSOClientConfig:
"""
Load config for Azure Auth
"""
return AzureSSOClientConfig(
clientSecret=conf.get(LINEAGE, "client_secret"),
authority=conf.get(LINEAGE, "authority"),
clientId=conf.get(LINEAGE, "client_id"),
scopes=conf.getjson(LINEAGE, ... | 5,334,726 |
def get_map_zones(map_id):
"""Get map zones.
.. :quickref: Zones; Get map zones.
**Example request**:
.. sourcecode:: http
GET /zones/map/1 HTTP/1.1
**Example response**:
.. sourcecode:: json
[
{
"id": 1,
"p1": [0, 0, 0],
"p2": [25... | 5,334,727 |
def rgb2he_macenko(img, D=None, alpha=1.0, beta=0.15, white=255.0,
return_deconvolution_matrix=False):
"""
Performs stain separation from RGB images using the method in
M Macenko, et al. "A method for normalizing histology slides for quantitative analysis",
IEEE ISBI, 2009. dx.doi.org... | 5,334,728 |
def validated(base_model=None):
"""
Decorates an ``__init__`` method with typed parameters with validation
and auto-conversion logic.
>>> class ComplexNumber:
... @validated()
... def __init__(self, x: float = 0.0, y: float = 0.0) -> None:
... self.x = x
... self... | 5,334,729 |
def make_header_table(fitsdir, search_string='*fl?.fits'):
"""Construct a table of key-value pairs from FITS headers of images
used in dolphot run. Columns are the set of all keywords that appear
in any header, and rows are per image.
Inputs
------
fitsdir : string or Path
directory of... | 5,334,730 |
def test_main_incorrect_json_structure(monkeypatch, capfd, service_account_json, caplog):
"""Tests the execution of main function when incorrectly formatted service account json is provided."""
from RubrikPolaris import main
monkeypatch.setattr(mock_params, lambda: {
"url": "rubrik-se-beta",
... | 5,334,731 |
def parse_head_final_tags(ctx, lang, form):
"""Parses tags that are allowed at the end of a form head from the end
of the form. This can also be used for parsing the final gender etc tags
from translations and linkages."""
assert isinstance(ctx, Wtp)
assert isinstance(lang, str) # Should be langua... | 5,334,732 |
def cars_to_people(df,peoplePerCar=1.7,percentOfTransit=.005):
"""
args: demand dataframe, people/car float, % of transit floats
returns: people demand dataframe by terminal and arrival/departure
"""
columns = ['Arrive_A','Arrive_B','Arrive_C','Arrive_D','Arrive_E',
'Depart_A','Depart... | 5,334,733 |
def get_dup_key_val(errmsg):
"""Return the duplicate key referenced in an error message.
Parameters
----------
errmsg : |str|
A pymongo `DuplicateKeyError` message.
Returns
-------
|dict|
The key(s) and value(s) of the duplicate key.
Example
-------
>>> errmsg ... | 5,334,734 |
def mock_archive(request, tmpdir_factory):
"""Creates a very simple archive directory with a configure script and a
makefile that installs to a prefix. Tars it up into an archive.
"""
tar = spack.util.executable.which('tar', required=True)
tmpdir = tmpdir_factory.mktemp('mock-archive-dir')
tmpd... | 5,334,735 |
def worker(vac_flag,cache_dict,mylock): # Used in multiprocess_traditional_evaluate() #20220204
"""thread worker function"""
this_key = tuple(vac_flag.squeeze().cpu().numpy())
if(this_key in cache_dict):
print('Found in cache_dict')
[total_cases, case_rate_std] = cache_dict[this_key]
el... | 5,334,736 |
def use_k8s_secret(
secret_name: str = 'k8s-secret',
k8s_secret_key_to_env: Optional[Dict] = None,
):
"""An operator that configures the container to use k8s credentials.
k8s_secret_key_to_env specifies a mapping from the name of the keys in the k8s secret to the name of the
environment variables w... | 5,334,737 |
def delete_access_key(UserName=None, AccessKeyId=None):
"""
Deletes the access key pair associated with the specified IAM user.
If you do not specify a user name, IAM determines the user name implicitly based on the AWS access key ID signing the request. Because this action works for access keys under the A... | 5,334,738 |
def get_recommendations(artists = tuple(), genres = tuple(), limit = 20, features = True, client = None):
"""Return DataFrame of recommended tracks.
Arguments:
artists: an optional sequence of artists to seed recommendation
genres: an optional sequence of genres to seed recommendation
... | 5,334,739 |
def reorder_point(max_units_sold_daily, avg_units_sold_daily, max_lead_time, avg_lead_time, lead_time):
"""Returns the reorder point for a given product based on sales and lead time.
The reorder point is the stock level at which a new order should be placed in order to avoid stock outs.
Args:
max_... | 5,334,740 |
def get_total_value_report(total_value):
""""TBD"""
# Total value report
currency = CURRENCY
slack_str = "*" + "Total value report" + "*\n>>>\n"
slack_str = slack_str + make_slack_etf_chain_total(total_value, currency)
"""
sendSlackNotification('etf', slack_str, "ETF Notification", ':chart_w... | 5,334,741 |
def verify_count_responses(responses):
""" Verifies that the responses given are well formed.
Parameters
----------
responses : int OR list-like
If an int, the exact number of responses targeted.
If list-like, the first two elements are the minimum and maximum
(inclusive) range ... | 5,334,742 |
def _mdk_writefile(path, contents):
"""Write a file to disk."""
with open(path, "wb") as f:
f.write(contents.encode("utf-8")) | 5,334,743 |
def _subtract(supernet, subnets, subnet_idx, ranges):
"""Calculate IPSet([supernet]) - IPSet(subnets).
Assumptions: subnets is sorted, subnet_idx points to the first
element in subnets that is a subnet of supernet.
Results are appended to the ranges parameter as tuples of in format
(version, first... | 5,334,744 |
def commiter_factory(config: dict) -> BaseCommitizen:
"""Return the correct commitizen existing in the registry."""
name: str = config["name"]
try:
_cz = registry[name](config)
except KeyError:
msg_error = (
"The commiter has not been found in the system.\n\n"
f"T... | 5,334,745 |
def changeDocIdToMongoId(jsonDoc):
"""
Changes the _id to ObjectId.
Will crash if jsonDoc is not a simple JSON object with _id field
"""
if(jsonDoc is not None):
jsonDoc['_id'] = ObjectId(jsonDoc['_id']) | 5,334,746 |
def faceshq(output_folder):
"""faceshq.
src yaml: 'https://app.koofr.net/links/a04deec9-0c59-4673-8b37-3d696fe63a5d?path=%2F2020-11-13T21-41-45_faceshq_transformer%2Fconfigs%2F2020-11-13T21-41-45-project.yaml'
src ckpt: 'https://app.koofr.net/content/links/a04deec9-0c59-4673-8b37-3d696fe63a5d/files/get/last... | 5,334,747 |
async def apiAccountEditPhaaze(cls:"WebIndex", WebRequest:Request) -> Response:
"""
Default url: /api/account/phaaze/edit
"""
WebUser:WebUserInfo = await cls.getWebUserInfo(WebRequest)
if not WebUser.found:
return await apiMissingAuthorisation(cls, WebRequest)
Data:WebRequestContent = WebRequestContent(WebRe... | 5,334,748 |
def put_push_messages_to_dynamo(body, shop_info, remind_date_difference):
"""
プッシュメッセージ情報を作成し、
予約完了メッセージの送信とDynamoDBにメッセージを登録処理を実行する。
Parameters
----------
body : dict
フロントから渡ってきたパラメータ
remind_date_difference : int
当日以前のリマインド行う日付の差分
予約日以降のメッセージ送信を考慮し、マイナス値を許可(ex:3日前→ ... | 5,334,749 |
def start(mainloop=False,banner=True):
"""
Start Tk and read in an options_database file (if present), then
open a TopoConsole.
Does nothing if the method has previously been called (i.e. the
module-level console variable is not None).
mainloop: If True, then the command-line is frozen while t... | 5,334,750 |
def get_s3_items_by_type_from_queue(volume_folder):
"""
Load redis queue named "volume:<volume_folder>", and return dict of keys and md5s sorted by file type.
Queue will contain items consisting of newline and tab-delimited lists of files.
Returned value:
{'alto': [[s3_key, md5]... | 5,334,751 |
def calculate_mixture_features(workspace, speech_dir, noise_dir, data_type, snr):
"""Calculate spectrogram for mixed, speech and noise audio. Then write the
features to disk.
Args:
workspace: str, path of workspace.
speech_dir: str, path of speech data.
noise_dir: str, path of nois... | 5,334,752 |
def strip_spectral_type(series, return_mask=False):
"""
Strip spectral type from series of string
Args:
series (pd.Series): series of object names (strings)
return_mask (bool): returns boolean mask True where there is a type
Returns:
no_type (pd.Series): series without spectral ... | 5,334,753 |
def already_in_bioconda(recipe, meta, df):
"""
Does the package exist in bioconda?
"""
results = _subset_df(recipe, meta, df)
build_number = int(meta.get_value('build/number', 0))
build_results = results[results.build_number == build_number]
channels = set(build_results.channel)
if 'bioc... | 5,334,754 |
def expand_groups(node_id, groups):
"""
node_id: a node ID that may be a group
groups: store group IDs and list of sub-ids
return value: a list that contains all group IDs deconvoluted
"""
node_list = []
if node_id in groups.keys():
for component_id in groups[node_id]:
... | 5,334,755 |
def atol_receive_receipt_report(self, receipt_id):
"""
Attempt to retrieve a receipt report for given receipt_id
If received an unrecoverable error, then stop any further attempts to receive the report
"""
atol = AtolAPI()
Receipt = apps.get_model('atol', 'Receipt')
receipt = Receipt.objects... | 5,334,756 |
def _preservation_derivatives_query(storage_service_id, storage_location_id, aip_uuid):
"""Fetch information on preservation derivatives from db.
:param storage_service_id: Storage Service ID (int)
:param storage_location_id: Storage Location ID (int)
:param aip_uuid: AIP UUID (str)
:returns: SQLA... | 5,334,757 |
def euler2rot_symbolic(angle1='ϕ', angle2='θ', angle3='ψ', order='X-Y-Z', ertype='extrinsic'):
"""returns symbolic expression for the composition of elementary rotation matrices
Parameters
----------
angle1 : string or sympy.Symbol
angle representing first rotation
angle2 : string or sym... | 5,334,758 |
def add_plugin_translations(plugin, translation):
"""Adds a new language to the plugin translations.
:param plugin: The plugins identifier.
:param translation: The short name of the translation
like ``en`` or ``de_AT``.
"""
plugin_folder = current_app.pluggy.get_plugin(plugi... | 5,334,759 |
def k4a_playback_get_next_imu_sample(playback_handle, imu_sample):
"""
K4ARECORD_EXPORT k4a_stream_result_t k4a_playback_get_next_imu_sample(k4a_playback_t playback_handle,
k4a_imu_sample_t *imu_sample);
"""
_k4a_playback_get_next_imu_sample = record_dll.k4a_playback_get_next_imu_sample
_k4a_playb... | 5,334,760 |
def knapsack_iterative_numpy(items, maxweight):
"""
Iterative knapsack method
maximize \sum_{i \in T} v_i
subject to \sum_{i \in T} w_i \leq W
Notes:
dpmat is the dynamic programming memoization matrix.
dpmat[i, w] is the total value of the items with weight at most W
T is ... | 5,334,761 |
def gram_matrix(image: torch.Tensor):
"""https://pytorch.org/tutorials/
advanced/neural_style_tutorial.html#style-loss"""
n, c, h, w = image.shape
x = image.view(n * c, w * h)
gram_m = torch.mm(x, x.t()).div(n * c * w * h)
return gram_m | 5,334,762 |
def create_xls_file(files,
output,
clean=False,
delimiter=DEF_DELIMITER,
quotechar=DEF_QUOTECHAR,
inference=True,
date_format=DEF_DATE_FORMAT,
keep_prefix=False):
"""Main funct... | 5,334,763 |
def _block_diag_cvp(model, vec):
"""
g: n x p
v: p
c = sum[gg^t]: p x p
cvp = sum[gg^t]v = sum[g(g^t)v]: p
"""
batch_gvp_dict = {k: v for k, v in _module_batch_gvp(model, vec)}
for module, batch_grads in _module_batch_grads(model):
cvp = []
# compute cvp = sum[g(g^t)v]
... | 5,334,764 |
def photos_of_user(request, user_id):
"""Displaying user's photo gallery and adding new photos to user's gellery
view.
"""
template = 'accounts/profile/photos_gallery.html'
user_acc = get_object_or_404(TLAccount, id=user_id)
photos = user_acc.photos_of_user.all() # Custom related name
con... | 5,334,765 |
def sync(lock):
"""
A thread that will sync Leases with the local rethinkdb
"""
# db connection is shared between threads
dbconnection = connect()
logger = logging.getLogger('myslice.leases')
while True:
logger.info("syncing Leases")
try:
syncLeases()
exc... | 5,334,766 |
def sw_update_opts_w_name_db_model_to_dict(sw_update_opts, subcloud_name):
"""Convert sw update options db model plus subcloud name to dictionary."""
result = {"id": sw_update_opts.id,
"name": subcloud_name,
"subcloud-id": sw_update_opts.subcloud_id,
"storage-apply-type... | 5,334,767 |
def test_jsd5():
""" Test that JSD fails when more weights than dists are given """
d1 = Distribution("AB", [0.5, 0.5])
d2 = Distribution("BC", [0.5, 0.5])
assert_raises(ditException, JSD, [d1, d2], [0.1, 0.6, 0.3]) | 5,334,768 |
def imf_binary_primary(m, imf, binary_fraction=constants.BIN_FRACTION):
"""
Initial mass function for primary stars of binary systems
Integrated between m' and m'' using Newton-Cotes
Returns 0 unless m is in (1.5, 16)
"""
m_inf = max(constants.B_MIN, m)
m_sup = min(constants.B_MAX, 2 * m)
... | 5,334,769 |
def optimize_local_loss(layer, get_inp_out, data_tensor, optimizer, loss_fn, batch_size, iters,
use_cached_data=True, keep_gpu=True):
"""AdaRound optimization loop."""
if use_cached_data:
logger.info('Caching data for local loss optimization')
cached_batches = []
... | 5,334,770 |
def compute_scene_graph_similarity(ade20k_split, threshold=None,
recall_funct=compute_recall_johnson_feiefei):
"""
:param ade20k_split:
:param threshold:
:param recall_funct:
:return:
"""
model = get_scene_graph_encoder()
model.ev... | 5,334,771 |
def load_cmudict():
"""Loads the CMU Pronouncing Dictionary"""
dict_ref = importlib_resources.files("tacotron").joinpath("cmudict-0.7b.txt")
with open(dict_ref, encoding="ISO-8859-1") as file:
cmudict = (line.strip().split(" ") for line in islice(file, 126, 133905))
cmudict = {
... | 5,334,772 |
def evalasm(d, text, r0 = 0, defines = defines, address = pad, thumb = False):
"""Compile and remotely execute an assembly snippet.
32-bit ARM instruction set by default.
Saves and restores r2-r12 and lr.
Returns (r0, r1).
"""
if thumb:
# In Thumb mode, we still use ARM cod... | 5,334,773 |
def _get_thread_count():
"""Gets a thread_count based on the multiprocessing.cpu_count()."""
try:
thread_count = multiprocessing.cpu_count()
# cpu_count only gets the physical core count. There doesn't appear to be a
# simple way of determining whether a CPU supports simultaneous
# multithreading in... | 5,334,774 |
def _fft_inplace(points, invert=True):
"""Computes the fast fourier transform inplace
The length of points must be a power of two. Pass False to invert to
calculate the inverse.
"""
# Resources:
# https://cp-algorithms.web.app/algebra/fft.html
# https://jakevdp.github.io/blog/2013/08/28/un... | 5,334,775 |
def is_dir(dir_name):
"""Checks if a path is an actual directory"""
if not os.path.isdir(dir_name):
msg = "{0} does not exist".format(dir_name)
raise argparse.ArgumentTypeError(msg)
else:
return dir_name | 5,334,776 |
def weighted_avg(x, weights): # used in lego_reader.py
""" x = batch * len * d
weights = batch * len
"""
return weights.unsqueeze(1).bmm(x).squeeze(1) | 5,334,777 |
def test_partial_load__short_read_of_required():
"""Crash if we get a short read on a required field."""
stream = io.BytesIO(b"zyxwvut\x0b\xad")
# int64 should be the last field included in the output.
with pytest.raises(errors.UnexpectedEOFError):
BasicStruct.partial_load(stream, "int64") | 5,334,778 |
def CYR(df, N=5, M=5):
"""
市场强弱
:param df:
:param M:
:return:
"""
VOL = df['volume']
AMOUNT = df['amount']
DIVE = 0.01 * EMA(AMOUNT, N) / EMA(VOL, N)
CRY = (DIVE / REF(DIVE, 1) - 1) * 100
MACYR = MA(CRY, M)
return pd.DataFrame({
'CRY': CRY, 'MACYR': MACYR
}) | 5,334,779 |
def configure_vrf_on_interface(device, interface, vrf):
""" Configure interface to use VRF
Args:
device ('obj'): Device object
interface ('str'): Interface
vrf ('str'): VRF name
Returns:
None
Raises:
SubCommandFailure
"""
... | 5,334,780 |
def main(number, divisors):
""" Run the program """
print(som(number, divisors)) | 5,334,781 |
def test_download_urls_to_file(
credentials, mocker, project_id_download, recording, vcr
):
"""Test saving downloaded urls output to a json file."""
runner = CliRunner()
if not recording:
# Mock only if using the cassettes, since we mock the return value.
get_project_samples_response = g... | 5,334,782 |
def packCode(code):
"""Packs the given code by passing it to the compression engine"""
if code in packCache:
return packCache[code]
packed = compressor.compress(parse(code))
packCache[code] = packed
return packed | 5,334,783 |
def _get_vars_cls(_cls):
"""
Yield all attributes and it's value which isn't in object class.
class AnyClass(object):
a=1
b=2.
list(_get_vars_cls(_cls))
# return: [('a', 1), ('b', 2)]
"""
if not inspect.isclass(_cls):
raise TypeError(f"Expect class object. Got '{typ... | 5,334,784 |
def cus_excepthook(logger):
"""
Custom excepthook function to log exception information.
logger will log exception information automatically.
This doesn't work in ipython(including jupyter). Use `get_ipython().set_custom_execs((Exception,), your_exception_function)` instead in ipython environment.
... | 5,334,785 |
def langpack_submission_allowed(user, parsed_addon_data):
"""Language packs can only be submitted by people with the right
permission.
See https://github.com/mozilla/addons-server/issues/11788 and
https://github.com/mozilla/addons-server/issues/11793
"""
return (
not parsed_addon_data.g... | 5,334,786 |
def ht_edge_probabilities(p):
"""
Given the probability of sampling an edge, returns the probabilities of sampling two-stars and triangles
Parameters
---------------------
p: float
"""
pi_twostars = 0
pi_triangles = 0
###TIP: #TODO write the probabilites of sampling twostars and tri... | 5,334,787 |
def install_git_hook(c, force=False):
"""Installs pre-push git hook
"""
path = Path('.git/hooks/pre-push')
hook_exists = path.is_file()
if hook_exists:
if force:
path.unlink()
else:
sys.exit('Error: pre-push hook already exists. '
'Run: "... | 5,334,788 |
def lseek(fd, pos, how):
"""Set the current position of file descriptor *fd* to position *pos*, modified
by *how*: :const:`SEEK_SET` or ``0`` to set the position relative to the
beginning of the file; :const:`SEEK_CUR` or ``1`` to set it relative to the
current position; :const:`os.SEEK_END` or... | 5,334,789 |
def get_tag_color_name(colorid):
""" Return name of the Finder color based on ID """
# TODO: need to figure out how to do this in locale/language name
try:
colorname = _COLORIDS[colorid]
except:
raise ValueError(f"Invalid colorid: {colorid}")
return colorname | 5,334,790 |
def com_google_fonts_check_083(family_metadata):
"""METADATA.pb: check if fonts field only has
unique "full_name" values.
"""
fonts = {}
for f in family_metadata.fonts:
fonts[f.full_name] = f
if len(set(fonts.keys())) != len(family_metadata.fonts):
yield FAIL, ("Found duplicated \"full_name\" va... | 5,334,791 |
def process_derived_core_properties(derived_core_properties):
"""Parse DerivedCoreProperties.txt and returns its version,
and set of characters with ID_Start and ID_Continue. """
id_start = set()
id_continue = set()
m = re.match('# DerivedCoreProperties-([0-9\.]+).txt', derived_core_properties)
... | 5,334,792 |
def error_500(error):
"""Route function for handling 500 error pages
"""
return flask.templating.render_template("errors/500.html.j2"), 500 | 5,334,793 |
def poormax(X : np.ndarray, feature_axis = 1) -> np.ndarray:
"""
对数据进行极差化 \n
:param feature_axis: 各特征所在的维度 \n
feature_axis = 1 表示每列是不同的特征 \n
"""
if not feature_axis:
X = X.T
_min = np.min(X, axis = 0)
_max = np.max(X, axis = 0)
across = _max - _min
X = (X - _min) / across
if not featu... | 5,334,794 |
def login_form(request):
"""
The request must be get
"""
menu = MenuService.visitor_menu()
requestContext = RequestContext(request, {'menu':menu,
'page_title': 'Login'} )
return render_to_response('login.html', requestContext) | 5,334,795 |
def tz_from_dd(points):
"""Get the timezone for a coordinate pair
Args:
points: (lat, lon) | [(lat, lon),] | pd.DataFrame w/lat and lon as columns
Returns:
np.array
"""
if isinstance(points, pd.DataFrame):
points = points.values.tolist()
if not isinstance(points, list)... | 5,334,796 |
def create_volume(devstack_node, ceph_node, vol_name, size):
"""
:param size: The size of the volume, in GB
"""
size = str(size)
log.info("Creating a {size}GB volume named {name}...".format(
name=vol_name,
size=size))
args = ['source', 'devstack/openrc', run.Raw('&&'), 'cinder', ... | 5,334,797 |
def find_touching_pixels(label_img, distance=1, selem=None):
"""
Returns a mask indicating touching regions. Either provide a diameter for a disk shape
distance or a selem mask.
:param label_img: a label image with integer labels
:param distance: =1: touching pixels, >1 pixels labels distance appart... | 5,334,798 |
def install_ssh_keys(config, *hosts):
"""
Generate and put public and private SSH keys to hosts that are listed in
hosts to make cold migration work.
:param config: CloudFerry config
:param hosts: list of hosts where to install keys
"""
ssh_user = config.cloud.ssh_user
ssh_password = con... | 5,334,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.