content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_single_io_arg(info):
"""
Get single input/output arg from io info
:param info:
:return:input/output arg
"""
if 'valid' not in info:
raise ValueError("Json string Errors, key:valid not found.")
if info['valid']:
check_arg_info(info)
del info['valid']
de... | 37,200 |
def new_credentials(
client_id: str, consumer_secret: str, data: Dict[str, Any]
) -> Credentials:
"""Create Credentials from config and json."""
return Credentials(
access_token=str_or_raise(data.get("access_token")),
token_expiry=arrow.utcnow().timestamp + data.get("expires_in"),
to... | 37,201 |
def get_chains(table, ipv6=False):
""" Return the existing chains of a table """
iptc_table = _iptc_gettable(table, ipv6)
return [iptc_chain.name for iptc_chain in iptc_table.chains] | 37,202 |
def check_file(file):
"""
检查本地有没有这个文件,相关文件路径能否找到文件 并返回文件名
"""
# 如果传进来的是文件或者是’‘, 直接返回文件名str
if os.path.isfile(file) or file == '':
return file
# 如果传进来的就是当前项目下的一个全局路径 查找匹配的文件名返回第一个
else:
files = glob.glob('./**/' + file, recursive=True)
# 验证文件名是否存在
assert len(fi... | 37,203 |
def unscale_fundamental_matrix(fundamental_matrix, M):
"""
Unscale fundamental matrix by coordinate scaling factor
:param fundamental_matrix:
:param M: Scaling factor
:return: Unscaled fundamental matrix
"""
T = np.diag([1 / M, 1 / M, 1])
unscaled_F = T.T.dot(fundamental_matrix).dot(T)
... | 37,204 |
def initialize_server_request(request):
"""Shortcut for initialization."""
# Django converts Authorization header in HTTP_AUTHORIZATION
# Warning: it doesn't happen in tests but it's useful, do not remove!
auth_header = {}
if 'Authorization' in request.META:
auth_header = {'Authorization': r... | 37,205 |
def _parse_coordinate_arg(coords, frame, units, init_kwargs):
"""
Single unnamed arg supplied. This must be:
- Coordinate frame with data
- Representation
- SkyCoord
- List or tuple of:
- String which splits into two values
- Iterable with two values
- SkyCoord, frame, or repr... | 37,206 |
def build_names(dependency: Dependency, version_in_url: bool = True) -> Tuple[RemoteResolver, str, str]:
"""
A function to build directory and file names based on the given dependency..
:param dependency: the dependency to create the file container for.
:param version_in_url: a flag noting whether the ... | 37,207 |
def convert_apc_examples_to_features(examples, label_list, max_seq_len, tokenizer, opt=None):
"""Loads a data file into a list of `InputBatch`s."""
configure_spacy_model(opt)
bos_token = tokenizer.bos_token
eos_token = tokenizer.eos_token
label_map = {label: i for i, label in enumerate(label_list,... | 37,208 |
def write_output(opts: AppOptions, out_lines):
"""
Writes the modified document lines to a new file with "MODIFIED" and
a date_time tag added to the file name. Returns the file name.
"""
ds = datetime.now().strftime("%Y%m%d_%H%M%S")
out_name = f"{opts.doc_path.stem}_MODIFIED_{ds}{opts.doc_path.... | 37,209 |
def ssh_pub_key(key_file):
"""Creates a string of a public key from the private key file.
"""
key = paramiko.RSAKey(filename=key_file)
pub = "{0} {1} autogenerated by polyphemus"
pub = pub.format(key.get_name(), key.get_base64())
return pub | 37,210 |
def _variable_with_weight_decay(name, shape, stddev, wd, use_xavier=True, use_zeros=False, init=None):
"""Helper to create an initialized Variable with weight decay.
Note that the Variable is initialized with a truncated normal distribution.
A weight decay is added only if one is specified.
Args:
name: na... | 37,211 |
def test_main_info_with_ble_interface(capsys, reset_globals):
"""Test --info"""
sys.argv = ['', '--info', '--ble', 'foo']
Globals.getInstance().set_args(sys.argv)
iface = MagicMock(autospec=BLEInterface)
def mock_showInfo():
print('inside mocked showInfo')
iface.showInfo.side_effect = m... | 37,212 |
def build_mobile_vit(config):
"""Build MobileViT by reading options in config object
Args:
config: config instance contains setting options
Returns:
model: MobileViT model
"""
model = MobileViT(in_channels=config.MODEL.IN_CHANNELS,
dims=config.MODEL.DIMS... | 37,213 |
def _openSerialPort(comport):
"""Opens the serial port name passed in comport. Returns the stream id"""
#debuglog.info("Check if serial module is available in sys {}".format(sys.modules["serial"]))
s = None
try:
s = serial.Serial(
port=comport,
baudrate=115200,
... | 37,214 |
def search_youtube(query, retries = 4, max_num_results = -1):
""" Unlimited youtube search by web scrapping """
transformed_query = reduce(lambda s_ant, s_sig : s_ant + '+' + s_sig, query) if len(query) != 0 else ''
scrapped_data = []
num_of_requests = 0
for i in range(retries):
page = get_h... | 37,215 |
def threaded(count):
"""This is the main body of each thread. It will generate a `count`
number of log messages (which will cause actor transmits to the
logger) and then exit.
"""
try:
time.sleep(1)
for x in range(count):
logging.debug('Msg %s of %s', x, count)
... | 37,216 |
def assert_less(first, second, msg_fmt="{msg}"):
"""Fail if first is not less than second.
>>> assert_less('bar', 'foo')
>>> assert_less(5, 5)
Traceback (most recent call last):
...
AssertionError: 5 is not less than 5
The following msg_fmt arguments are supported:
* msg - the defa... | 37,217 |
def Pull( display_sentinel,
json_filename,
result_filename,
first=False,
output_stream=sys.stdout,
):
"""Called prior to committing a change pushed from a client to the local repository"""
return _Impl( display_sentinel,
json_filename,
... | 37,218 |
def show_vars(names: List[str]) -> None:
"""
List "variables" with values.
This shows all known configuration settings as "variables" with their values or just
the variables that are selected.
This is a callback of a command.
"""
config_mapping = etl.config.get_config_map()
all_keys = ... | 37,219 |
def define_empty_source_parallel_buckets(max_seq_len_target: int,
bucket_width: int = 10) -> List[Tuple[int, int]]:
"""
Returns (source, target) buckets up to (None, max_seq_len_target). The source
is empty since it is supposed to not contain data that can be bucketi... | 37,220 |
def _hue_scaling(args):
"""return scaled hue values as described in
http://dlmf.nist.gov/help/vrml/aboutcolor
args : ndarray of args / angle of complex numbers between in the open
interval [0, 2*pi)
q : scaled values returned in the interval [0, 1)
"""
q = 4.0*_np.mod((args/(2*_np.pi... | 37,221 |
def _java_junit5_test(name,
srcs,
test_package = None,
deps = [],
runtime_deps = [],
testonly = True,
classpath_resources = None,
**kwargs):
""" Establish Bazel ... | 37,222 |
def validate_max_synapse_rates(parsed_args):
"""Run the check"""
use_saved_data = parsed_args.use_saved_data
max_rates_2 = load_txt_data(DATA_DIR + "max_rates_2.txt") # max rates / 2
syn_n = len(max_rates_2)
if use_saved_data:
low_rates = load_txt_data(DATA_DIR + "low_rates.txt")
low... | 37,223 |
def show(unmask: bool) -> None:
"""Show the account information stored in the plan engine."""
result = retrieve_account()
if not result:
click.secho("Account information is not set")
else:
token = result.pat_token if unmask else _mask_token(result.pat_token)
click.secho("PAT toke... | 37,224 |
def get_orbs(fp, orbs, truncate=False, tol=1e-8):
""" return the list of requested Kohn-Sham orbitals
Args:
fp (h5py.File): wf h5 file
orbs (list): a list of 3-tuples, each tuple species the KS state
by (kpoint/twist, spin, band) i.e. (ik, ispin, ib)
truncate (bool, optional): remove PWs with ``sm... | 37,225 |
def geturlcgivars(baseurl, port):
"""
Extract CGI variables from baseurl
>>> geturlcgivars("http://host.org/base", "80")
('host.org', '80', '/base')
>>> geturlcgivars("http://host.org:8000/base", "80")
('host.org', '8000', '/base')
>>> geturlcgivars('/base', 8000)
('', '8000', '/base')
... | 37,226 |
def insert_rails(file_path, half_gauge, drive_right = True, mr = 12.5, copy = True): # TODO - print 'progress messages' for done steps
"""
Deduces all rails' vertices from graph data and adds them to the json blueprint
half_gauge represents distance between center of the road and of the vehicle,
drive_... | 37,227 |
def prepare_log_for_upload(symbolized_output, return_code):
"""Prepare log for upload."""
# Add revision information to the logs.
app_revision = environment.get_value('APP_REVISION')
job_name = environment.get_value('JOB_NAME')
components = revisions.get_component_list(app_revision, job_name)
component_revi... | 37,228 |
def bucketize(point, bucket_size):
"""floor the point to the next lower multiple of bucket_size"""
return bucket_size * math.floor(point / bucket_size) | 37,229 |
def find_unit(df):
"""find unit in the df, add column to df indicating which token contains unit
and return the unit as string."""
doc_unit = ""
# thousand = "(\$)(0){3}|thousand|€(\s*)thous|TEUR|T(\s*)€|Tsd|Tausend"
# million = "millions|million|£(\s*)m|$(\s*)m|€(\s*)m|mn|mio(\s*)€|in(\s+)mio|MM|\d... | 37,230 |
def regular_channels(audio ,new_channels):
"""
torchaudio-file([tensor,sample_rate])+target_channel -> new_tensor
"""
sig ,sr =audio
if sig.shape[0 ]==new_channels:
return audio
if new_channels==1:
new_sig =sig[:1 ,:] # 直接取得第一个channel的frame进行操作即可
else:
# 融合(... | 37,231 |
def is_less_than(maximum: Union[int, float, Decimal]) -> Callable[[Union[int, float, Decimal]], bool]:
"""
:param maximum: A number
:return: A predicate that checks if a value is less than the given number
"""
def predicate(i: Union[int, float, Decimal]):
"""
:param i: A number
... | 37,232 |
def a_function(my_arg, another):
"""
This is the brief description of my function.
This is a more complete example of my function. It can include doctest,
code blocks or any other reST structure.
>>> a_function(10, [MyClass('a'), MyClass('b')])
20
:param int my_arg: The first argument of ... | 37,233 |
def substitute_vars(oldList, runSet=None, task_file=None):
"""
This method replaces special substrings from a list of string
and return a new list.
"""
keyValueList = []
if runSet:
benchmark = runSet.benchmark
# list with tuples (key, value): 'key' is replaced by 'value'
... | 37,234 |
def run(csv_file_path, version, local_working_dir):
"""Main function to start the labeling."""
label_set, data_set = extract_relevant_columns(csv_file_path)
# Build a label index and ask user to input more labels if needed.
labels_list = _add_labels(list(label_set))
for i, row in enumerate(data_s... | 37,235 |
def _safe_filename(filename):
"""
Generates a safe filename that is unlikely to collide with existing objects
in Google Cloud Storage.
``filename.ext`` is transformed into ``filename-YYYY-MM-DD-HHMMSS.ext``
"""
filename = secure_filename(filename)
date = datetime.datetime.utcnow().strftime(... | 37,236 |
def load_model(model_name, data_dir=''):
"""
Load and return a trained model
@param model_name: base name for saved files
@param data_dir: directory containing trained model
"""
# load json and create model
json_file = open(os.path.join(data_dir, '%s.json' % model_name), 'r')
... | 37,237 |
def _make_with_custom_variables(func, variables):
"""Calls func and replaces any trainable variables.
This returns the output of func, but whenever `get_variable` is called it
will replace any trainable variables with the tensors in `variables`, in the
same order. Non-trainable variables will re-use any variab... | 37,238 |
def create_loss_and_learner(
model, labels, learning_rate,
momentum_coef=0.0, wdecay=0.0, nesterov=False,
gradient_clip_norm=None, gradient_clip_value=None):
"""
Auxiliary function to create loss function (cross entropy and softmax)
and trainer using stochastic gradient descent with ... | 37,239 |
def main_CL():
""" Command line parsing and and defaults methods
"""
parser = OptionParser(usage=mainTaskUsage(), version='%s'%version)
parser.add_option("-a", "--cmd", dest="cmd", default="get", help="Command type to use.")
parser.add_option("-x", "--parm", dest="parm", default="", ... | 37,240 |
def get_opentsdb_config():
"""Read and parse Open TSDB config from config.ini"""
if os.path.exists(os.path.abspath(os.path.join(__file__, os.pardir, "config.ini"))):
config_parser = ConfigParser.SafeConfigParser()
config_parser.read(os.path.abspath(os.path.join(__file__, os.pardir, "config.ini")... | 37,241 |
def test_copying():
"""
5.3.8
:return:
"""
mo = my_object("mo")
rhs = my_object("rhs")
# 5.3.8.1
with pytest.raises(error_classes.UsePythonMethod):
mo.copy(rhs)
# 5.3.8.2
with pytest.raises(error_classes.UsePythonMethod):
mo.do_copy(rhs) | 37,242 |
def mesh_subdivide_tri(mesh, k=1):
"""Subdivide a mesh using simple insertion of vertices.
Parameters
----------
mesh : Mesh
The mesh object that will be subdivided.
k : int
Optional. The number of levels of subdivision. Default is ``1``.
Returns
-------
Mesh
A ... | 37,243 |
def make_projection(proj_params):
"""
turn a set of proj4 parameters into a cartopy laea projection
introduced in read_resample.ipynb
Parameters
----------
proj_params: dict
dictionary with parameters lat_0, lon_0 datum and ellps
Returns
-------
cartopy... | 37,244 |
def _shape(df):
""" Return DataFrame shape even if is not a Pandas dataframe."""
if type(df) == pandas.DataFrame or type(df) == pandas.Series:
return df.shape
try:
shape = (len(df), len(df.columns))
except Exception as e:
logging.error(e)
raise e
return shape | 37,245 |
def hvplot_line(
df, title, x, y: List[str], output_dir: Path, vlines=None, save_figure=True, **kwargs
):
"""Draw line splot with optional vertical lines.
Example:
hvplot_line(
df,
title=col,
x="time", # This is index name
y=col_n... | 37,246 |
def load_zstack(fn):
"""
Returns zstack, [zmin, zmax]
"""
with open(fn, "rb") as f:
d = np.fromfile(f,dtype=header_dtype,count=1,sep="")
version, shape, zrange = d[0]
zstack = np.fromfile(f,dtype='<f4',sep="").reshape(shape)
return zstack, zrange | 37,247 |
def Download_ALEXI_from_WA_FTP(local_filename, DirFile, filename,
lonlim, latlim, yID, xID, TimeStep):
"""Retrieves ALEXI data
This function retrieves ALEXI data for a given date from the
`<ftp.wateraccounting.unesco-ihe.org>`_ server.
Args:
local_filename (str): n... | 37,248 |
def parseFile(path):
"""
Read sections headed by :SectionName into lists by section name in a dictionary
blank lines, line preceeding and ending whitespace and #Comments are stripped
"""
d={}
currentList=None
f = open(pathPrefix()+path, 'r')
for t in f.readlines(... | 37,249 |
def test_kubernetes():
""" Test import of system_config file for kubernetes """
# Create the path to the system_config file
systemfile = os.path.join(
os.getcwd(), "controllerconfig/tests/files/",
"system_config.kubernetes")
# Test import and generation of answer file
_test_system_... | 37,250 |
def setName(name):
"""
Sets the name of the robot.
This is cleared with a power cycle and displayed on the robot screen during idle times
Name will be shortened to 11 characters
Args:
name (any): Name to set for the robot. Will be cast to a string
Returns:
None
"""
name = ... | 37,251 |
def get_cmd_output(cmd):
"""Run a command in shell, and return the Unicode output."""
try:
data = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as ex:
data = ex.output
try:
data = data.decode("utf-8")
except UnicodeDec... | 37,252 |
def twoBodyCMmom(m_0, m_1, m_2):
"""relative momentum for 0 -> 1 + 2"""
M12S = m_1 + m_2
M12D = m_1 - m_2
if hasattr(M12S, "dtype"):
m_0 = tf.convert_to_tensor(m_0, dtype=M12S.dtype)
# m_eff = tf.where(m_0 > M12S, m_0, M12S)
# p = (m_eff - M12S) * (m_eff + M12S) * (m_eff - M12D) * ... | 37,253 |
def svn_repos_post_commit_hook(*args):
"""svn_repos_post_commit_hook(svn_repos_t repos, apr_pool_t pool) -> char"""
return _repos.svn_repos_post_commit_hook(*args) | 37,254 |
def add_reconstruction_summaries(images, reconstructions, prebinary,
num_imgs_to_visualize=8):
"""Adds image summaries."""
reshaped_img = stack_images(images, reconstructions, num_imgs_to_visualize)
tf.summary.image('real_vs_reconstruction', reshaped_img, max_outputs=1)
if preb... | 37,255 |
def run(one_worker_per_rse=False, once=False, rses=[], scheme=None, all_os_rses=False, older_than=30, sleep_time=1):
"""
Starts up the injector threads.
:param one_worker_per_rse: If True, one worker per RSE; Otherwise, one worker for all RSEs.
:param once: If True, only runs one iteration of the main ... | 37,256 |
def get_window_size():
"""Return the window width and height"""
width = os.popen(
"xrandr --current | grep '*' | uniq | awk '{print $1}' | cut -d 'x' -f1").read().strip(
"\n")
height = os.popen(
"xrandr --current | grep '*' | uniq | awk '{print $1}' | cut -d 'x' -f2").read().strip(
... | 37,257 |
def test_geo_ops_smoke(backend, fn_expr):
"""Smoke tests for geo spatial operations."""
geo_table = backend.table('geo')
assert fn_expr(geo_table).compile() != '' | 37,258 |
def slot_selection_is_free(effect):
"""
all slots ar selected when participant applies
"""
activity = effect.instance.activity
return activity.slot_selection == 'free' | 37,259 |
def get_consumption_tax(amount, tax_rate, decimal_type):
"""消費税を取得する。
:param amount:
:param tax_rate:
:param decimal_type:
:return:
"""
if not amount:
return 0
return get_integer(decimal_type, float(amount) * float(tax_rate)) | 37,260 |
def homology(long_sequence, short_sequence):
"""
Cross-compare to find the strand of long sequence with the highest similarity with the short sequence.
:param long_sequence: str
:param short_sequence: str
:return ans: str, the strand of long sequence with the highest similarity with the short sequen... | 37,261 |
def oneliner_to_phylip(line):
"""Convert one-liner to phylip format."""
seqs = line.strip(";\n").split(',')
label_seqs = zip(seqs[:-1:2], seqs[1::2])
taxa_count = len(label_seqs)
seq_length = len(label_seqs[0][1])
# pad all names to length of longest name + 1 space
max_name_length = max([len... | 37,262 |
def _no_op_missing_kt_jvm_lib_impl(name, **kwargs):
"""
This is a help macro for missing concrete rule implementation.
This will be used in cases when some dependencies require Kotlin rule implementation.
Args:
name: A unique name for this target.
**kwargs: Anything else. Not used.
... | 37,263 |
def get_final_histogram(n_states, logfile, temp):
"""
This function analyzes the log file and performs the following tasks:
1. Output the counts of each lambda state at the last time frame (for plotting histogram)
2. Estimate the uncertainty of free energy difference from the final histogram
Parane... | 37,264 |
def create_sql_delete_stmt(del_list, name):
"""
:param del_list: list of records that need to be formatted in SQL delete statement.
:param name: the name of the table
:return: SQL statement for deleting the specific records
"""
sql_list = ", ".join(del_list)
sql_stmt = f"DELETE FROM method_u... | 37,265 |
def parse_track(trackelement):
"""Extract info from every track entry and output to list."""
print(trackelement)
if trackelement.find('artist').getchildren():
#artist info is nested in loved/banned tracks xml
artistname = trackelement.find('artist').find('name').text
artistmbid = ... | 37,266 |
def flattencommand(input, separator, sort_keys, style, **kwargs):
"""
Flattens JSON input with nested or hierarchical structure into a flat (depth 1) hierarchy. Requires valid input.
Examples:
\b
Example: Basic usage:
$ echo '{"a":{"b":null,"c":"null","d":"","e":{"f":null},"g":{},"... | 37,267 |
def AddMutexEnvVarsFlags(parser):
"""Add flags for creating updating and deleting env vars."""
# TODO(b/119837621): Use env_vars_util.AddUpdateEnvVarsFlags when
# `gcloud run` supports an env var file.
key_type = env_vars_util.EnvVarKeyType
value_type = env_vars_util.EnvVarValueType
flag_name = 'env-vars'
... | 37,268 |
def _coord_matrix(model, pos, noutp):
"""
Create an array representing inputs and outputs of a simple model.
The array has a shape (noutp, model.n_inputs).
Parameters
----------
model : `astropy.modeling.Model`
model
pos : str
Position of this model in the expression tree.
... | 37,269 |
def showp2rev(context, mapping):
"""Integer. The repository-local revision number of the changeset's
second parent, or -1 if the changeset has no second parent."""
ctx = context.resource(mapping, 'ctx')
return ctx.p2().rev() | 37,270 |
def puan_kam(text: str = 'สวัสดี',
first: Optional[bool] = None,
keep_tone: Optional[bool] = None,
all: Optional[bool] = False,
skip_tokenize: Optional[bool] = None):
"""Puan kum (ผวนคำ) is a Thai toung twister, This API convert string into kampuan
Play ar... | 37,271 |
def _flask_app_from_location(module_name: str) -> flask.app.Flask:
"""
:param module_name: String specifying path and module name as well as
actual flask app attribute. e.g., /path/to/module:flask_app
"""
module_and_app_name: str = (module_name.split('/')[-1])
module_file: str = module_and_app... | 37,272 |
def get_app_wx(*args, **kwargs):
"""Create a new wx app or return an exiting one."""
import wx
app = wx.GetApp()
if app is None:
if 'redirect' not in kwargs:
kwargs['redirect'] = False
app = wx.PySimpleApp(*args, **kwargs)
return app | 37,273 |
def do_part_1():
"""
Solve the puzzle.
"""
data = input_lines(1)
total = 0
for line in data:
val, op = interpret_line(line)
total = op(total, val)
print(total)
return total | 37,274 |
def handle_rpc_errors(fnc):
"""Decorator to add more context to RPC errors"""
@wraps(fnc)
def wrapper(*args, **kwargs):
try:
return fnc(*args, **kwargs)
except grpc.RpcError as exc:
# lnd might be active, but not possible to contact
# using RPC if the wal... | 37,275 |
def _check_BoolOp_expr(boolop, t, env):
"""Boolean Operations."""
assert boolop.__class__ is ast.BoolOp
op = boolop.op
es = boolop.values
assert op.__class__ in bool_ops, "%s not in bool ops" % cname(op)
# (BoolOp) assignment rule.
return all(check_expr(e, t, env) for e in es) | 37,276 |
def get_matproj(dbpath, cutoff, api_key, dataset_properties):
"""
Args:
dbpath (str): path to the local database
cutoff (float): cutoff radius
api_key (str): personal api_key for materialsproject.org
dataset_properties (list): properties of the dataset
Returns:
Atoms... | 37,277 |
def parse_change_values_from_opts(opts):
"""
Convert optparse style options into a dictionary for changing.
:param opts: optparse style options
:returns: a dictonary with change values to filter devices,
supported parameters are ip, port, replication_ip,
replication_port
... | 37,278 |
def save_annotations(index_value):
"""
Function to save the annotations
"""
try:
if os.path.exists(CSV_FILENAME):
with open(CSV_FILENAME, "a", encoding='utf-8') as file_object:
wavfile_information_object = csv.writer(file_object)
wavfile_information_object.w... | 37,279 |
def chooseMove(board,gameState):
"""called once per turn. Calls either escapeTrail or approachOpponent to determine move choice"""
def escapeTrail():
"""returns a command to move to the next space if we are in danger of an explosion Trail, or None if we are safe"""
# if we are not currently on a... | 37,280 |
def xr_linear_trends_2D(da, dim_names, with_nans=False):
""" calculate linear trend of 2D field in time
! slow, use xr_2D_trends instead
input:
da .. 3D xr DataArray with (dim_names) dimensions
dim_names .. tuple of 2 strings: e.g. lat, lon dimension names
output:
da_trend ... | 37,281 |
def sanitize_email(email):
"""
Returns an e-mail address in lower-case and strip leading and trailing
whitespaces.
>>> sanitize_email(' MyEmailAddress@example.com ')
'myemailaddress@example.com'
"""
return email.lower().strip() | 37,282 |
def draw_perm_reps(data_1, data_2, func, size=1, args=()):
"""
Generate permutation replicates of `func` from `data_1` and
`data_2`
Parameters
----------
data_1 : array_like
One-dimensional array of data.
data_2 : array_like
One-dimensional array of data.
func : function... | 37,283 |
def construct(template_name, parameter_dict, path=""):
"""Construct an HTML file using a given template and parameters.
Handles all necessary tasks for generating finished HTML files in output directory.
Likely the tuscon function that the user will call most often in their code.
:param template_name:... | 37,284 |
def get_attachment_form(parser, token):
"""
Get a (new) form object to upload a new attachment
Syntax::
{% get_attachment_form for [object] as [varname] %}
{% get_attachment_for for [app].[model] [object_id] as [varname] %}
"""
return AttachmentFormNode.handle_token(parser, token) | 37,285 |
def greet(name):
"""Greet message, formatted differently for johnny."""
if name == "Johnny":
return "Hello, my love!"
return "Hello, {name}!".format(name=name) | 37,286 |
def get_naca_points(naca_digits, number_of_points=100,
sharp_trailing_edge=True,
abscissa_map=lambda x: 0.03*x+0.97*x**2,
verbose=False):
"""
Return a list of coordinates of NACA 4-digit and 5-digit series
airfoils.
"""
if verbose:
def explain(*s):
print(... | 37,287 |
def get_request_now():
"""
When constructing the SOAP request, the timestamps have to be naive but with localtime values.
E.g. if the current offset is utc+1 and the utc now is 2016/03/30 0:00, the SOAP endpoint expects 2016/03/30 1:00
without tzinfo. That's pretty ugly but ¯\_(ツ)_/¯
In order to do... | 37,288 |
def test_2_2():
"""Testing PWBS Config Manager"""
# Import
from ..config.pwbs_config import PWBS_ConfigManager
from ..config.config_manager import PWBSConfigFileDontExistError
from ..config.config_manager import PWBSInvalidConfigFile
# Values
t1 = PWBS_ConfigManager()
t1.log.log("Test 2.... | 37,289 |
def _make_decorator(
obj: Wrappable,
to_wrap: tp.Iterable[str]
) -> tp.Callable[[tp.Type[WrapperInjector]], tp.type[WrapperInjector]]:
"""Makes the decorator function to use for wrapping.
Parameters
----------
obj : :obj:`ModuleType`, :obj:`type` or :obj:`object`
The source object to wr... | 37,290 |
def logistic_regression_path(X, y, pos_class=None, Cs=10, fit_intercept=True,
max_iter=100, tol=1e-4, verbose=0,
solver='lbfgs', coef=None,
class_weight=None, dual=False, penalty='l2',
intercept_scaling=1... | 37,291 |
def merge_labels_below_minsize(labels: np.array,
min_size: int,
connectivity: int = 8) -> np.array:
"""
Takes labels below min_size and merges a label with a connected neighbor
(with respect to the connectivity description). Ignores label 0 as
... | 37,292 |
def create_model_error_grid(
func: MultiFidelityFunction,
instances: Sequence[Instance],
mfbo_options: Dict[str, Any],
save_dir: Path,
extra_attributes=dict(),
plot_1d: bool=False,
record_values: bool=False
) -> None:
"""Create a grid of model errors for the g... | 37,293 |
def plot_testfn():
"""Make contour plots of all 6 test functions in 2d."""
assert plt_loaded, 'Matplotlib not installed'
dim = 2
global c, w
c = np.array([0.5] * dim)
c = c / sum(c) * 9.
w = np.array([0.5] * dim)
xi = np.linspace(0., 1., 100)
xx = mylib.meshgrid_flatten(xi, xi)
... | 37,294 |
def custom_cnn_model(config, labels, model_weights=None):
"""
Convolutional Neural network architecture based on 'Photonic Human Identification based on
Deep Learning of Back Scattered Laser Speckle Patterns' paper.
:param conf: Configuration list of models hyper & learning params
:param labels: Lis... | 37,295 |
def check_day_crossover(tRxSeconds, tTxSeconds):
"""
Checks time propagation time for day crossover
:param tRxSeconds: received time in seconds of week
:param tTxSeconds: transmitted time in seconds of week
:return: corrected propagation time
"""
tau = tRxSeconds - tTxSeconds
if tau > ... | 37,296 |
def matrix2xyx_extrinsic(rotation_matrices: np.ndarray) -> np.ndarray:
"""
Rx(k3) @ Ry(k2) @ Rx(k1) = [[c2, s1s2, c1s2],
[s2s3, -s1c2s3+c1c3, -c1c2s3-s1c3],
[-s2c3, s1c2c3+c1s3, c1c2c3-s1s3]]
"""
rotation_matrices = rotation_matrices.reshap... | 37,297 |
def _merge_low_rank_eigendecomposition(S1, V1, S2, V2, rank=None):
"""Private helper function for merging SVD based low rank approximations.
Given factors S1, V1 and S2, V2 of shapes [K1], [M, K1] and [K2], [M, K2]
respectively of singular value decompositions
A1 = U1 @ np.diag(S1) @ V1.T
... | 37,298 |
def usgs(path):
"""Reads USGS-formatted ASCII files.
Reads the ascii format spectral data from USGS and returns an object with the mean
and +/- standard deviation. Reference: https://www.sciencebase.gov/catalog/item/5807a2a2e4b0841e59e3a18d
Args:
path: file path the the USGS spectra text file.... | 37,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.