content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def create_discriminator_inputs(images, conditional_vectors):
"""
識別器用入力画像(画像+条件画像)を生成する。
Args:
images: 画像
conditional_vectors: 条件ベクトル
index: image_seqから取得するデータのインデックス
Returns
画像+条件画像を統合したテンソル (B, H, W, A + C)
B: バッチサイズ。images.shape[0]
H: 画像の高さ。images... | 75a14931106c05dd4007a0963c4152f0b54b04d5 | 3,635,700 |
def add_to_master_list(single_list, master_list):
"""This function appends items in a list to the master list.
:param single_list: List of dictionaries from the paginated query
:type single_list: list
:param master_list: Master list of dictionaries containing group information
:type master_list: li... | 4b4e122e334624626c7db4f09278b44b8b141504 | 3,635,701 |
from typing import Optional
def weight_by_attr(
attr: str, prev_edge: Optional[models.Edge], edge: models.Edge
) -> float:
"""
Generic weight function to retrieve a value from an edge.
"""
return getattr(edge, attr) | 292ab3d8cd551122eb57663bdc20f0aed288dd43 | 3,635,702 |
from typing import Union
import warnings
def check_if_porous(structure: Structure, threshold: float = 2.4) -> Union[bool, None]:
"""Runs zeo++ to check if structure is porous according to the CoRE-MOF
definition (PLD > 2.4, https://pubs.acs.org/doi/10.1021/acs.jced.9b00835)
Args:
structure (Struc... | a6af20bcb3273b4d516309fbe156b997db7e30dd | 3,635,703 |
import os
def load_vlay( #load a layer from a file
fp,
providerLib='ogr',
logger=mod_logger):
"""
what are we using this for?
see instanc emethod
"""
log = logger.getChild('load_vlay')
assert os.path.exists(fp), 'requested file does not exist: %s'%fp
... | b3794e219dcf3c580dbe8123cfca2c75d5af9e57 | 3,635,704 |
def order_node_list(tree):
"""
Sorts a list of node dict from a LightGBM instance. Key `tree_structure` is
specific for LightGBM.
Parameters
----------
tree : list,
Unsorted list of node dicts
Returns
-------
ordered_node_list : list,
Ordered list of node dicts com... | 812dcaeb96e4c0a55dece5e678fd86d27f42ddf0 | 3,635,705 |
import logging
import traceback
import json
def teardown_request_wrap(exception):
"""
Prints tracebacks and handles bugs
"""
if exception:
logging.error(traceback.format_exc())
return json.dumps({"result":None, 'error':{'message':'Invalid request'}, 'id':1}) | eaf4a6ebc75a5166704794b0c028a4410f21cfdc | 3,635,706 |
import logging
def sanitize_parameters(func):
"""Sets any queryparams in the kwargs"""
@wraps(func)
def wrapper(*args, **kwargs):
try:
logging.info(f'[middleware] [sanitizer] args: {args}')
myargs = dict(request.args)
# Exclude params like loggedUser here
... | b76d4361e73671130b03463ac74144a3a2111bef | 3,635,707 |
def build_render_setup(cfg):
"""Build information struct about the rendering backup from a configuration.
This performs type conversion to the expected types. Paths contained in
cfg are expected to be alread expanded. That is, it should not contain
global variables or other system dependent abbreviatio... | e7631ccbda98a99d1db961b3bbcbcf36d1b7b3ad | 3,635,708 |
def generate_coupled_image_from_self(img, out_img, noise_amp=10):
"""
Generates an input image for siam by concatenating an image with a transformed version of itself
"""
def __synthesize_prev_img(in_img, noise_amp=10):
"""Synthesizes previous frame by transforming the input image
... | 778de50045b2b8932453c61863923bb9d2127ad6 | 3,635,709 |
def pca_preprocess(df, pca_components):
"""Preprocess the given dataframe using PCA"""
# Drop rows
df.dropna(axis=0, inplace=True)
# Separate features and targets
X = df.drop('ASPFWR5', axis=1)
y = df['ASPFWR5']
# Dimensionality reduction with principal component analysis
... | b09506efb52502aacbb66a9b80a6d2abe55f84d9 | 3,635,710 |
from datetime import datetime
def add_nonce(func):
"""Helper function which adds a nonce to the kwargs dict"""
@wraps(func)
def inner(*args, **kwargs):
if "nonce" not in kwargs:
kwargs["nonce"] = int(datetime.datetime.utcnow().timestamp() * 1000)
return func(*args, **kwargs)
... | 9138066e65416dab677c42ac8a6106f4dc421832 | 3,635,711 |
from typing import Dict
from typing import Any
import os
import toml
def build_train_dict(config_file: str, task: str) -> Dict[str, Any]:
"""
Read the configuration file given by the user.
If it is a TOML file, ensures that the format corresponds to the one in resources.
Args:
config_file: pat... | cffccce5763596323e49a2633c70eebdbb96a1e8 | 3,635,712 |
def morse_encode(string):
"""Converts a string to morse code"""
words = [morse_encode_word(word) for word in string.split(' ')]
return ' '.join(words) | aea0ffc0172096f8507c16ee5f7fc9e75f36c596 | 3,635,713 |
import glob
import os
def examples():
"""Load example paths."""
return [(loader(path), path) for path in glob.glob(os.path.join(RESOURCE_DIR, "examples", "*.json"))] | 2e4aefd01f783d94d30418ccd302c63deead2022 | 3,635,714 |
def TIMES_cleanup (file, Model_Module):
"""Cleans data genrated by Oasis TIMES and returns a dataframe witht he DTXSID of the parent compound and InChI key of each metabolite"""
"""The Model_Module argument should be a string to designate the model used for metabolism (e.g., TIMES_RatLiver S9, TIMES_RatInVivo""... | ae5d566ad606ea74d7209b8304693238c71981e0 | 3,635,715 |
import random
def generate_key():
"""Generate an key for our cipher"""
shuffled = sorted(chars, key=lambda k: random.random())
return dict(zip(chars, shuffled)) | dc0cc2c5ac063f0b0e5f7b53445a43680d34be8f | 3,635,716 |
import os
import re
def get_sdkconfig_value(sdkconfig_file, key):
"""
Return the value of given key from sdkconfig_file.
If sdkconfig_file does not exist or the option is not present, returns None.
"""
assert key.startswith('CONFIG_')
if not os.path.exists(sdkconfig_file):
return None
... | d8f11dec3406d5fc166883d99bc3f42ca4eb6483 | 3,635,717 |
def unmatched(match):
"""Return unmatched part of re.Match object."""
start, end = match.span(0)
return match.string[:start] + match.string[end:] | 6d34396c2d3c957d55dbef16c2673bb7f571205c | 3,635,718 |
def cubicgw(ipparams, width, etc = []):
"""
This function fits the variation in Gaussian-measured PRF half-widths using a 2D cubic.
Parameters
----------
x1: linear coefficient in x
x2: quadratic coefficient in x
x3: cubic coefficient in x
y1: linear coefficient in y
y2: quadratic coeffici... | 334be9d8dc8baaddf122243e4f19d681efc707cf | 3,635,719 |
import argparse
def _make_parser():
""" Generates argument parser with all necessarry parameters.
:returns script's arguments (host, port, index, type, id,
searchserver, server, stdin, pipeline)
:rtype argparse.ArgumentParser
"""
p = argparse.ArgumentParser(description=__doc__,
... | 30e4daf3ef65684c57f918716bcfd61eebdefffe | 3,635,720 |
def main():
"""
This function displays all the gui elements of the music recommender system
Parameters:
-
Returns:
df_list (DataFrame): the list of input audio entered by the user
"""
fileslist... | dcde78271a7358848b0947d2ad0674d15fcf9ae1 | 3,635,721 |
def get_columns_by_type(df, req_type):
"""
get columns by type of data frame
Parameters:
df : data frame
req_type : type of column like categorical, integer,
Returns:
df: Pandas data frame
"""
g = df.columns.to_series().groupby(df.dtypes).groups
type_dict = {k.name: v for k, v ... | aeedea92fbfb720ca6e7a9cd9920827a6ad8c6b0 | 3,635,722 |
def get_total(lines):
"""
This function takes in a list of lines and returns
a single float value that is the total of a particular
variable for a given year and tech.
Parameters:
-----------
lines : list
This is a list of datalines that we want to total.
Returns:
--------
... | 284f8061f3659999ae7e4df104c86d0077b384da | 3,635,723 |
def get_ipv6_by_ids(ip_ids):
"""Get Many Ipv6."""
networks = list()
for ip_id in ip_ids:
networks.append(get_ipv6_by_id(ip_id))
return networks | 29511fca93063921ace5019225c03ede518b4c0d | 3,635,724 |
def box(t, t_start, t_stop):
"""Box-shape (Theta-function)
The shape is 0 before `t_start` and after `t_stop` and 1 elsewhere.
Args:
t (float): Time point or time grid
t_start (float): First value of `t` for which the box has value 1
t_stop (float): Last value of `t` for which the ... | 8f4f0e57323f38c9cfa57b1661c597b756e8c4e7 | 3,635,725 |
from datetime import datetime
import os
import multiprocessing
def updateBaselines(product, date:datetime, n_workers=20, block_scale_factor= 1, time=False) -> dict:
"""Updates anomaly baselines
***
Parameters
----------
product:str
date:datetime
n_workers:int
block_scale_factor:int
... | d731ca3f8af79b279a5f995f51ef110c4952c453 | 3,635,726 |
import os
import collections
import re
def analyze_integration_target_dependencies(integration_targets): # type: (t.List[IntegrationTarget]) -> t.Dict[str, t.Set[str]]
"""Analyze the given list of integration test targets and return a dictionary expressing target names and the target names which depend on them."... | affbfb081bbbd4d40a2c1dd21f047d139b54dc77 | 3,635,727 |
import numpy
def newton_cotes(order, domain=(0, 1), growth=False, segments=1):
"""
Generate the abscissas and weights in Newton-Cotes quadrature.
Newton-Cotes quadrature, are a group of formulas for numerical integration
based on evaluating the integrand at equally spaced points.
Args:
o... | 72c4afcd7dce50752f349556356db000addba649 | 3,635,728 |
def transpose(a, axes=None):
"""transpose(a, axes=None) returns array with dimensions permuted
according to axes. If axes is None (default) returns array with
dimensions reversed.
"""
# if axes is None: # this test has been moved into multiarray.transpose
# axes = arange(len(array(a).shape))[... | 80fd37c9ab9e48d9bddc95eb8ae32f6d48250b6a | 3,635,729 |
def find_next_prime(N: int) -> int:
"""Find next prime >= N
Parameters
----------
N : int
Starting point to find the next prime >= N.
Returns
-------
int
the next prime found after the number N
"""
def is_prime(n):
if n % 2 == 0:
return False
... | 8648b3583e84a520eca0435cf6ebeb5a939af2fd | 3,635,730 |
def in_16(library, session, space, offset, extended=False):
"""Reads in an 16-bit value from the specified memory space and offset.
Corresponds to viIn16* function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:para... | af7f28001faed46e52af0645462cd429e5ca7eb8 | 3,635,731 |
from typing import Pattern
def match_head(subject, pattern):
"""Checks if the head of subject matches the pattern's head."""
if isinstance(pattern, Pattern):
pattern = pattern.expression
pattern_head = get_head(pattern)
if pattern_head is None:
return True
if issubclass(pattern_hea... | cd1b418635dd9a974a0ca4643641ad97add0ed7d | 3,635,732 |
def update(number):
"""
update() : Update document in Firestore collection with request body.
Ensure you pass a custom ID as part of json body in post request,
e.g. json={'id': '1', 'title': 'Write a blog post today'}
"""
try:
todo_ref = user_ref.document(number).collection("... | acb36cb6bcd066af635c97030bb9d843159869b0 | 3,635,733 |
import json
import time
def sfn_result(session, arn, wait=10):
"""Get the results of a StepFunction execution
Args:
session (Session): Boto3 session
arn (string): ARN of the execution to get the results of
wait (int): Seconds to wait between polling
Returns:
dict|None: Di... | ba8a80e81aa5929360d5c9f63fb7dff5ebaf91f3 | 3,635,734 |
def forum_latest_user_posts(parser, token):
"""
{% forum_latest_user_posts user [number] as [context_var] %}
"""
bits = token.contents.split()
if len(bits) not in (2, 3, 5):
raise TemplateSyntaxError('%s tag requires one, two or four arguments' % bits[0])
if bits[3] != 'as':
rais... | 3138f7f43a7cc2b45d7d05ba82cc74bb512dcc29 | 3,635,735 |
import argparse
def parse_args(args):
"""Parse command line arguments.
"""
parser = argparse.ArgumentParser(description='YouTube Subscription Search')
parser.add_argument(
'-s', '--secrets-file', default='client_id.json',
help='Client secret file. See README.md on how to get this file... | 8d1bacab9754ada84fe0a3da0b229e6ab30e3550 | 3,635,736 |
def PureMultiHeadedAttention(x, params, num_heads=8, dropout=0.0,
mode='train', **kwargs):
"""Pure transformer-style multi-headed attention.
Args:
x: inputs ((q, k, v), mask)
params: parameters (none)
num_heads: int: number of attention heads
dropout: float: dropout rat... | 32fb6aee5c82b6eaa5aae4cab3b98fb0b5cc423b | 3,635,737 |
def validate_options(options):
"""
Validate the options and return bool.
:param options: options to validate
:type options: dict
:rtype: bool
"""
pywikibot.log('Options:')
notice_keys = [
'email_subject',
'email_subject2',
'email_text',
'email_text2',
... | dade1084873dc9eec95a3be364560d115bbb670c | 3,635,738 |
import requests
import os
def verify() -> bool:
"""Verify access to the NFVIS Device."""
print("==> Verifying access to the NFVIS Device Environment.")
nip, url, login, password = nvfis_getgcred()
s = requests.Session()
s.auth = (login, password)
s.headers = ({'Content-type': 'application/vnd... | 4d446ced8208314f51a98d2cb3eab90812cbd1cf | 3,635,739 |
from typing import List
from typing import Dict
from typing import Any
import logging
def main(
domain: InnerEnv,
planner: planning_types.Planner,
belief: belief_types.Belief,
runs: int,
logging_level: str,
) -> List[Dict[str, Any]]:
"""plan online function of online planning
Handles call... | e45d8aa43933bd85779d48572e4db327003887ec | 3,635,740 |
import os
def convert_to_target(filepath, data_ann_path_out, target_map):
"""
Saves the image as a .png in the data path
"""
if not os.path.isfile(filepath):
print("No such file found: ", filepath)
return False
ann_file = os.path.basename(filepath)
# open the image
mask ... | 6633c311de2b4fda12ae2fabca1bee43c8b78b1b | 3,635,741 |
from typing import Union
from typing import Any
def format_color(
color: Union[ColorInputType, Any],
warn_if_invalid: bool = True
) -> Union[ColorType, Any]:
"""
Format color from string, int, or tuple to tuple type.
Available formats:
- Color name str: name of the color to use, e.g. ... | e4b5413ce96824e7e4990d9e78ec36ad1690a400 | 3,635,742 |
from typing import Optional
def is_yaml_requested(
content_type: str = None,
proto: ExtendedProto = None,
path_suffix: Optional[str] = None,
) -> bool:
"""Checks whether YAML is requested by the user, depending on params."""
is_yaml = False
if content_type is not None:
is_yaml = ("yaml... | 93ace7639b00430d7f3731a0a54792037edff4cc | 3,635,743 |
def _pqs_in_range(dehn_pq_limit, num_cusps):
"""
Return an iterator. This iterator, at each step, returns a
tuple. The contents of this tuple are num_cusps other tuples, and
each of these is of the form (p,q), where 0 <= p <= dehn_pq_limit,
-dehn_pq_limit <= q <= dehn_pq_limit, and gcd(p,q) <= 1.
... | fe28e43823c6b2510ed80294d4b7ed4bed02ed54 | 3,635,744 |
def _units_defaults(calendar, has_year_zero=None):
"""
Set calendar specific default units as 'days since reference_date'
Day 0 of *excel* and *excel1900* starts at 1899-12-31 00:00:00.
Day 0 of *excel1904* starts at 1903-12-31 00:00:00.
Decimal calendars *decimal*, *decimal360*, *decimal365*, an... | 06b7cbc78ad49bdfc24324249c89c49cc7a63723 | 3,635,745 |
def submit_a_feed(request):
"""
用户添加一个自定义的订阅源
"""
feed_url = request.POST.get('url', '').strip()[:1024]
user = get_login_user(request)
if feed_url:
host = get_host_name(feed_url)
if host in settings.ALLOWED_HOSTS:
rsp = add_self_feed(feed_url)
elif settings.... | bf9d4abc850c8012e7c5f56a18df6880b0ea5b04 | 3,635,746 |
def check_existing_credendtials(account_Name):
"""
Function that check if a Credentials exists with that account name and return a Boolean
"""
return Credentials.credential_exist(account_Name) | 31a0edad670b15c9e6e45175c24a55705e9eac4c | 3,635,747 |
import os
def hash_paths(paths, log_interval):
"""Returns a map of the base64 hash to the filename for all paths in path."""
output = {}
count_since_log = 0
for path in paths:
output[hash_file(path)] = os.path.basename(path)
count_since_log += 1
if count_since_log >= log_inter... | 97d210473344dbd8612389366e7648ef125c3fc5 | 3,635,748 |
def scmplx(p,a,b):
"""
p is a string designating a type, either scalar_f or scalar_d.
"""
if p == 'scalar_f':
return vsip_cmplx_f(a,b)
elif p == 'scalar_d':
return vsip_cmplx_d(a,b)
else:
assert False,'Type %s not defined for cmplx.'%p | 56773eaded2b676c09cdd3b93ef320d9e8a615b3 | 3,635,749 |
import json
def ips_description(request):
"""See :class:`bgpranking.api.get_ips_descs`"""
asn = request.get('asn')
block = request.get('block')
if asn is None or block is None:
return json.dumps({})
return json.dumps(bgpranking.get_ips_descs(asn, block,
request.get('d... | 47318917517cd519e646e477cd933bd639aa4ceb | 3,635,750 |
def handle_msg(msg: dict) ->list:
""" Handler for message request object. Logs message and returns list of responses."""
msg_alert(msg['From'], msg['Body'])
msg, lol = parse_msg(msg)
if lol is not None:
resp = lol
elif lol is None:
resp = get_response(msg)
log_msg = [
{... | d3f751dacf2594ae1aa691c4d4f9e58ee41b4f44 | 3,635,751 |
def create_app(register_blueprints=True):
"""Function to instantiate, configure, and return a flask app"""
app = Flask(__name__, instance_relative_config=True)
app.config.from_object('app.default_config') # default config
# app.config.from_pyfile('application.cfg.py') # server config file, do not inc... | 459c776e713f6e4c4157d9599a625235565c50c8 | 3,635,752 |
def RoleAdmin():
"""超级管理员"""
return 1 | 78a4fce55fa0fb331c0274c23213ae72afe7184f | 3,635,753 |
import pyproj
from pyproj.exceptions import DataDirError
def _get_proj_info():
"""Information on system PROJ
Returns
-------
proj_info: dict
system PROJ information
"""
try:
data_dir = pyproj.datadir.get_data_dir()
except DataDirError:
data_dir = None
blob = ... | 4e6d7b3f1375f32a5fe4dd106b8e9ac79f29912f | 3,635,754 |
def run_program(intcodes):
"""run intcodes, which are stored as a dict of step: intcode pairs"""
pc = 0
last = len(intcodes) - 1
while pc <= last:
if intcodes[pc] == 1:
# add
if pc + 3 > last:
raise Exception("out of opcodes")
arg1 = intcodes[... | e87343483abddffd9508be6da7814abcbcd59a79 | 3,635,755 |
from re import T
def concat(lst, cat_symb=None, append_to_end=False):
"""Concatenates `lst` of Tensors, optionally with a join symbol.
Args:
lst: list of Tensors to concatenate.
cat_symb: concatenation symbol.
append_to_end: if set to ``True``, it will add the `cat_symb` to the end
... | c8a17b7c44abd3f41ca57097782a2707ba9aaa63 | 3,635,756 |
def find_mcs(mols):
"""Function to count the number of molecules making ito the end of the test"""
out_mols = ROMol_Vect()
while mols.hasNext():
molobj = mols.next()
rdmol, molobj = get_or_create_rdmol(molobj)
# Add this mol to that vector
out_mols.add(rdmol)
# Now find t... | b1ca9cba06187918559bd5ce6b13319b793c4fc6 | 3,635,757 |
def to_numpy(tensor):
"""Convert 3-D torch tensor to a 3-D numpy array.
Args:
tensor: Tensor to be converted.
"""
return tensor.transpose(0, 1).transpose(1, 2).clone().numpy() | 034e016caccdf18e8e33e476673884e2354e21c7 | 3,635,758 |
def calib_constants(det, exp=None, ctype='pedestals', run=None, time_sec=None, vers=None, url=cc.URL) :
"""Returns calibration constants and document with metadata for specified parameters.
To get meaningful constants, at least a few parameters must be specified, e.g.:
- det, ctype, time_sec
-... | bb84690d11747c5bcc408ae7ccef05b62e0267ba | 3,635,759 |
import time
def is_cluster_healthy(admin, zk, retries=10, retry_wait=30):
"""Return true if cluster is healthy."""
retries_left = retries
while retries_left:
md = _request_meta(admin)
if md is not None and not _unhealthy(md, zk):
logger.info("Cluster is healthy!")
r... | 2995067e30664a616cc48409b6597bf1a80f0067 | 3,635,760 |
def load_data(loc):
""" Load in the csv file """
df = pd.read_csv(loc, engine = "python", encoding = "utf-8")
df.fillna("")
df = np.asarray(df)
return df | b59cc344cdc2ad2805f7d237e22c65c8b2f7300c | 3,635,761 |
import os
def listdir(folder, suffix):
""" Output the path of files in the folder with specific suffix"""
list_path = []
for root, _, files in os.walk(folder, followlinks=True):
for f in files:
if f.endswith(suffix):
list_path.append(osp.join(root, f))
return list_p... | 6762a7fb0a8531af0de2aa9c3306c85b0306d820 | 3,635,762 |
def clif_deps_to_cclibs(labels):
"""Gets the cc_library name for each of label as a list."""
return [_clif_to_lib(name, PYCLIF_CC_LIB_SUFFIX) for name in labels] | aeb85cd716282099b9efc36efd6dcd6cd49413ba | 3,635,763 |
def _get_cache_filename(year=2020):
"""Returns the `Path` to the COBS data file for a given year."""
return CACHEDIR / f'cobs{year}.feather' | 70f989165b6e3e10604a468d06f5f565e499ab28 | 3,635,764 |
def get_critical_hours_end(critical_ffmc: float, solar_noon_ffmc: float, critical_hour_start: float):
""" Returns the hour of day (on 24H clock) at which the hourly FFMC drops below
the threshold of critical_ffmc.
Should only be called if critical_hour_start is not None.
"""
if critical_hour_start i... | f50bfca5769bbe36d597ad1ff42d73c8aa4b4bae | 3,635,765 |
def dolpc(x, model_order=8):
"""
Function dolpc computes the autoregressive model from spectral magnitude samples.
@param x: Critical band filters.
@param model_order: Order of model. Default is 8.
@returns: Autoregressive model from spectral magnitude samples.
"""
num_bands, num_frames... | 81e008bd00fd5f8efa3f55df1e310eb52727aa85 | 3,635,766 |
def filter_domains(domains, by="evalue", coverage_pct=0.5, tolerance_pct=0.1):
"""Filter overlapping Domain objects and test adjcency rules.
Adjacency rules are tested again here, in case they are missed within overlap
groups. For example, the NRPS-para261 domain is not always entirely contained by
a c... | b980c69bf3309628cbaf3d91c59b77b33b3be4e2 | 3,635,767 |
def _replicate_and_maybe_restore_latest_checkpoint(
unreplicated_optimizer_state,
unreplicated_params,
unreplicated_batch_stats,
unreplicated_training_metrics_grabber,
train_dir,
use_deprecated_checkpointing):
"""Restore from the latest checkpoint, if it exists."""
uninitialized_global_step ... | a49b0b74d4a1fdd6ed8cae715249ab8febd7c352 | 3,635,768 |
def minkowskiSum(obj1, obj2):
"""
Minkowski sum of two polygon objects
Args:
obj1, obj2: (n,2) array of corner point
Return:
poly: (n,2) array of minkowski polygon vertices centered at (0, 0)
bound: [min_x, min_y] max/min signed distances from vertices
... | 7000676601c40c7e32961f26a12c2c79c2c592bd | 3,635,769 |
def get_rotated_image_from_contour(img, contour, rotation=90):
""" Returns a rotated version of img based on cv2.minAreaRect of contour.
First side, (i.e most left to top edge) is always "Width" from minAreaRect.
If our width > height, we know we have the sheet rotated to the right.
We nee... | 5351303dbc9d786b32c1760ccadfce81e1174b70 | 3,635,770 |
def fix_dataset_dims(d):
"""Given one of the dataset files given by the organizers, fix its
dimensions so its easier to concatenate and use with xr.open_mfdataset.
Arguments:
d. xr.Dataset. The dataset you get when you open one of the provided files.
"""
month = int(d.forecast_time[0].dt.mon... | 323aa2c89cfcf124e06d9efa97c4d61775680bdf | 3,635,771 |
def prettyprint_xml(element):
"""
A rough and dirty way to prettyprint an Element with indention.
:param lxml.etree._Element element: The Element or ElementTree to format.
:rtype: str
:returns: A prettyprinted representation of the element.
"""
return etree.tostring(element, pretty_print=T... | 58749d409c3735b021045ba614888858d12b6651 | 3,635,772 |
import sys
def load_vimba_lib(vimba_project: str):
""" Load shared library shipped with the Vimba installation
Arguments:
vimba_project - Library name without prefix or extension
Return:
CDLL or WinDLL Handle on loaded library
Raises:
VimbaSystemError if given library could ... | dd27ced38906f9922594035564e8b66c007e3d34 | 3,635,773 |
def decorator(IterativeReconAlg, name=None, docstring=None):
"""
Calls run_main_iter when parameters are given to it.
:param IterativeReconAlg: obj, class
instance of IterativeReconAlg
:param name: str
for name of func
:param docstring: str
other documentation that may need ... | 0c7224ea3d58c367d8b7519f7f8ba4d68c00076e | 3,635,774 |
from typing import Any
import json
def read_json_file(filepath: str) -> Any:
"""Read JSON from a file.
Args:
filepath (str): Path to file
Returns:
Any: The parsed JSON
"""
with open(filepath, 'r') as json_file:
data = json.load(json_file)
return data | b4b492aa796b55b81dc8f6a8b91713fe1f00ecd4 | 3,635,775 |
def penalized_loss(loss_func,
model,
inputs,
targets,
output_regularization,
l2_regularization = 0.0,
use_dnn = False):
"""Computes penalized loss with L2 regularization and output penalty.
Args:
l... | c1e8403b274cef6d37ed419b8ba7ed2dc0e30845 | 3,635,776 |
import glob
from typing import Optional
from pathlib import Path
import json
import os
def load_corpus(corpus_id: str, download_if_missing=False) -> Optional[list]:
"""Loads a corpus that has previously been downloaded
Parameters
----------
corpus_id: str
The id of the corpus to load.
dow... | 02798717b05a45d4bd0fb6d48525073a56ddffbb | 3,635,777 |
def tx_deserialize( tx_hex ):
"""
Given a serialized transaction, return its inputs, outputs, locktime, and version
Each input will have:
* txid: string
* vout: int
* [optional] sequence: int
* [optional] scriptSig: {"asm": ..., "hex": ...}
Each output will have:
* value: Dec... | dfd97a8493430ea6600d8c45c0c0b5ea81cc803e | 3,635,778 |
import time
def wait_for_result(polling_function, polling_config):
"""
wait_for_result will periodically run `polling_function`
using the parameters described in `polling_config` and return the
output of the polling function.
Args:
polling_config (PollingConfig): The p... | 663f23b3134dabcf3cc3c2f72db33d09ca480555 | 3,635,779 |
def regrid(idx):
"""
Decorator factory to compute a model on a constant grid, then interpolate.
This is to be used for reconvolution fits when the independant axis isn't
evently spaced. This function returns a decorator. You should call the
result of this function with the model to regrid. The constant grid
Par... | c0d3ef6b5f32545a004fcbaebc585ca2e6e1d984 | 3,635,780 |
from typing import Optional
def create_random_bytes(
min_length: Optional[int] = None, max_length: Optional[int] = None, lower_case: bool = False
) -> bytes:
"""Generates a random bytes given the constraints"""
if min_length is None:
min_length = 0
if max_length is None:
max_length = m... | 1e71debc3a495d2291a7989fe92c0f3712556baa | 3,635,781 |
def calculate_v_correction(df, photopic_response):
"""
Closure to calculate the e correction factor from a dataframe
"""
# Get angles from column names first
try:
angles = df.drop(["0_deg", "wavelength"], axis=1).columns.to_numpy(float)
except:
angles = df.drop(["wavelength"], a... | f9768d204813a89df6f246864ed669c8b8b305cf | 3,635,782 |
def wrap_statement(token_str):
"""
Wraps a long string of space-separated tokens
or a list of tokens.
"""
if isinstance(token_str, list):
token_str = ' '.join(token_str)
wrap_ind = '\n' + INDENT * 4
return wrap_ind.join(gtextWrapper.wrap(token_str)) | 447b74a2d33d6a053791c35112d43e356194f575 | 3,635,783 |
def mlas_packb(B, K, N, transb_size, transb=True):
"""Pre-pack B matrix if it is constant for mlas_matmul, C = A * B^T.
It only supports float32 datatype.
Parameters
----------
B : tvm.te.Tensor
The second input of mlas_matmul.
K : int
The number of colums of A.
N : int
... | c232e0f00b008c044c9843db90058425f6050cd3 | 3,635,784 |
def file_version_summary(list_of_files):
"""
Given the result of list_file_versions, returns a list
of all file versions, with "+" for upload and "-" for
hide, looking like this:
['+ photos/a.jpg', '- photos/b.jpg', '+ photos/c.jpg']
"""
return [('+ ' if (f['action'] == 'upload') else '-... | 8ca8e75c3395ea13c6db54149b12e62f07aefc13 | 3,635,785 |
def make_players(data, what_to_replace_null_data_with):
"""
1. feature selection
2. replacing null values
:param data:
:param what_to_replace_null_data_with: accepted values: "1", "mean", "median"
:return: players
"""
players = data[["Overall", "Potential", "Position", "Skill Moves", "C... | 081e563f475e7e05caf3761954646b8a35ec8e54 | 3,635,786 |
def pwm_to_duty_cycle(pulsewidth_micros, pwm_params):
"""Converts a pwm signal (measured in microseconds)
to a corresponding duty cycle on the gpio pwm pin
Parameters
----------
pulsewidth_micros : float
Width of the pwm signal in microseconds
pwm_params : PWMParams
PWMParams ob... | e627b84bf7e01f3d4dcb98ec94271cd34249fb23 | 3,635,787 |
import json
def update_plugin_packages_in_kv(rid, runit):
"""Update the plugin packages for this unit in the kv store.
It returns a tuple of 'install_packages' and 'purge_packages' that are
different from that which was previously stored.
:param rid: The relation_id of the unit
:type rid: str
... | 66d342e014f738e178629973b81c7a5c8d68dd41 | 3,635,788 |
def get_a_record(dns_name, zone_name):
"""Lookup an 'A' record with the supplied name.
Args:
dns_name: DNS nname of the resource.
zone_name: Cloud DNS managed zone name.
Returns:
The first A record for the DNS resource. None if not found
"""
rr_set_response = api.CLIENTS.dn... | c982fdb603d1c6accb7c205d64fc57a783559979 | 3,635,789 |
def get_file_obj(fname, mode='r', encoding=None):
"""
Light wrapper to handle strings and let files (anything else) pass through.
It also handle '.gz' files.
Parameters
----------
fname: string or file-like object
File to open / forward
mode: string
Argument passed to the '... | c8a24ef76869be8f743a7ddb7e66bf6ea4f0edf1 | 3,635,790 |
def decode(codes, alphabet):
""" Converts one-hot encodings to string
Parameters
----------
code : torch.Tensor
One-hot encodings.
alphabet : Alphabet
Matches one-hot encodings to letters.
Returns
-------
genes : list of Tensor
List of proteins
others : list... | 79ff69034293a8fb7d005ec89c98ae5e7535e487 | 3,635,791 |
import logging
def GetSuites(milo_client, waterfall, builder_name, build_number):
"""Gets a list of suites ids for a given build from Milo.
Args:
milo_client: MiloClient object.
waterfall: Buildbot waterfall.
builder_name: Buildbot builder name.
build_number: Buidlbot build number.
Returns:
... | 266ef9d5042d247b01d0f0819d8222104a591960 | 3,635,792 |
import re
def getNormform_space(synonym):
"""
"""
return re.sub("[^a-z0-9]", " ", synonym.lower()) | 5e03a89ca25cb5b4ae9a76ef9fb44c213a043cbd | 3,635,793 |
def electrolyte_conductivity_PeymanMPM(c_e, T):
"""
Conductivity of LiPF6 in EC:DMC as a function of ion concentration. The original
data is from [1]. The fit is from Dualfoil [2].
References
----------
.. [1] C Capiglia et al. 7Li and 19F diffusion coefficients and thermal
properties of no... | 61c5a0f8a8b514607d6829fabd784ab620e4bdf8 | 3,635,794 |
import re
def rename_leaves_taxids(tree):
"""
Rename the leaf nodes with just the NCBI taxonomy ID if we have it
:param tree: the tree to rename
:return: the tree with renamed leaves
"""
for n in tree.get_leaves():
m = re.search(r'\[(\d+)\]', n.name)
if m:
n.name =... | 26b55177b1e9372ff58f3a79ab703c639661551c | 3,635,795 |
def hshift(x, shifts=0):
"""shift batch of images horizontally"""
return paddle.roll(x, int(shifts*x.shape[3]), axis=3) | 176336fb7953197697b123041183798bf445b43f | 3,635,796 |
def getFirstCatalogKeyPath(cataloglist, keypath, default = None):
"""
Get the value of the keypath in the first catalog containing it.
"""
for name in cataloglist:
catalog = getCatalog(name)
if catalog is not None:
value = valueForKeyPath(catalog, keypath)
if valu... | 9e5a999e3bf9ae2e24c56c4e4fc1d6a8bf3e0095 | 3,635,797 |
import argparse
import os
from datetime import datetime
def load_context():
"""Load and parse command line arguments and create runtime context.
Parse command line arguments and create runtime context. Also set any
logging parameters passed in (just to file for the moment).
Returns:
context:... | 14174c40cff4f8b1ed8660992534527ec1990fb9 | 3,635,798 |
def HT_DCPHASE(ds, count):
"""Hilbert Transform - Dominant Cycle Phase"""
return call_talib_with_ds(ds, count, talib.HT_DCPHASE) | bb1f98e8adc8f90f2f35418b7598bec574f014ae | 3,635,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.