content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_init():
"""Smoke test for Dataset class."""
dataset_dir = get_test_data_path()
dset = Dataset("dataset_files", dataset_dir)
assert isinstance(dset, Dataset) | 5,305,500 |
def signup(request):
"""
Create a new user with the given credentials.
GET parameters:
html
turn on the HTML version of the API
POST parameters (JSON):
username:
user's name
email:
user's e-mail
password:
user's password
... | 5,305,501 |
def test_agg_summary():
"""Test the aggregation summary method against a baseline file."""
s = SupplyCurveAggregation.summary(EXCL, GEN, TM_DSET,
excl_dict=EXCL_DICT,
res_class_dset=RES_CLASS_DSET,
... | 5,305,502 |
def preprocess_observation(observation_dict, amt_nodes=21, amt_features=9):
"""Preprocesses an observation dictionary to feature- and adjacency matrices.
:param observation_dict: The observation dictionary returned by the "TreeObsForRailEnv"-
observation builder.
:param amt_nod... | 5,305,503 |
def test_md5_str():
"""Test md5 on strings."""
assert get_md5('foo', string=True) == 'acbd18db4cc2f85cedef654fccc4a4d8'
assert get_md5(b'foo') == 'acbd18db4cc2f85cedef654fccc4a4d8'
assert check_md5(b'foo', 'acbd18db4cc2f85cedef654fccc4a4d8') | 5,305,504 |
def init_aes(shared_secret, nonce):
""" Initialize AES instance
:param hex shared_secret: Shared Secret to use as encryption key
:param int nonce: Random nonce
:return: AES instance
:rtype: AES
"""
" Shared Secret "
ss = hashlib.sha512(unhexlify(shared_secret)).digest()
... | 5,305,505 |
def which(cmd):
"""
Returns full path to a executable.
Args:
cmd (str): Executable command to search for.
Returns:
(str) Full path to command. None if it is not found.
Example::
full_path_to_python = which("python")
"""
def is_exe(fp):
return os.path.isfi... | 5,305,506 |
def create(context, name, template, force, **kwargs):
""" Create a new plan based on given template. """
tmt.Plan._save_context(context)
tmt.Plan.create(name, template, context.obj.tree.root, force) | 5,305,507 |
def getHackerNewsItem(item_id):
"""Get an 'item' as specified in the HackerNews v0 API."""
time.sleep(0.2)
item_json_link = "https://hacker-news.firebaseio.com/v0/item/" + item_id + ".json"
try:
with urllib.request.urlopen(item_json_link) as item_json:
return json.loads(item_json.rea... | 5,305,508 |
def fix_line(line):
"""
Apply all the fixes to one line from the DIFF.tsv file
"""
line = line.strip()
if line.startswith('#LOC'):
return "#LOC\tSVTYPE\tDIFF\tFIXED"
loc, svtype, instr_orig = line.split('\t')
instructions = parse_instr_set(instr_orig, loc)
if upper(svtype) == 'A... | 5,305,509 |
def get_spot_fleet(id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetSpotFleetResult:
"""
Resource Type definition for AWS::EC2::SpotFleet
"""
__args__ = dict()
__args__['id'] = id
if opts is None:
opts = pulumi.InvokeOptions()
i... | 5,305,510 |
def factory_invoice_reference(invoice_id: int, invoice_number: str = '10021'):
"""Return Factory."""
return InvoiceReference(invoice_id=invoice_id,
status_code=InvoiceReferenceStatus.ACTIVE.value,
invoice_number=invoice_number).save() | 5,305,511 |
def read_folder(folder):
"""
Parameters
----------
folder : string
Path to a folde with *.inkml files.
Returns
-------
list :
Objects of the type HandwrittenData
"""
# Core Library modules
import glob
recordings = []
for filename in natsorted(glob.glob("... | 5,305,512 |
def trainingdb_show_training(request, item_container, veranst_iq_id):
""" zeigt Einzelveranstaltung der Fortbildungsdatenbank """
item = get_veranstaltung_by_iq_id(veranst_iq_id)
if item == None:
return show_error(request, item_container, _('Falsche Veranstaltungsnummer'),
_(u'<p>Zu... | 5,305,513 |
def merge_frames(header, frames):
""" Merge frames into original lengths
Examples
--------
>>> merge_frames({'lengths': [3, 3]}, [b'123456'])
[b'123', b'456']
>>> merge_frames({'lengths': [6]}, [b'123', b'456'])
[b'123456']
"""
lengths = list(header['lengths'])
if not frames:
... | 5,305,514 |
def main():
"""main
"""
parser = argparse.ArgumentParser()
parser.add_argument('--net', type=str, required=True, help='net prototxt')
parser.add_argument('--weight', type=str, required=True, help='net weight')
args = parser.parse_args()
print(args)
net = caffe_pb2.NetParameter()
tex... | 5,305,515 |
def populate_last_id(conn_str, search_path, id_name):
"""Populate study id maps from dcc_pedsnet.
:param str conn_str: database connection string
:param str search_path: PostgreSQL schema search path
:param str id_name: name of the id
:returns: True if the funct... | 5,305,516 |
def parse_args():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description='Test a Fast R-CNN network')
parser.add_argument('--device', dest='device', help='device to use',
default='gpu', type=str)
parser.add_argument('--device_id', dest='device_id', hel... | 5,305,517 |
def memcached(func):
"""Use memcached to cache the results of a function.
Must have the memcached server running.
"""
def wrapper(key, *args, **kwargs):
value = memcached_client().get(key)
if value is None:
value = func(key, *args, **kwargs)
memcached_client().s... | 5,305,518 |
def initialize_indexes_by_model(models=None, using='default', fail_gracefully=False):
"""Initialize models. If a list of ``models`` is supplied,
then only those models will be initialized. Otherwise all known models will be initialized.
If ``using`` is supplied similar to the expectations of `elasticsearch... | 5,305,519 |
def _get_identities_from_provisioning_profile(provisioning_profile):
"""Iterates through all the identities in a provisioning profile, lazily."""
for identity in provisioning_profile['DeveloperCertificates']:
if not isinstance(identity, bytes):
# Old versions of plistlib return the deprecated plistlib.Dat... | 5,305,520 |
def __virtual__():
"""
Only works on Windows systems with PyWin32 installed
"""
if not salt.utils.platform.is_windows():
return False, "Module win_service: module only works on Windows."
if not HAS_WIN32_MODS:
return False, "Module win_service: failed to load win32 modules"
ret... | 5,305,521 |
def parse_html(mail):
"""
Parser for HTML part of message
"""
link = ""
soup = BeautifulSoup(mail, "lxml")
# print(soup.prettify())
for item in soup.find_all('a'):
link = re.findall(match_regex, str(item.get('href')))
if len(link) != 0:
return [True, item.get('hre... | 5,305,522 |
def line_fit():
"""Load the data from housing.npy. Use least squares to calculate the line
that best relates height to weight.
Plot the original data points and the least squares line together.
"""
raise NotImplementedError("Problem 2 Incomplete") | 5,305,523 |
def clamp(input, min, max):
"""
Return an attribute that represents the given input clamped in the range
[min, max].
All inputs can be either attributes or values.
"""
return _createUtilityAndReturnOutput('clamp', input=input, min=min, max=max) | 5,305,524 |
def quick_sort(alist, first, last):
"""
快速排序不像之前的那样把序列分成两部分
而是第一个元素通过一个low一个high游标相夹, low的左边都比第一个元素小,high的右边都比第一个元素大
以此来确定第一个元素在序列中的位置
时间复杂度O(nlogn) 第一次分成2部分,2部分分成4部分,也就是 2*2*2*...=n 也就是logn次才能变成一个个单独元素的数组推出递归
如果9个元素的话,n = log2为底9,结果为3,横向为n,纵向为logn总体最优复杂度为O(nlogn),最坏为O(n^2)
... | 5,305,525 |
def _url_handler(url, content_type="text/html"):
"""The pydoc url handler for use with the pydoc server.
If the content_type is 'text/css', the _pydoc.css style
sheet is read and returned if it exits.
If the content_type is 'text/html', then the result of
get_html_page(url) is returned.
"""
... | 5,305,526 |
def train_pmi(dataset, initial_cutoff=0.5, alpha=0.75, margin=1.0, max_iter=15, batch_size=256):
"""
Train a dict mapping pairs of ASJP sounds/chars to their PMI scores on word
pairs using the EM algorithm with the specified parameters.
The first arg should be a Dataset or a PairsDataset instance provi... | 5,305,527 |
def to_category(category_reference, fuzzy=True):
""" Coerces a category, category name or category id to a BuiltInCategory.
>>> from rpw.utils.coerce import to_category
>>> to_category('OST_Walls')
BuiltInCategory.OST_Walls
>>> to_category('Walls')
BuiltInCategory.OST_Walls
>>> to_c... | 5,305,528 |
def test_bokeh_access(client, credentials, data_files):
"""Test Bokeh visualization routes redirect user if missing information."""
with client.session_transaction() as sess:
sess['dataset'] = None
username, password = credentials
response_value = login(client, username, password) # Sign in
... | 5,305,529 |
def get_class_mapping(super_mode: str):
"""
Mapping mode into integer
:param super_mode: before, after & both
:return:
"""
class_mapping = ['none', 'replace']
if super_mode == 'both':
class_mapping.extend(['before', 'after'])
else:
class_mapping.append(super_mode)
ret... | 5,305,530 |
def cheer():
""" Prints 2 4 6 8, who do we appreciate .... Note that everything in
the while loop is indented. The first line not indented is the first
line following the while loop. """
ct = 2
while ct <= 8:
print(ct,end=" ") # end = " " keeps from starting a new line
ct = ... | 5,305,531 |
def get_test_obs(cursor=None, testid=0):
"""Arguments:
cursor: cursor of the database connection to be used for the query
testid: test ID
Return value:
Dictionary with observer IDs, keys and node IDs
1 if there is an error in the arguments passed to the functi... | 5,305,532 |
def permissions_required(permissions, login_url=None):
"""
Decorator that checks if a user has the given permissions.
Accepts a list or tuple of lists of permissions (see check_permissions
documentation).
If the user is not logged in and the test fails, she is redirected to a
login page. If the ... | 5,305,533 |
def test_annotated_sector_name_level_two():
"""Test the sector name annotation for a sector two levels deep."""
grandparent = SectorFactory()
parent = SectorFactory(parent=grandparent)
sector = SectorFactory(parent=parent)
annotated_sector = Sector.objects.annotate(
name_annotation=get_secto... | 5,305,534 |
def u_P1():
"""
Plot P1 basis functions and a resulting u to
illustrate what it means to use finite elements.
"""
import matplotlib.pyplot as plt
x = [0, 1.5, 2.5, 3.5, 4]
phi = [np.zeros(len(x)) for i in range(len(x)-2)]
for i in range(len(phi)):
phi[i][i+1] = 1
#u = 5*x*np.... | 5,305,535 |
def main_build_all(args):
"""
Main function for the 'all' command.
"""
log.info("Started full build")
# Load configuration file
config = autokernel.config.load_config(args.autokernel_config)
main_build(args, config)
main_install(args, config) | 5,305,536 |
def auth(opts, whitelist=None):
"""
Returns the auth modules
:param dict opts: The Salt options dictionary
:returns: LazyLoader
"""
return LazyLoader(
_module_dirs(opts, "auth"),
opts,
tag="auth",
whitelist=whitelist,
pack={"__salt__": minion_mods(opts)},... | 5,305,537 |
def preprocess_data(dfs, target):
"""
For each df in dictionary the number of columns is reduced to number of features.
Features get scaled using preprocessing.scale()
Arguments:
dfs(dict) - dictionary with monthly fixtures
target(str) - market to predict, three markets get handled: "e... | 5,305,538 |
def mlp(inputs, mlp_hidden=[], mlp_nonlinearity=tf.nn.relu, regularizer=None, scope=None):
"""Define an MLP."""
with tf.variable_scope(scope or 'Linear'):
mlp_layer = len(mlp_hidden)
res = inputs
for l in range(mlp_layer):
res = mlp_nonlinearity(linear(res, mlp_hidden[l], scope='l'+str(l), r... | 5,305,539 |
def get_banner():
"""Get the ``banner`` that will be signed in :meth:`adb_shell.adb_device.AdbDevice.connect` / :meth:`adb_shell.adb_device_async.AdbDeviceAsync.connect`.
Returns
-------
bytearray
The hostname, or "unknown" if it could not be determined
"""
try:
return bytearra... | 5,305,540 |
def sort2(b):
"""
Insertion Sort: Sorts the array b in n^2 time
Parameter b: The sequence to sort
Precondition: b is a mutable sequence (e.g. a list).
"""
assert type(b) == list, repr(b)+' is not a list'
n = len(b)
# Start from beginning of list
i = 0
while i < n:
j = ... | 5,305,541 |
async def test_send_raw_transaction_and_get_balance(
async_stubbed_sender, async_stubbed_receiver, test_http_client_async
):
"""Test sending a raw transaction to localnet."""
# Get a recent blockhash
resp = await test_http_client_async.get_recent_blockhash(Finalized)
assert_valid_response(resp)
... | 5,305,542 |
def tweets_for_search(*args):
"""
Tweets for a search query.
"""
return tweets_for(QUERY_TYPE_SEARCH, args) | 5,305,543 |
def test_invalid_service_account_has_external_access(
client,
app,
encoded_jwt_service_accounts_access,
valid_service_account_patcher,
valid_google_project_patcher,
db_session,
cloud_manager,
):
"""
Test that an invalid service account gives us the expected error structure
"""
... | 5,305,544 |
def buildCMakeProject(srcDir, buildDir, cmakeVars=None, env=env_vars, install_dir=None):
"""
cd buildDir
cmake srcDir -D...
make
(make install)
"""
# Ensure build dir exists
mkdir_p(buildDir)
if env is not None:
fullenv = dict(os.environ)
fullenv.update(env)
... | 5,305,545 |
def get_vois(dwi_array, image_coordinate_system, phantom_definition, debug=False, name=None):
"""
Find the VOIs for this phantom and ADC/T1.
Args:
dwi_array: 4d numpy array of dicom pixel data indexed by slice, then original dicom pixel_data x/y, then flip angle or b value;
e.g. dwi[sl... | 5,305,546 |
def rol(value, count):
"""A rotate-left instruction in Python"""
for y in range(count):
value *= 2
if (value > 0xFFFFFFFFFFFFFFFF):
value -= 0x10000000000000000
value += 1
return value | 5,305,547 |
def power(**kwargs):
"""
Powers on/off key fob.
Optional arguments:
- value (bool): Power on or off.
"""
return client.send_sync(_msg_pack(_handler="power", **kwargs)) | 5,305,548 |
def estimate_bonds(mol):
"""Estimates bond order based on default atom valencies."""
# Build connections of radicals
for bond in mol.GetBonds():
atom1_radicals = bond.GetBeginAtom().GetNumRadicalElectrons()
atom2_radicals = bond.GetEndAtom().GetNumRadicalElectrons()
if atom1_radica... | 5,305,549 |
def collatz(num):
"""
:type num: int;
:param num: start number, any positive integer;
:return [start number, [following_numbers], steps, time];
"""
num_original = num
following_nums = []
step = 0
start = time.time()
while num != 1:
# print(str(num))
if (num % 2) =... | 5,305,550 |
def bubble_sort(vals):
"""Sort the given array using bubble sort."""
for i in range(len(vals) - 1):
for j in range(len(vals) - i - 1):
if vals[j] > vals[j + 1]:
vals[j], vals[j + 1] = vals[j + 1], vals[j]
return vals | 5,305,551 |
def create_labels(features_end, prediction_start, prediction_end, conn, output = False):
"""
Generate a list of labels and return the table as a dataframe.
Parameters
----------
features_end
prediction_start
prediction_end
conn: obj
Returns
-------
df_labels: Da... | 5,305,552 |
def latex_print(expr):
"""Prints a tensor expression in Latex."""
# my_strs = copy(defaults)
# my_strs["dot"] = "%s %s"
# my_strs["inverse"] = "{%s}^{-1}"
# my_strs["name_attr"] = "latex"
# my_strs["transpose"] = "{%s}^t"
# my_strs["pow"] = "{%s}^{%s}"
# my_strs["div_under_one"] = "{%s}^{-1}"
#... | 5,305,553 |
def clean(grid, distances):
"""
Given a list of boxes and the distances between each pair, returns a new list of boxes and distances, by removing
the boxes that are not on land, as well as the -empty- distances referring to these boxes.
Args:
grid: A m*n list of boxes
distances: A (m*n)... | 5,305,554 |
def get_all_labware_definitions() -> List[str]:
"""
Return a list of standard and custom labware definitions with load_name +
name_space + version existing on the robot
"""
labware_list = ModifiedList()
def _check_for_subdirectories(path):
with os.scandir(path) as top_path:
... | 5,305,555 |
def public_byte_prefix(is_test):
"""Address prefix. Returns b'\0' for main network and b'\x6f' for testnet"""
return b'\x6f' if is_test else b'\0' | 5,305,556 |
def main() -> None:
"""The main function."""
parser = argparse.ArgumentParser(description="Process the arguments.")
parser.add_argument("--filename", type=str, help="specifies the filename.")
args = parser.parse_args()
filename = args.filename
with open("./test.csv", "w") as test:
wr... | 5,305,557 |
def add_stopword(word):
"""Adds the given stop word to the datastore."""
Stopword(token=word).put() | 5,305,558 |
def map_refseq_to_uniprot() -> Dict[str, str]:
"""
Reads the RefSeq_UniProt_collab file and maps RefSeq IDs to UniProt IDs.
:return: dictionary of refseq: uniprot
"""
ref_up_mapping = {}
with gzip.open(osp.join(DATA, 'gene_refseq_uniprotkb_collab.gz'), 'rt') as filehandle:
next(filehandl... | 5,305,559 |
async def character_search(bot, context):
"""Searches for characters with the given list of tags."""
tags = [_clean_text_wrapper(it) for it in context.arguments]
cursor = data.db_select(
bot, from_arg='characters', where_arg='tags @> %s',
input_args=[tags], additional='ORDER BY clean_name AS... | 5,305,560 |
def global_synchronization_enabled():
"""Checks if we should synchronize objects via hooks.
We shouldn't run these hooks if integration to IssueTracker turned off or
it was called by import request.
We can detect that it was called by import via trying to get request. Import
calls doesn't have requests.
"... | 5,305,561 |
def handle(*args, **kwargs):
"""
Handles `/space_info` command.
"""
if USE_GRAPH:
handle_with_graph(*args, **kwargs)
else:
handle_with_text(*args, **kwargs) | 5,305,562 |
def is_template_like(obj: Any) -> bool:
"""Check whether the given object is template-like.
Currently this includes templates and dataclasses.
"""
return is_template(obj) or dataclasses.is_dataclass(obj) | 5,305,563 |
def get_resource_ignore_params(params):
"""Helper method to determine which parameters to ignore for actions
:returns: A list of the parameter names that does not need to be
included in a resource's method call for documentation purposes.
"""
ignore_params = []
for param in params:
... | 5,305,564 |
async def test_invalid_hostname_windows(opp):
"""Test with invalid hostname on windows."""
assert await async_setup_component(
opp,
switch.DOMAIN,
{
"switch": {
"platform": "wake_on_lan",
"mac": "00-01-02-03-04-05",
"host": "in... | 5,305,565 |
def Rotation3DMatrix(Xangle=0,Yangle=0,Zangle=0):
"""
unit: degree [0,360]
"""
Xangle = np.pi*Xangle/180
Yangle = np.pi*Yangle/180
Zangle = np.pi*Zangle/180
Rx = np.array([[1,0,0],
[0,np.cos(Xangle),-np.sin(Xangle)],
[0,np.sin(Xangle),... | 5,305,566 |
def sum(x: Callable[[AbstractRow], R | None]) -> AggregateSpecification:
"""Compute the sum of `x`, with an empty column summing to NULL.
Parameters
----------
x
A column getter.
"""
return AggregateSpecification(Sum, x) | 5,305,567 |
def process_declared_and_found(df_declared_and_found, df_stations, df_temperature, out_path):
"""Create `declared_and_found` fact table, and apply range quality check for recovery date, the non-empty and unique key constraint checks
Args:
df_declared_and_found (DataFrame): data frame for lost and foun... | 5,305,568 |
def shift_particles_periodic_numba( z, zmin, zmax ):
"""
Shift the particle positions by an integer number of box length,
so that outside particle are back inside the physical domain
Parameters:
-----------
z: 1darray of floats
The z position of the particles (one element per particle)
... | 5,305,569 |
def camera_to_world_frame(x, R, T):
"""
Args
x: Nx3 points in camera coordinates
R: 3x3 Camera rotation matrix
T: 3x1 Camera translation parameters
Returns
xcam: Nx3 points in world coordinates
"""
xcam = R.T.dot(x.T) + T # rotate and translate
return xcam.T | 5,305,570 |
def left_multiplied_unitary_solution(C, R, c, verify=False):
""" Find portfolio in a rather indirect way ... useful for checking
min w^t R C w subject to w^t c == 1
"""
C_prime, H, c_prime = left_multiplied_unitary_problem(C=C, R=R)
u = scaled_unitary_problem_solution(C=C_prime, c=c_prime)
... | 5,305,571 |
def reinitialize():
"""This procedure must be called after setting variables in
the |theme| module. This procedure propagates the new values of
the theme variables to other modules that depend on their values."""
for proc in hooks:
proc() | 5,305,572 |
def export_filter_results(parquetFilePath, outFilePath, outFileType:FileTypeEnum, inputFileType=FileTypeEnum.Parquet, gzippedInput=False, columnList: list=[], query=None, transpose= False, includeAllColumns = False, gzipResults=False, indexCol="Sample"):
"""
Performs mulitple queries on a parquet dataset and exports ... | 5,305,573 |
def pck(path, variable):
"""Writes a python/pickle format data file
Args:
path - the path to the output pickle file
variable - the python variable to write
Returns:
None
"""
with open(path, "wb") as f:
_pickle.dump(variable, f) | 5,305,574 |
def find_job(schedd=None, attr_list=None, **constraints):
"""Query the condor queue for a single job matching the constraints
Parameters
----------
schedd : `htcondor.Schedd`, optional
open scheduler connection
attr_list : `list` of `str`
list of attributes to return for each job, ... | 5,305,575 |
def xor(use_hf=True):
# Copied from: hessianfree/hessianfree/demos.py
"""Run a basic xor training test.
:param bool use_hf: if True run example using Hessian-free optimization,
otherwise use stochastic gradient descent
"""
# data
inputs = np.asarray([[0, 0], [0, 1], [1, 0], [1, 1]], dtyp... | 5,305,576 |
def _json_read(filename):
"""Read a json into a dict."""
with open(filename) as file:
return json.load(file) | 5,305,577 |
def get_flagged_cells(gameboard):
"""This is another example that is written through the use of a cell class."""
flagged_cells = []
for cell in gameboard:
if cell.is_flagged():
flagged_cells.append(cell)
return flagged_cells
# consider
def copy_string(a1, a2)
# vs
def copy_string(source, destination)
... | 5,305,578 |
def test_moving_environment_to_background_process_macos():
"""Test moving an LLVM environment to a background process."""
queue = mp.Queue(maxsize=3)
with gym.make("llvm-autophase-ic-v0") as env:
env.reset(benchmark="cbench-v1/crc32")
process = mp.Process(
target=process_worker... | 5,305,579 |
def addLists(list1, list2):
"""Add lists together by value. i.e. addLists([1,1], [2,2]) == [3,3]."""
# Find big list and small list
blist, slist = list(list2), list(list1)
if len(list1) > len(list2):
blist, slist = slist, blist
# Overlay small list onto big list
for i, b in enumerate(sl... | 5,305,580 |
def qrGetGuidesColorFromGuidesNode( guidesNode ):
"""
This method sets the color from the guides node.
It returns the color of the root of all the guides.
"""
return cmds.getAttr( '%s.overrideColorRGB' % guidesNode )[ 0 ] | 5,305,581 |
def to_pickle(obj,fname):
"""
serializes an object to a .pickle file
"""
ensure_path(fname)
with open(fname, "wb") as outf:
pickle.dump(obj, outf) | 5,305,582 |
def dbconn_mysql(host=None, user=None, password=None, database=None, port=3306,
from_file=False, filename=None):
"""
Return MySQL database connection and cursor objects. Prompt for
missing credentials.
DESIGN:
Function designed to create a connection to a MySQL database
... | 5,305,583 |
def test_fitzpatrick99_idl():
"""Test that result matches implementation in IDL procedure FM_UNRED"""
for r_v in (2.3, 3.1, 4.0, 5.3):
fname = os.path.join('testdata', 'fm_unred_{:3.1f}.dat'.format(r_v))
wave, a_lambda_ref = np.loadtxt(fname, unpack=True)
a_lambda = extinction.Fitzpatri... | 5,305,584 |
def test_seki_02():
"""
:Proceure:
:Confirmation:
:Tester:
:Date:
"""
assert Calc(-9, 2).seki() == -18 | 5,305,585 |
def apply_coefficients_for_band(numpyarray, band, regression_coefficients):
"""
Apply regression coefficients in the form: ETM = c0 + OLI*c1
As per table 2 in http://www.mdpi.com/2072-4292/6/9/7952/htm
:param numpyarray: array of measurements to apply coefficients to
:param band: name of the coeffic... | 5,305,586 |
def append_to_csv(file_name, nda_str, set_id_group):
"""
Output all doc in set_id to a csv file.
Parameters:
file_name (Path): filename to store exported csv
nda_str (String): ex "12345-23456"
set_id_group (String): ex: "7b5489a1-e30f-450f-bd2b-00d05fd52915"
"""
_logger.info... | 5,305,587 |
def _sumprod(
func: Callable,
values: np.ndarray,
mask: np.ndarray,
*,
skipna: bool = True,
min_count: int = 0,
):
"""
Sum or product for 1D masked array.
Parameters
----------
func : np.sum or np.prod
values : np.ndarray
Numpy array with the value... | 5,305,588 |
def files_from_archive(tar_archive: tarfile.TarFile):
"""
Extracts only the actual files from the given tarfile
:param tar_archive: the tar archive from which to extract the files
:return: List of file object extracted from the tar archive
"""
file_members = []
# Find the actual files in t... | 5,305,589 |
def regular_wl_axis(axis, xlims=None):
"""
Converts a wavenumber axis ([cm-1]) into a regular (==equally spaced) wavelength axis ([Angstroms])
Parameters
----------
axis : 1D :class:`~numpy:numpy.ndarray`
Input axis in cm-1
xlims : tuple of floats
(Optional) limits in cm-1 to re... | 5,305,590 |
def load_stack_plane(image,c,z,x,y,w,h):
"""
Load ROI of a Z plane from every time point in OMERO image
Inputs:
image: OMERO ImageWrapper
c: int, channel
z: int, plane
x: float, x corner of ROI
y: float, y corner of ROI
width: int, width of ROI
height:... | 5,305,591 |
def test_invalid_vehicle_year():
"""Assert that an invalid vehicleCollateral fails - year outside 1900 - 2100."""
vehicle = copy.deepcopy(VEHICLE_COLLATERAL)
vehicle['year'] = 2220
is_valid, errors = validate(vehicle, 'vehicleCollateral', 'ppr')
if errors:
for err in errors:
pr... | 5,305,592 |
def read_file(href: HREF, stac_io: Optional[StacIO] = None) -> STACObject:
"""Reads a STAC object from a file.
This method will return either a Catalog, a Collection, or an Item based on what
the file contains.
This is a convenience method for :meth:`StacIO.read_stac_object
<pystac.StacIO.read_sta... | 5,305,593 |
def gcn_encoder(features, hparams, embed_scope,
embed_token_fn=common_embed.embed_tokens,
adjcency_feature="obj_dom_dist",
discretize=True):
"""Encodes a screen using Graph Convolution Networks.
Args:
features: the feature dict.
hparams: the hyperparameter.
... | 5,305,594 |
def help(term, arabic_column, english_column):
""" show all details of word"""
exclude_keys = [arabic_column, english_column]
details = {k: term[k] for k in set(list(term.keys())) - set(exclude_keys)}
return details | 5,305,595 |
def test_custom_credentials_not_in_v1_api_detail(get, admin, organization):
"""
'Custom' credentials (those not managed by Tower) shouldn't be visible from
the V1 credentials API detail
"""
credential_type = CredentialType(
kind='cloud',
name='MyCloud',
inputs = {
... | 5,305,596 |
def nodify(n):
"""
Modifies string to contain node#mod_
:param n: string
:return: string
"""
return 'node#mod_{}'.format(n) | 5,305,597 |
def calculate_rescue_time_pulse(very_distracting, distracting, neutral, productive, very_productive):
"""
Per RescueTime API
:param very_distracting: integer - number of seconds spent
:param distracting: integer - number of seconds spent
:param neutral: integer - number of seconds spent
:param ... | 5,305,598 |
def load_linux_so():
""" Load the shared object for Linux platforms.
The shared object must be in the same folder as this python script.
"""
shared_name = get_project_root() / "build/libastyle.so"
shared = str(pl.Path(shared_name).absolute())
# file_ = {f for f in pl.Path().iterdir() if f.n... | 5,305,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.