content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def kernel_primitive_zhao_vec(x, s0=0.08333, theta=0.242):
"""
Calculates the primitive of the Zhao kernel for given values.
Optimized using nd-arrays and vectorization.
:param x: points to evaluate, should be a nd-array
:param s0: initial reaction time
:param theta: empirically determined cons... | 13,500 |
def capture_output(function, *args):
""" captures the printed output from a function """
@contextmanager
def captured_output():
new_out, new_err = StringIO(), StringIO()
old_out, old_err = sys.stdout, sys.stderr
try:
sys.stdout, sys.stderr = new_out, new_err
... | 13,501 |
def enable_pretty_logging_at_debug(
logger,
level,
log_file="",
backupCount=10,
maxBytes=10000000):
"""Turns on formatted logging output only at DEBUG level
"""
if level == logging.DEBUG:
enable_pretty_logging(logger, level, log_file, backupCount, maxBytes)
... | 13,502 |
def scaled_dot_product_attention(q, k, v, mask):
"""Calculate the attention weights.
q, k, v must have matching leading dimensions.
k, v must have matching penultimate dimension, i.e.: seq_len_k = seq_len_v.
The mask has different shapes depending on its type(padding or look ahead)
but it must be b... | 13,503 |
async def ban(message: types.Message):
"""
Заблокировать пользователя.
"""
try:
name = message.reply_to_message.from_user.full_name
user_id = message.reply_to_message.from_user.id
if user_id == BOT_ID: # Попытка забанить бота
await bot.send_message(message.chat.id, r... | 13,504 |
def drop_tables(config_name=None):
"""
Drop all tables despite existing constraints
Source https://bitbucket.org/zzzeek/sqlalchemy/wiki/UsageRecipes/DropEverything # noqa E501
:param config_name: a dict key which specifies which Config class to select
in config.config dict. The Config class encaps... | 13,505 |
def train_segmentation_model(
TRAIN_IMG_PATH: str,
TRAIN_LABELS_PATH: str,
VAL_IMG_PATH: str,
VAL_LABELS_PATH: str,
model_save_name: str = "segmentation_model.pt",
) -> Module:
"""The approach which has been used for training best categorization model
as defined and described in the given re... | 13,506 |
def cvCascades(argv=sys.argv[1:]):
"""Control the OpenCV cascade Examples.
Please see :meth:`cv2ArgumentParser <pycharmers.utils.argparse_utils.cv2ArgumentParser>` for arguments.
Note:
When you run from the command line, execute as follows::
$ cv-cascades --cam 0 --radio-width 200
... | 13,507 |
def new_creator_report(file_obj, keys, source):
"""Add CrossRef creators to existing Eprints record"""
print(f"Processing {len(keys)} eprint records for creators")
all_creators = []
if source.split(".")[-1] == "ds":
dot_paths = ["._Key", ".creators.items", ".related_url.items"]
labels = ... | 13,508 |
async def shutdown():
""" Close all open database connections """
global engines
for engine in engines.values():
engine.close()
await asyncio.gather(*[engine.wait_closed() for engine in engines.values()]) | 13,509 |
def extract_data(state: str, data) -> List[List[Any]]:
"""
Collects
"""
try:
extracted = []
for sample in data['_return']['traces']:
for obs in sample['trace']:
# TODO-Detail - put detail re the purpose of obs['q'] - I don't know what/why this
... | 13,510 |
def sort(ctx, targets="."):
"""Sort module imports."""
print("sorting imports ...")
args = ["isort", "-rc", "--atomic", targets]
ctx.run(" ".join(args)) | 13,511 |
def merge(input_list: List, low: int, mid: int, high: int) -> List:
"""
sorting left-half and right-half individually
then merging them into result
"""
result = []
left, right = input_list[low:mid], input_list[mid : high + 1]
while left and right:
result.append((left if left[0] <= ri... | 13,512 |
def fc_caps(activation_in,
pose_in,
ncaps_out,
name='class_caps',
weights_regularizer=None):
"""Fully connected capsule layer.
"The last layer of convolutional capsules is connected to the final capsule
layer which has one capsule per output class." We call ... | 13,513 |
def drawKernelIds00(ax, layer, inputSize, outputSize, fontsize, markersize,
synGroupColors):
"""Draw the kernel ids into an existing figure.
The displayed ids are not interleaved and are not grouped into partitions.
The ids are color-coded according to the unique synapse group they belo... | 13,514 |
def delete_host(deleter_email, host_id, cluster_ids):
"""Delete the given host.
:param host_id: id of the host
:type host_id: int
:param cluster_ids: list of cluster id
:type cluster_ids: list of int
"""
try:
delete.delete_host(
host_id, cluster_ids, deleter_email
... | 13,515 |
def get_optional_relations():
"""Return a dictionary of optional relations.
@returns {relation: relation_name}
"""
optional_interfaces = {}
if relation_ids('ceph'):
optional_interfaces['storage-backend'] = ['ceph']
if relation_ids('neutron-plugin'):
optional_interfaces['neutron-... | 13,516 |
def rf_plot(X, y, a=None, b=None, name1='data', name2=None):
"""
This function returns parity plot of regression result by Random
Forest.
Parameters
----------
X: an array or array-like predictors.
It should be scaled by StandardScaler.
y: an array or array-like ... | 13,517 |
def splitmod(n, k):
"""
Split n into k lists containing the elements of n in positions i (mod k).
Return the heads of the lists and the tails.
"""
heads = [None]*k
tails = [None]*k
i = 0
while n is not None:
if heads[i] is None:
heads[i] = n
if tails[i] is not... | 13,518 |
def cli(repo, **kwargs):
"""
Create a label.
The label color must be specified as a six-character hex code, e.g.,
`ff00ff`.
"""
kwargs["color"] = kwargs["color"].lstrip('#')
print_json(repo.labels.post(json=kwargs)) | 13,519 |
def dirname_to_prefix(dirname):
"""Return filename prefix from dirname"""
return os.path.basename(dirname.strip('/')).split("-", maxsplit=1)[1] | 13,520 |
def find_flats(flats, flat2_finder=find_flat2):
"""Find flat pairs."""
file1s = sorted([item.strip() for item in flats
if item.find('flat1') != -1])
return [(f1, flat2_finder(f1)) for f1 in file1s] | 13,521 |
def binary_accuracy(a,b):
"""
Calculate the binary acc.
"""
return ((a.argmax(dim=1) == b).sum().item()) / a.size(0) | 13,522 |
def add_ice_post_arrow_hq_lq_arguments2(parser):
"""Add quiver QV threshold to mark an isoform as high-quality or low-quality."""
# if isinstance(parser, PbParser):
# #parser = _wrap_parser(parser)
# arg_parser = parser.arg_parser.parser
# tcp = parser.tool_contract_parser
# tcp.... | 13,523 |
def dev_step(tset, train_m, test_m, net, dataset, args, nd_possible_rating_values):
"""
Evaluates model on a dev set
"""
batch_size = 256
#print("tset:",tset)
user_te = np.array(list(tset.keys()))
#print("user_te:",user_te)
user_te2 = user_te[:, np.newaxis]
#user_te2 = user_te
l... | 13,524 |
def clear_image_threads(serial_number):
"""
Stops all running threads and clears all thread dictionaries
:param serial_number: serial number of active stream deck
"""
global stop_animation
stop_animation_keys = list(stop_animation.keys())
for key in stop_animation_keys:
if key[0] =... | 13,525 |
def email_change_view(request, extra_context={},
success_url='email_verification_sent',
template_name='email_change/email_change_form.html',
email_message_template_name='email_change_request',
form_class=EmailChangeForm):
"""All... | 13,526 |
def check_is_pair(record1, record2):
"""Check if the two sequence records belong to the same fragment.
In an matching pair the records are left and right pairs
of each other, respectively. Returns True or False as appropriate.
Handles both Casava formats: seq/1 and seq/2, and 'seq::... 1::...'
an... | 13,527 |
def decompress_bzip2_from_hdu(hdu):
"""Decompress data in a PyFits HDU object using libz2.
"""
import bz2
data = hdu.data.field(0)
source_type = np.dtype(hdu.header['PCSRCTP'])
return (np.fromstring(bz2.decompress(data.tostring()),
dtype=source_type),
nump... | 13,528 |
def grid_values(grid):
"""
Convert grid into a dict of {square: char} with '123456789' for empties.
Args:
grid : string
A grid in string form.
Returns:
grid : dict
Keys are the boxes (e.g., 'A1').
Values are the values in each box (e.g., '8').
... | 13,529 |
def get_ftp_files(build_type, tag_name, config) -> List[ReleaseFile] :
"""!
@brief Gets file metadata for nightlies hosted on FTP, as determined by config["ftp"] attributes
@param [in] `build_type` Unknown str
@param [in] `tag_name` Github tag name of the release
@param [in] `config` conf... | 13,530 |
def trade_model(data, column='percentile_7Y', show=False, show_annual_invest=True):
"""
交易模型:
1、低估:买入、适中:保持不变、高估:卖出
"""
df = data.copy()
# 去除无滚动百分位数据
df.dropna(inplace=True)
# 找每个月第一个交易日
month_first_date = first_trade_date_in_month(df)
# 假设每个月第一个交易日增加5000元可支配
month_invest_con... | 13,531 |
def variables(i, o):
""" WRITEME
:type i: list
:param i: input L{Variable}s
:type o: list
:param o: output L{Variable}s
:returns:
the set of Variables that are involved in the subgraph that lies between i and o. This
includes i, o, orphans(i, o) and all values of all intermedia... | 13,532 |
def new_instance(): # display_callback=None):
"""
Create a new instance of Ghostscript
This instance is passed to most other API functions.
"""
# :todo: The caller_handle will be provided to callback functions.
display_callback=None
instance = gs_main_instance()
rc = libgs.gsapi_new... | 13,533 |
def ldns_resolver_dnssec_cd(*args):
"""LDNS buffer."""
return _ldns.ldns_resolver_dnssec_cd(*args) | 13,534 |
def print_dialog(line, speaker, show_speaker=False):
"""Print the line and speaker, formatted appropriately."""
if show_speaker:
speaker = speaker.title()
print('{} -- {}'.format(line.__repr__(), speaker))
else:
print(line) | 13,535 |
def spf_record_for(hostname, bypass_cache=True):
"""Retrieves SPF record for a given hostname.
According to the standard, domain must not have multiple SPF records, so
if it's the case then an empty string is returned.
"""
try:
primary_ns = None
if bypass_cache:
primary_... | 13,536 |
def remove_file_handlers():
"""Remove all file handlers from package logger."""
log = get_logger()
handlers = log.handlers
for handler in handlers:
if isinstance(handler, logging.FileHandler):
log.removeHandler(handler) | 13,537 |
def raw_to_df(
rawfile: os.PathLike,
n_channels: int = 2048,
fmt: np.dtype = ">i8",
order: str = "F",
) -> pd.DataFrame:
"""Read a binary raw data file, and returns a dataframe."""
bin_raw = read_file(rawfile, "rb")
dt = np.dtype(fmt)
np_data = np.frombuffer(bin_raw, dtype=dt)
bytes_... | 13,538 |
def check_number_of_entries(data, n_entries=1):
"""Check that data has more than specified number of entries"""
if not data.size > n_entries:
msg = (f"Data should have more than {n_entries} entries")
raise ValueError(msg) | 13,539 |
def cleanup():
"""Deactivates webpages and deletes html lighthouse reports."""
shutil.rmtree('.lighthouseci')
pattern = 'COMMUNITY_DASHBOARD_ENABLED = .*'
replace = 'COMMUNITY_DASHBOARD_ENABLED = False'
common.inplace_replace_file(FECONF_FILE_PATH, pattern, replace)
pattern = '"ENABLE_ACCOUNT_... | 13,540 |
def get_duplicated_members(first_name, last_name):
"""同じ名前の持つメンバーが存在するかどうか
:param first_name:
:param last_name:
:return:
"""
first_name = first_name.strip() if first_name else None
last_name = last_name.strip() if last_name else None
queryset = models.Member.objects.filter(
firs... | 13,541 |
def get_oauth_id():
"""Returns user email ID if OAUTH token present, or None."""
try:
user_email = oauth.get_current_user(SCOPE).email()
except oauth.Error as e:
user_email = None
logging.error('OAuth failure: {}'.format(e))
return user_email | 13,542 |
def check_for_publication(form, formsets, user_data):
"""
Run additional validation across forms fields for status LILACS-Express and LILACS
"""
valid = valid_descriptor = valid_url = True
# regex match starts with S (Serial) and ends with (as) analytic
regex_sas = r"^S.*as$"
Sas_record = re... | 13,543 |
def test_ChooseScraper():
"""
Tests the scraper for Amazon, Bestbuy, and Walmart URLs.
"""
# Testing Amazon case
scraper = Scraper()
stock_info, cost = scraper.ChooseScraper(amazon_URL)
assert stock_info == "Error Occurred" or stock_info == "In Stock"
# Testing BestBuy case
scraper ... | 13,544 |
def signal_handler(sig: int, frame) -> None:
"""Sets reaction to interrupt from keyboard"""
global LISTEN
if LISTEN:
print(' SIGINT received.\n Terminating...')
LISTEN = False
else:
print(f' It\'s can take some time due connection delay, '\
'please be patient') | 13,545 |
def _generate_var_name(prefix, field_name):
"""
Generate the environment variable name, given a prefix
and the configuration field name.
Examples:
>>> _generate_var_name("", "some_var")
"SOME_VAR"
>>> _generate_var_name("my_app", "some_var")
"MY_APP_SOME_VAR"
:param prefix: the pr... | 13,546 |
def VelocityPostProcessingChooser(transport):
"""
pick acceptable velocity postprocessing based on input
"""
tryNew = True
velocityPostProcessor = None
if transport.conservativeFlux is not None:
if (transport.mesh.parallelPartitioningType == 0 and transport.mesh.nLayersOfOverlap==0): #el... | 13,547 |
def get_node_hierarchical_structure(graph: nx.Graph, node: str, hop: int):
"""
explore hierarchical neighborhoods of node
"""
layers = [[node]]
curLayer = {node}
visited = {node}
for _ in range(hop):
if len(curLayer) == 0:
break
nextLayer = set()
for neigh... | 13,548 |
def svn_utf_cstring_from_utf8_string(*args):
"""svn_utf_cstring_from_utf8_string(svn_string_t src, apr_pool_t pool) -> svn_error_t"""
return _core.svn_utf_cstring_from_utf8_string(*args) | 13,549 |
def fitness_sum(element):
"""
Test fitness function.
"""
return np.sum(element) | 13,550 |
def Stepk(k, basetree=[]): # XXX. make sure basetree is passed as expected.
"""Try to solve the puzzle using assumptions.
k --> The step number. (1st step is solving exactly,
2nd step is solving using 1 assumption,
3rd step is solving using 2 assumptions and so on.)
Note: The assumpt... | 13,551 |
def load_handler(path, *args, **kwargs):
"""
Given a path to a handler, return an instance of that handler.
E.g.::
>>> load_handler('anthill.framework.core.files.uploadhandler.TemporaryFileUploadHandler', request)
<TemporaryFileUploadHandler object at 0x...>
"""
return import_string... | 13,552 |
def ghetto(RDnet, attIndex, param) :
"""assign proportion param[0] of nodes in net a value of param[1] at attIndex in a ghetto"""
#these should become parameters later on
per1 = param[0]
#per0 = 1.0-per1
curr1 = 0
#start with a seed
seedind = random.randint(1,len(RDnet.nodes()))
see... | 13,553 |
def validate_twilio_request():
"""Ensure a request is coming from Twilio by checking the signature."""
validator = RequestValidator(current_app.config['TWILIO_AUTH_TOKEN'])
if 'X-Twilio-Signature' not in request.headers:
return False
signature = request.headers['X-Twilio-Signature']
if 'SmsS... | 13,554 |
def paper_selection(text=[], keywords=[]):
"""
This function calculates the similarity between keywords or phrases relating a text. So it is possible to compare
several texts and keywords in once to see which text is the best relating special keywords. Also a plot is
generated, where it is possible to s... | 13,555 |
def six_records_sam(tmpdir):
"""Copy the six_records.sam file to temporary directory."""
src = py.path.local(os.path.dirname(__file__)).join(
'files', 'six_records.sam')
dst = tmpdir.join('six_records.sam')
src.copy(dst)
yield dst
dst.remove() | 13,556 |
def list_subpackages(package_trail,verbose=False):
""" package_trails = list_subpackages(package_trail)
returns a list of package trails
Inputs:
package_trail : a list of dependant package names, as strings
example: os.path -> ['os','path']
Outputs:
pac... | 13,557 |
def _get_out_of_bounds_window(radius, padding_value):
"""Return a window full of padding_value."""
return padding_value * np.ones((2 * radius + 1, 2 * radius + 1), dtype=int) | 13,558 |
def open_fw(file_name, encoding=ENCODING, encode=True):
"""Open file for writing respecting Python version and OS differences.
Sets newline to Linux line endings on Python 3
When encode=False does not set encoding on nix and Python 3 to keep as bytes
"""
if sys.version_info >= (3, 0, 0):
if... | 13,559 |
def covid_API_request(
location: str = "Exeter",
location_type: str = "ltla") -> dict[str]:
"""Requests current COVID data from the Cov19API for a given area.
Uses the Cov19API to request the most recent COVID data for
a given area. Returns data as a list of comma separated strings.
... | 13,560 |
def resize(img, height, width, is_flow, mask=None):
"""Resize an image or flow field to a new resolution.
In case a mask (per pixel {0,1} flag) is passed a weighted resizing is
performed to account for missing flow entries in the sparse flow field. The
weighting is based on the resized mask, which determines t... | 13,561 |
def render(ops_info, is_module):
"""Render the module or stub file."""
yield MODULE_PREAMBLE if is_module else STUBFILE_PREAMBLE
for cls_name, method_blocks in ops_info.items():
yield CLASS_PREAMBLE.format(cls_name=cls_name, newline="\n" * is_module)
yield from _render_classbody(method_bloc... | 13,562 |
def num_decodings2(enc_mes):
"""
:type s: str
:rtype: int
"""
if not enc_mes or enc_mes.startswith('0'):
return 0
stack = [1, 1]
for i in range(1, len(enc_mes)):
if enc_mes[i] == '0':
if enc_mes[i-1] == '0' or enc_mes[i-1] > '2':
# only '10', '20' ... | 13,563 |
def spot2Cmyk(spot, default=None):
"""Answers the CMYK value of spot color. If the value does not exist,
answer default of black. Note that this is a double conversion:
spot-->rgb-->cmyk
>>> '%0.2f, %0.2f, %0.2f, %0.2f' % spot2Cmyk(300)
'0.78, 0.33, 0.00, 0.22'
>>> # Nonexistent spot colors ma... | 13,564 |
def clean(text):
"""
Removes irrelevant parts from :param: text.
"""
# Collect spans
spans = []
# Drop HTML comments
for m in comment.finditer(text):
spans.append((m.start(), m.end()))
# Drop self-closing tags
for pattern in selfClosing_tag_patterns:
for m in patter... | 13,565 |
def get_offset(t0,t1,zone,station,gps):
"""
Determine UTC to local Local offset to be applied.
Parameters
----------
t0 : datetime
Starting timestamp
t1 : datetime
End timestamp
zone : str
Define timing zone, either Local or UTC
city : str
City where the sens... | 13,566 |
def notify_user(user, channel, message, url):
"""
Notifies a single user.
See notify().
"""
notify([user], channel, message, url) | 13,567 |
def my_render_template(html, **arguments):
"""Call render_template with comparison_types as one of the arguments.
:param string html: name of the template
:param **arguments: other arguments to be passed while rendering template
"""
arguments.setdefault(
'comparison_types', ComparisonType.g... | 13,568 |
def find_or_create_qualification(qualification_name, description,
must_be_owned=True):
"""Query amazon to find the existing qualification name, return the Id. If
it exists and must_be_owned is true but we don't own it, this prints an
error and returns none. If it doesn't exi... | 13,569 |
def delete_file(ssh: paramiko.SSHClient, file_name: str) -> None:
"""
Delete file named file_name via ssh.
:param ssh: sshclient with opened connection
:param file_name: name of file to be unlocked
"""
ssh.exec_command("rm -rf {}".format(file_name)) | 13,570 |
def generate(root_node, link_types, identifier, ancestor_depth, descendant_depth, process_out, process_in, engine,
verbose, output_format, show):
"""
Generate a graph from a ROOT_NODE (specified by pk or uuid).
"""
# pylint: disable=too-many-arguments
from aiida.tools.visualization impo... | 13,571 |
def hard_to_soft(Y_h, k):
"""Converts a 1D tensor of hard labels into a 2D tensor of soft labels
Source: MeTaL from HazyResearch, https://github.com/HazyResearch/metal/blob/master/metal/utils.py
Args:
Y_h: an [n], or [n,1] tensor of hard (int) labels in {1,...,k}
k: the largest possible labe... | 13,572 |
def find_negations(doc, neg_comma=True, neg_modals=True, debug=False):
"""
Takes as input a list of words and returns the positions (indices) of the words
that are in the context of a negation.
:param list doc: a list of words (strings)
:param bool neg_comma: if True, the negation context ends on a... | 13,573 |
def test_status_format(input, expected):
""" test various formatting cases embodied in utils.status_messages.status_format """
assert status_format(input) == expected | 13,574 |
def apply_all_menus(output, manual_change, dates):
"""Apply the change to all dates in the applicable range. If no menu exist for a day, it will be created."""
print(f"Matching all menus from {manual_change.resto} between {manual_change.start} to {manual_change.end}")
print("================================... | 13,575 |
def int_pow(base: int, power: int, modulus: int=None, safe: bool=True):
"""
Calculate `base` raised to `power`, optionally mod `modulus`
The python standard library offers the same functionality,
and this function exists only as a proof of Concept.
This function only aims to support positive intege... | 13,576 |
def add_webhook(doc, session):
"""Use Mandrill API to add the webhook"""
r = session.post(get_api_url("/webhooks/add.json"), data=json.dumps({
"key": doc.password,
"url": get_webhook_post_url(),
"description": _("Frappé Mandrill Integration"),
"events": [
# subscribe to these events
# NOTE: 'deferral' e... | 13,577 |
def iter_compare_dicts(dict1, dict2, only_common_keys=False, comparison_op=operator.ne):
"""
A generator for comparation of values in the given two dicts.
Yields the tuples (key, pair of values positively compared).
By default, the *difference* of values is evaluated using the usual != op, but can be ... | 13,578 |
def truncate_decimal_places(value: decimal.Decimal, places: int = 1) -> float:
"""
Truncate a float (i.e round towards zero) to a given number of decimal places.
NB: Takes a decimal but returns a float!
>>> truncate_decimal_places(12.364, 1)
12.3
>>> round_decimal_places(-12.364, 1)
-12.3... | 13,579 |
def site_url(self, url):
"""
Return the fully qualified URL for the given URL fragment.
"""
try:
# In Django < 1.9, `live_server_url` is decorated as a `property`, but
# we need to access it on the class.
base_url = self.testclass.live_server_url.__get__(self.testclass)
exce... | 13,580 |
def myisinteger(
num: int) -> bool:
"""
Checks if num is an integer
"""
val = 1 if num == floor(num) else 0
return val | 13,581 |
def _get_timeunit(min_time: pd.Timestamp, max_time: pd.Timestamp, dflt: int) -> str:
"""Auxillary function to find an appropriate time unit. Will find the
time unit such that the number of time units are closest to dflt."""
dt_secs = {
"year": 60 * 60 * 24 * 365,
"quarter": 60 * 60 * 24 * 9... | 13,582 |
def get_resource_path(relative_path):
"""
relative_path = "data/beach.jpg"
relative_path = pathlib.Path("data") / "beach.jpg"
relative_path = os.path.join("data", "beach.jpg")
"""
rel_path = pathlib.Path(relative_path)
dev_base_path = pathlib.Path(__file__).resolve().parent.parent
base_p... | 13,583 |
def data_sample(df, x, y, group_number, quantile):
"""
分组选点法
x: 分组变量
y: 取值变量
"""
group_width = (np.max(df[x]) - np.min(df[x])) / group_number # 分组宽度
x_group = np.arange(np.min(df[x]), np.max(df[x]), group_width) # 分组的X
# 选取每组中设定的分位数的点, 对点数大于零的组选点
if len(quantile) == 3:
... | 13,584 |
def spec_col_file(filename):
"""
Specify an INI file with column names to be automatically used in plots.
The column-label-pairs must be placed under the INI section `[Columns]`.
:param filename: A path to the INI file.
"""
cfg = ConfigParser()
cfg.read(filename, encoding='utf8')
_col_l... | 13,585 |
def index(request):
""" Shows all challenges related to the current user """
profile = request.user.get_profile()
chall_user = profile.get_extension(ChallengeUser)
challs = ChallengeGame.get_active(chall_user)
played = ChallengeGame.get_played(chall_user)[:10]
if not chall_user.is_eligible():
... | 13,586 |
def hansen(threshold, geojson, begin, end, logger):
"""For a given threshold and geometry return a dictionary of ha area.
The threshold is used to identify which band of loss and tree to select.
asset_id should be 'projects/wri-datalab/HansenComposite_14-15'
Methods used to identify data:
Gain band ... | 13,587 |
def rectangluarMask(image):
"""
this function will take an image as an input and created a rectangluar mask(image sized) and in the center of canvas
"""
mask = np.zeros(image.shape[:2], dtype = 'uint8')
(cX, cY) = (image.shape[1]//2, image.shape[0]//2)
cv2.rectangle(mask, (cX-75, cY-75), (cX+75, cY+75), 255, -1)
... | 13,588 |
def get_artist_listen_for_change_streams(artist: Artist=None):
"""
Computation steps:
1. Define start and end dates
2. Create stream filters for the current artist
3. aggregate the streams from the Model
4. Return just the number (maybe a dict idk)
"""
# Validate argument data types
... | 13,589 |
def flip_dict(d):
"""Returns a dict with values and keys reversed.
Args:
d: The dict to flip the values and keys of.
Returns:
A dict whose keys are the values of the original dict, and whose values
are the corresponding keys.
"""
return {v: k for k, v in d.items()} | 13,590 |
def branch_exists(branch: str) -> bool:
""" Check if the branch exists in the current Git repo. """
try:
subprocess.check_call(
["git", "rev-parse", "--quiet", "--verify", branch],
stdout=subprocess.DEVNULL,
)
return True
except subprocess.CalledProcessError:
... | 13,591 |
def assert_equal(actual: Literal["oim"], desired: Literal["oim"]):
"""
usage.statsmodels: 2
"""
... | 13,592 |
def has_sample(args):
"""Returns if some kind of sample id is given in args.
"""
return args.sample or args.samples or args.sample_tag | 13,593 |
def get_search_selection(config: models.Config) -> models.Config:
"""Gets search criteria for search mode"""
search_selection: models.SearchSelection = models.SearchSelection()
print('\nPlease select what system you want to search')
print('Press Enter to do a general site wide search')
helpers.print... | 13,594 |
def make_key_type(func: Callable[..., Any]) -> Type[CallKey]:
"""Construct a type representing a functions signature."""
sig = inspect.signature(func)
# make a format string that unpacks and names the parameters nicely
repr_fmt = (
(
func.__name__
if "<locals>" in func._... | 13,595 |
def gen_string(prop=None):
"""
Generate String value
:param prop: dict
Examples: {'minLength': 10, 'maxLength': 154}
{'pattern': '^\\d+\\w*$'}
"""
if not prop:
prop = {}
min_length = prop.get("minLength", 1)
max_length = prop.get("maxLength", 1024)
pattern = pro... | 13,596 |
async def test_error_fetching_new_version_bad_json(hass, aioclient_mock):
"""Test we handle json error while fetching new version."""
aioclient_mock.post(updater.UPDATER_URL, text="not json")
with patch(
"homeassistant.helpers.system_info.async_get_system_info",
Mock(return_value=mock_coro(... | 13,597 |
def process_documents(args: dict[str, bool]) -> None:
"""Process the documents.
Args:
args (dict[str, bool]): The processing steps based on CLI arguments.
"""
cfg.glob.logger.debug(cfg.glob.LOGGER_START)
# Connect to the database.
db.driver.connect_db()
# Check the version of the ... | 13,598 |
def standardize_data(data, eps=None):
"""
Standardize each image data to have zero mean and unit standard-deviation (z-score)
Inputs:
data: [np.ndarray] unnormalized data
Outputs:
data: [np.ndarray] normalized data
"""
if eps is None:
eps = 1.0 / np.sqrt(data[0,...].size)
data, orig_shape = re... | 13,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.