content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import argparse
def setup_args():
"""Setup and return the command line argument parser"""
parser = argparse.ArgumentParser(description='')
# parser.add_argument('csv', type=str, help='CSV file to load')
parser.add_argument(
'-clang-tidy-binary', help='Path to the clang-tidy executable.', meta... | 477da4faf063a461a77791f372f50e0e105b8ac7 | 3,642,900 |
def create_event(type_, source):
"""Create Event"""
cls = _events.get(type_, UnknownEvent)
try:
return cls(type=type_, **source)
except TypeError as e:
raise TypeError(f'Error at creating {cls.__name__}: {e}') | 263fc768d94db5ae9cb0acb8565c01337ffb56c6 | 3,642,901 |
import tempfile
import os
import stat
import subprocess
def _execute(script, prefix=None, path=None):
"""
Execute a shell script.
Setting prefix will add the environment variable
COLCON_BUNDLE_INSTALL_PFREFIX equal to the passed in value
:param str script: script to execute
:param str prefix... | e7e34a0da2acee1193f4511688aea43685b359e8 | 3,642,902 |
import os
def main(event, context):
"""
Gets layer arns for each region and publish to S3
"""
dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table(os.environ["DB_NAME"])
region = event.get("pathParameters").get("region")
python_version = event.get("pathParameters").get("python_ver... | 392b8a7cc5c13efc489ce1c331d4e457e9da994b | 3,642,903 |
import os
import pickle
def rescore_and_rerank_by_num_inliers(test_image_id,
train_ids_labels_and_scores):
"""Returns rescored and sorted training images by local feature extraction."""
test_image_path = get_image_path(test_image_id)
try:
name = os.path.base... | 837718c2d3d206485651a2dc4ee16682747a0889 | 3,642,904 |
from typing import Iterable
from typing import Callable
from typing import List
from typing import Awaitable
import asyncio
def aggregate_policy(
policies: Iterable[PermissionPolicy_T],
aggregator: Callable[[Iterable[object]], bool] = all
) -> PermissionPolicy_T:
"""
在默认参数下,将多个权限检查策略函数使用 AND 操作符连接并返回单... | c0fa2ef66ba71deba88ca4e9debbb521ba49fe82 | 3,642,905 |
def optionally_load_system_paasta_config(
path: str = PATH_TO_SYSTEM_PAASTA_CONFIG_DIR,
) -> "SystemPaastaConfig":
"""
Tries to load the system paasta config, but will return an empty configuration if not available,
without raising.
"""
try:
return load_system_paasta_config(path=path)
... | 7309d28ab156572d1b3cdbf347d4979f3ee607d8 | 3,642,906 |
def get_sage_bank_accounts(company_id: int) -> list:
"""
Retrieves the bank accounts for a company in Sage One
**company_id** The Company ID
"""
config = get_config() # Get the config
sage_client = SageOneAPIClient(config.get("sageone", "url"), config.get("sageone", "api_key"), config.get("sage... | a3684d5a3b06944ba297f95b5498d61f7281c40c | 3,642,907 |
def compute_fstar(tarr, mstar, index_select, index_high, fstar_tdelay):
"""Time averaged SFH that has ocurred over some previous time period
fstar = (mstar(t) - mstar(t-fstar_tdelay)) / fstar_tdelay
Parameters
----------
tarr : ndarray of shape (n_times, )
Cosmic time of each simulated snap... | 89ef08ee08f41fa6b7931ebdbbb3611bda6346ae | 3,642,908 |
def notification_error(code: str, search_id: str, status_code, message: str = None):
"""Return to the event listener a notification error response based on the status code."""
error = CALLBACK_MESSAGES[code].format(search_id=search_id)
if message:
error += ' ' + message
current_app.logger.error(... | 6522023ad36f7164a2c721493d38d3cc0b5d4690 | 3,642,909 |
import os
def get_avg(feature_name, default_value):
"""Get the average of numeric feature from the environment.
Return the default value if there is no the statistics in
the environment.
Args:
feature_name: String, feature name or column name in a table
default_value: Float.
Retu... | 5d1b7270dc0021f5b4a28ad3203a65860b6a05b5 | 3,642,910 |
def arccos(x: REAL) -> float:
"""Arc cosine."""
return pi/2 - arcsin(x) | 1829e6d777c32172afee7e8608d5d1034458660f | 3,642,911 |
import requests
def isLinkValid(test_video_link):
"""def isLinkValid(test_video_link): -> test_video_link
check if youtube video link is valid."""
try:
data = requests.get("https://www.youtube.com/oembed?format=json&url=" + test_video_link).json()
if data == "Not Found":
retu... | 0af4f8c1d05f2b98d046d63d5eaf39f679a37818 | 3,642,912 |
import time
import calendar
def _strptime(data_string, format='%a %b %d %H:%M:%S %Y'):
"""Return a 2-tuple consisting of a time struct and an int containing
the number of microseconds based on the input string and the
format string."""
for index, arg in enumerate([data_string, format]):
if not... | bd222fde85a3db2bdad28394f001ed74b1d68622 | 3,642,913 |
def to_simple_rdd(sc, features, labels):
"""Convert numpy arrays of features and labels into
an RDD of pairs.
:param sc: Spark context
:param features: numpy array with features
:param labels: numpy array with labels
:return: Spark RDD with feature-label pairs
"""
pairs = [(x, y) for x,... | 87afaae6214bedbde60d46e21d8ea82d644a0ca1 | 3,642,914 |
def add_decimal(op1: Decimal, op2: Decimal)-> Decimal:
"""
add
:param op1:
:param op2:
:return:
"""
result = op1 + op2
if result > 999:
return float(result)
return result | d05501daf67845eb339c7103fad02c7d0e2f8dc9 | 3,642,915 |
import os
def get_data_file_path(project, filename):
"""
Gets the path of data files we've stored for each project
:param project:
:return:
"""
return os.path.join(BASE_DIR, "waterspout_api", "data", project, filename) | cd64f6c96671e4ea9e28dd906d551a5edf35ca41 | 3,642,916 |
def freenas_spec(**kwargs):
"""FreeNAS specs."""
# Setup vars from kwargs
builder_spec = kwargs['data']['builder_spec']
bootstrap_cfg = None
builder_spec.update(
{
'boot_command': [
'<enter>',
'<wait30>1<enter>',
'y',
... | ffe666fd48b6d545e44389ae0413bc1f0c29c44e | 3,642,917 |
def checksum(routine):
"""
Compute the M routine checksum used by ``CHECK1^XTSUMBLD``,
implemented in ``^%ZOSF("RSUM1")`` and ``SUMB^XPDRSUM``.
"""
checksum = 0
lineNumber = 0
with open(routine, 'r') as f:
for line in f:
line = line.rstrip('\r\n')
lineNumber += 1
# ignore the second ... | ca93bbf29967a90b22de007f84ba5ec3898a4f1a | 3,642,918 |
def nusdas_parameter_change(param, value):
"""
def nusdas_parameter_change()
"""
# Set argtypes and restype
nusdas_parameter_change_ct = libnus.NuSDaS_parameter_change
nusdas_parameter_change_ct.restype = c_int32
nusdas_parameter_change_ct.argtypes = (c_int32,POINTER(c_int32))
icond... | cea9011eb807c6281c9e3d07b640860ee085d1ad | 3,642,919 |
def validate_retention_time(retention_time):
# type: (str) -> str
"""Validate retention_time. If -1, return string, else convert to ms.
Keyword arguments:
retention_time -- user configured retention-ms, pattern: %d%h%m%s%ms
Return:
retention_time -- If set to "-1", return it
"""
if ret... | 8f7c701f7e2f2e8e5fa708fef80f04804964928c | 3,642,920 |
import re
def is_sale(this_line):
"""Determine whether a given line describes a sale of cattle."""
is_not_succinct = len(this_line.split()) > 3
has_price = re.search(r'[0-9]+\.[0-9]{2}', this_line)
return bool(has_price and is_not_succinct) | 382da3d9a1690950e64a29c6f2fcd54e062eb600 | 3,642,921 |
def extract_policy(env, v, gamma = 1.0):
""" Extract the policy given a value-function """
policy = np.zeros(env.env.nS)
for s in range(env.env.nS):
q_sa = np.zeros(env.env.nA)
for a in range(env.env.nA):
q_sa[a] = sum([p * (r + gamma * v[s_]) for p, s_, r, _ in env.env.P[s][a]])... | 2342a531e0fa29e4b7bb1946aa30cbe8b739b688 | 3,642,922 |
def generate_parameters(var):
"""
Defines a distribution of parameters
Returns a settings dictionary
var is an iterable of variables in the range [0,1) which
we can make use of.
"""
var = iter(var)
model={}
training={}
settings = {'model':model, 'training':training}
# ma... | 8336a7cb19db62fa95b3b0d131f2ca6f0e919e39 | 3,642,923 |
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... | 6fec63cc6e154f874ae3a46a373fb2d7ceff2423 | 3,642,924 |
import os
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.pat... | 39f8109054367fe2c7f3f5dc61b24564f81160d7 | 3,642,925 |
from typing import Optional
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... | 1ebbb67406a5d1de4e51c5a516b15750b0205567 | 3,642,926 |
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... | 56bf751cddd412ddc234f371a17019ee9192aefe | 3,642,927 |
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... | 475a56584915bc4b67663b3460959ca5e807ae06 | 3,642,928 |
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... | 6e03a5dc081a5aed7436a948194965d1e61504d4 | 3,642,929 |
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_... | 6fbc40b4879abec7a2f30c7f763102f51215e079 | 3,642,930 |
from typing import Any
import pydantic
import functools
import inspect
import pathlib
import copy
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) =... | 24635521ee8bd94324c0b29384ba0f0b39060244 | 3,642,931 |
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 | 538b6495be88d47b49efcd3ac28bd0b291810587 | 3,642,932 |
import hashlib
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 charac... | 5d083adcdd2f64c03c6a2e454b74b4d911381132 | 3,642,933 |
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, ... | 948bfaa6e165ac401cfa0244ee6c1b0bcd813493 | 3,642,934 |
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... | c35c500c786539578c46a8e8c4f6517bf30b4525 | 3,642,935 |
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)) | 20cefd0796f52a78d03b2d38cb74c532a07ec20c | 3,642,936 |
import os
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")
filena... | 437ba7167af2e5540fae317fbaab376f36723a80 | 3,642,937 |
import uuid
def get_unique_id():
"""
for unique random docname
:return: length 32 string
"""
_id = str(uuid.uuid4()).replace("-", "")
return _id | 4cf99a919bd0e9672f0b186626df0532cacebaf4 | 3,642,938 |
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 Refresh and Ac... | 76c4bec2c7c2a3433d4ab7665fca9d6829083626 | 3,642,939 |
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, ... | 4e7eb1886da496c465db95aa2cee2aec4a107d78 | 3,642,940 |
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... | 89e60a0fd2e0e2b743aa54cf1debe67e5f860a13 | 3,642,941 |
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... | bfe19ef7882ac713534d28c0d636bda086cf95c6 | 3,642,942 |
import inspect
from typing import Any
import functools
from typing import OrderedDict
import torch
def validated(base_model=None):
"""
Decorates an ``__init__`` method with typed parameters with validation
and auto-conversion logic.
>>> class ComplexNumber:
... @validated()
... def __... | af599bff5aa5d1efeb44297c117685609842a212 | 3,642,943 |
from pathlib import Path
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... | 3d5d10b73a8e76abedcf85ef97a9854920996a0a | 3,642,944 |
import re
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) # Shou... | 38891b08fa2223e90f73c732ff497606ab1c729b | 3,642,945 |
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... | 54672baacf10683a3d7224ee8672e08ee1574b30 | 3,642,946 |
import re
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
-------
... | 14cbf0f51a89c4b76c5a1d363e2ef1dfe994ede6 | 3,642,947 |
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... | d88e92c7cd3c5bf85389e83440dc7752719d66c0 | 3,642,948 |
from kubernetes import client as k8s_client
from typing import Optional
from typing import Dict
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 ... | 2e88ad765322752ba7417d865f0ea60879c4bafe | 3,642,949 |
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
... | 6c9c4c44b7c5269fbb9718b22dba74632e80b092 | 3,642,950 |
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_... | 876544b5bce39342fb753f6a1bf33913fae6e33d | 3,642,951 |
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... | be1a9ff18c2faf37ae7b58be34f15eb454c72d62 | 3,642,952 |
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 ... | 63fbd00bc26fee8eb960f389d5d56178e90ff7ae | 3,642,953 |
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... | a7c738b5ddab1ed896677a011029a00af5779bcd | 3,642,954 |
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... | 0e001652e0698efe981bf7dfe0cc69ce337e6f97 | 3,642,955 |
from pathlib import Path
import os
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-... | 15e17e7217bd7a03e56b508633249c24197caf7f | 3,642,956 |
import re
from datetime import datetime
import json
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, WebReque... | 5ac51d1c70031858294283c1f000af80e8838c99 | 3,642,957 |
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]... | 7afece0e2f1f8d0863873f1ef987790c2eb1dad3 | 3,642,958 |
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 ... | 65b91749742b229637819582b1158554b1a457ea | 3,642,959 |
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... | 0a7402e85a36f2f97a36a91bc379077f01ab22f5 | 3,642,960 |
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]:
no... | 4c4b9c569a85396f201c589635b6ecea3807ddc2 | 3,642,961 |
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... | a4ab7d6fc011c3ffc3678388b221514f38ecb5db | 3,642,962 |
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... | 07069fc6c543acb9960f8203130cabcd04a762f4 | 3,642,963 |
import ctypes
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_sa... | faa127b8788163de209863adee1419c349852827 | 3,642,964 |
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 ... | 7ef8ab10b91e72b7625fdfc9445501c4ae8e5554 | 3,642,965 |
import torch
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 | 5912cfec026cba26a77131c3b52a8e751c0f575e | 3,642,966 |
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... | 3fd3cdfac7f1af4de13c464a3fe2bea26f72e6c2 | 3,642,967 |
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... | c9c1703d9e4d0b69920d3ab06e5bf19fbb622103 | 3,642,968 |
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)
... | ae49a298d66a7ee844b252b5e736ea1c1846c31b | 3,642,969 |
import torch
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... | 061435209baa2c8d03af93ce09d00fcaf02adf8a | 3,642,970 |
import importlib_resources
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))
... | 76f3ed592cb3709d4f073c42ee7229ac0142b77a | 3,642,971 |
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... | c5bf3f5728fc9e85dbfd2540083ae7b2b87cd452 | 3,642,972 |
import multiprocessing
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 simultaneou... | f7c4959734e49a70412d87ebc1f03b811b600600 | 3,642,973 |
import os
import argparse
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 | fc24ce57394cd0d854a2d5f054faaea65339ae80 | 3,642,974 |
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) | efa08d9719ccbcc727cb7349888f0a26140521e9 | 3,642,975 |
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
}) | 7d5f31064d8eb3e4aaed8f6694226760a656f4d7 | 3,642,976 |
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 | b20714a022e73cbec38819d515c1cb89b8157d8c | 3,642,977 |
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.
... | 15e13567af3584a970cc78549c222b9d1ef921d9 | 3,642,978 |
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... | 5d26aaff3089a4e4ba6b2325f25d7ad5d759bcd9 | 3,642,979 |
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... | 47711a464e07583736348c7245caafbfd9f89abc | 3,642,980 |
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 | baa8519d1d3379a45ee79469f060fc9913e3a73c | 3,642,981 |
import re
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_pro... | cb15993eb84e3d1e7a1f65528f2f677e1e596668 | 3,642,982 |
def error_500(error):
"""Route function for handling 500 error pages
"""
return flask.templating.render_template("errors/500.html.j2"), 500 | 8d93367e21e855c672de50901de9793a326867e6 | 3,642,983 |
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 feature_axis:
X = ... | 8d2c45b225d05f36951eb6fac2fc19214b6e3f31 | 3,642,984 |
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) | 596273f8925a4d6aa39584f94262fc0f1d53657d | 3,642,985 |
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)... | 5a6b05f1bf88c3a016cc5beae024a99873715904 | 3,642,986 |
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', ... | 0cc8949bb18bcd5f71c50ea44b439d5ce63ef6f4 | 3,642,987 |
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... | a69b2b89be2df9660f1016c008c266de7932bb90 | 3,642,988 |
def draw_boxes_on_image(img, boxes, labels_index, labelmap_dict,
**kwargs):
"""Short summary.
Parameters
----------
img : ndarray
Input image.
boxes : ndarray-like
It must has shape (n ,4) where n is the number of
bounding boxes.
labels_index : nd... | 1ee1d7b4e04e8646dd4e986e1a7e72d42d3f9685 | 3,642,989 |
def guess_locations(location):
"""Convenience function to guess where other Strongholds are located."""
location = Point(*location)
return (location,
rotate(location, CLOCKWISE),
rotate(location, COUNTERCLOCKWISE)) | 34c6824d63dbd99e4b09c6bb588298add404d87a | 3,642,990 |
def get_centroid(mol, conformer=-1):
"""
Returns the centroid of the molecule.
Parameters
---------
conformer : :class:`int`, optional
The id of the conformer to use.
Returns
-------
:class:`numpy.array`
A numpy array holding the position of the centroid.
"""
cen... | 393b5e27a5fa1779f98c2455c88d36027036e5f2 | 3,642,991 |
import torch
def idct(X, norm=None):
"""
The inverse to DCT-II, which is a scaled Discrete Cosine Transform, Type III
Our definition of idct is that idct(dct(x)) == x
For the meaning of the parameter `norm`, see:
https://docs.scipy.org/doc/ scipy.fftpack.dct.html
:param X: the input signal
... | f0b86dbbe80fe9b2e4b442f55ea67b82f7eaa019 | 3,642,992 |
def div25():
"""
Returns the divider 44444444444444444444444
:return: divider25
"""
return divider25 | 6bb38e50a6cd7fe80c9aef5dbb2d829c0c5a6fb5 | 3,642,993 |
def comp_periodicity(self, wind_mat=None):
"""Computes the winding matrix (anti-)periodicity
Parameters
----------
self : Winding
A Winding object
wind_mat : ndarray
Winding connection matrix
Returns
-------
per_a: int
Number of spatial periods of the winding
... | f1c7074cdc55be6af3c5511a071a1df0835e666e | 3,642,994 |
def _is_valid_target(target, target_name, target_ports, is_pair):
"""Return True if the specified target is valid, False otherwise."""
if is_pair:
return (target[:utils.PORT_ID_LENGTH] in target_ports and
target_name == _PAIR_TARGET_NAME)
if (target[:utils.PORT_ID_LENGTH] not in targ... | 58a7c2ceb7b3206777c01122b0c3ef01a5887b65 | 3,642,995 |
def _get_span_name(servicer_context):
"""Generates a span name based off of the gRPC server rpc_request_info"""
method_name = servicer_context._rpc_event.call_details.method[1:]
if isinstance(method_name, bytes):
method_name = method_name.decode('utf-8')
method_name = method_name.replace('/', '.... | 5527820fa766fe29009e6fe060e76c01a75e3c37 | 3,642,996 |
def calculateNDFairnessPara(_ranking, _protected_group, _cut_point, _gf_measure, _normalizer, items_n, proItems_n ):
"""
Calculate group fairness value of the whole ranking.
Calls function 'calculateFairness' in the calculation.
:param _ranking: A permutation of N numbers (0..N-1) that repre... | b1c0dfa53d1842f8d93a6ed6d2ae2ddd9ebafd7b | 3,642,997 |
import os
def getCategories(blog_id, username, password):
"""
Parameters
int blog_id
string username
string password
Return Values
array
struct
int categoryId
int parentId
string description
string ... | f299cccbcc35b43029fd60c5dc459deed0a60906 | 3,642,998 |
import json
import requests
def change_server(name: str = None, description: str = None, repo_url: str = None, main_status: int = None, components: dict = None, password: str = None):
"""Change server according to arguments (using package config).
This will automatically change the config so it has the right... | f7a5334da8ef011969c8ffb5c31c1b4f477ed2a5 | 3,642,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.