content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def vector(*args):
"""
A single vector in any coordinate basis,
as a numpy array.
"""
return N.array(args) | 5,329,400 |
def arcmin_to_deg(arcmin: float) -> float:
""" Convert arcmin to degree """
return arcmin / 60 | 5,329,401 |
def soft_embedding_lookup(embedding, soft_ids):
"""Transforms soft ids (e.g., probability distribution over ids) into
embeddings, by mixing the embedding vectors with the soft weights.
Args:
embedding: A Tensor of shape `[num_classes] + embedding-dim` containing
the embedding vectors. E... | 5,329,402 |
def test_user3_biosamples_access(user3_token):
""""
Make sure user3 has access to open1, open2, registered3, controlled4, and controlled6
"""
response = helper_get_katsu_response(user3_token, f"{KATSU_URL}/api/biosamples")
assert response.status_code == 200
response_json = response.json()
as... | 5,329,403 |
def param_11(i):
"""Returns parametrized Exp11Gate."""
return Exp11Gate(half_turns=i) | 5,329,404 |
def resolve_link(db: Redis[bytes], address: hash_t) -> hash_t:
"""Resolve any link recursively."""
key = join(ARTEFACTS, address, "links_to")
link = db.get(key)
if link is None:
return address
else:
out = hash_t(link.decode())
return resolve_link(db, out) | 5,329,405 |
def image_ppg(ppg_np):
"""
Input:
ppg: numpy array
Return:
ax: 画布信息
im:图像信息
"""
ppg_deps = ppg.DependenciesPPG()
ppg_M = Matrix(ppg_np)
monophone_ppgs = ppg.reduce_ppg_dim(ppg_M, ppg_deps.monophone_trans)
monophone_ppgs = monophone_ppgs.numpy().T
... | 5,329,406 |
def read_and_parse(filenames):
"""Read all apache log files (possibly gzipped) and
yield each parsed bitsteam download event."""
log_parser = create_log_parser()
for filename in filenames:
print("parsing '{0}'".format(filename))
if not os.path.exists(filename):
print("fa... | 5,329,407 |
def create_homography_calibrator_launch(filename):
"""
Creates launch file for homography calibrators
"""
template_name = 'homography_calibrator_launch.xml'
machine_file = mct_utilities.file_tools.machine_launch_file
params_file = mct_utilities.file_tools.homography_calibrator_params_file
#... | 5,329,408 |
def main():
"""
Fetch and write out HTML files around property values.
Use requests.Session to keep a connection open to the domain and get a
performance benefit, as per the documentation here:
http://docs.python-requests.org/en/master/user/advanced/
In case there is a poor connection or t... | 5,329,409 |
def hook_plan_building():
"""When builing the plan we should not call directly specific
methods from CrypTen and as such we return here some "dummy" responses
only to build the plan.
"""
f = lambda *args, **kwargs: crypten.cryptensor(th.zeros([]))
for method_name in methods_to_hook:
met... | 5,329,410 |
def print_list_all_apps():
"""This function print list of all installed packages or error message if an error
occurred
:returns: None
"""
all_apps, err_msg, err = get_list_all_apps()
if err:
print_error_and_exit(err_msg)
return
print_message('\n'.join(all_apps)) | 5,329,411 |
def create_inputs():
"""
Create inputs for `test_plot_spectra_for_qa_single_frame`.
The raw files will be downloaded and saved inside the path stored in the
`$DRAGONS_TEST/raw_inputs` directory. Processed files will be stored inside
a new folder called "dragons_test_inputs". The sub-directory struc... | 5,329,412 |
def test_add_updated():
"""Test the function that add updated repo to list"""
ctx = invoker.ctx()
repo = 'repo123'
cli_support.add_updated(ctx, repo)
assert repo in ctx.obj['updated'] | 5,329,413 |
def is_hex_value(val):
"""
Helper function that returns True if the provided value is an integer in
hexadecimal format.
"""
try:
int(val, 16)
except ValueError:
return False
return True | 5,329,414 |
def create_cluster(*, cluster_name: str) -> Optional[Operation]:
"""Create a dataproc cluster """
cluster_client = dataproc.ClusterControllerClient(client_options={"api_endpoint": dataproc_api_endpoint})
cluster = {
"project_id": project_id,
"cluster_name": cluster_name,
"confi... | 5,329,415 |
def gc_cache(seq: str) -> Cache:
"""Return the GC ratio of each range, between i and j, in the sequence
Args:
seq: The sequence whose tm we're querying
Returns:
Cache: A cache for GC ratio lookup
"""
n = len(seq)
arr_gc = []
for _ in seq:
arr_g... | 5,329,416 |
def ParseVariableName(variable_name, args):
"""Parse a variable name or URL, and return a resource.
Args:
variable_name: The variable name.
args: CLI arguments, possibly containing a config name.
Returns:
The parsed resource.
"""
return _ParseMultipartName(variable_name, args,
... | 5,329,417 |
def test_handle_success_request_success(provider_base_config, order_with_products):
"""Test request helper changes the order status to confirmed
Also check it returns a success url with order number"""
params = {
'RESPA_UI_RETURN_URL': 'http%3A%2F%2F127.0.0.1%3A8000%2Fv1',
'AUTHCODE': '905E... | 5,329,418 |
def index(request):
"""Home page"""
return render(request, 'read_only_site/index.html') | 5,329,419 |
def test_shorthand_inversion():
"""
Test that the Matplotlib subtraction shorthand for composing and inverting
transformations works.
"""
w1 = WCS(naxis=2)
w1.wcs.ctype = ['RA---TAN', 'DEC--TAN']
w1.wcs.crpix = [256.0, 256.0]
w1.wcs.cdelt = [-0.05, 0.05]
w1.wcs.crval = [120.0, -19.0]... | 5,329,420 |
def parse_calculation_strings_OLD(args):
"""form the strings into arrays
"""
calculations = []
for calculation in args.calculations:
calculation = calculation.split("/")
foreground = np.fromstring(
",".join(calculation[0].replace("x", "0")), sep=",")
background = np.f... | 5,329,421 |
def plot_inflections():
"""
"""
study_list = retrieve_ref('study_list')
sensor_list = retrieve_ref('sensor_list')
segment_list = retrieve_ref('segment_list')
searchRange = retrieve_ref('searchRange')
for study in study_list:
for sensor in sensor_list:
format_type = '... | 5,329,422 |
def fixture_hdf5_scalar(request):
"""fixture_hdf5_scalar"""
import h5py # pylint: disable=import-outside-toplevel
tmp_path = tempfile.mkdtemp()
filename = os.path.join(tmp_path, "test.h5")
with h5py.File(filename, 'w') as f:
f.create_dataset('int8', data=np.int8(123))
f.create_dataset('int16', data=... | 5,329,423 |
def find_border(edge_list) :
"""
find_border(edge_list)
Find the borders of a hexagonal graph
Input
-----
edge_list : array
List of edges of the graph
Returns
-------
border_set : set
Set of vertices of the border
... | 5,329,424 |
def get_all_files(credentials: Credentials, email: str) -> Set['DriveResult']:
"""Get all files shared with the specified email in the current half-year
(January-June or July-December of the current year)"""
# Create drive service with provided credentials
service = build('drive', 'v3', credentials=cred... | 5,329,425 |
def _split_kwargs(model, kwargs, lookups=False, with_fields=False):
"""
Split kwargs into fields which are safe to pass to create, and
m2m tag fields, creating SingleTagFields as required.
If lookups is True, TagFields with tagulous-specific lookups will also be
matched, and the returned tag_fields... | 5,329,426 |
def sliceResultToBytes(sr):
"""Copies a FLSliceResult to a Python bytes object. Does not free the FLSliceResult."""
if sr.buf == None:
return None
lib.FLSliceResult_Release(sr)
b = bytes( ffi.buffer(sr.buf, sr.size) )
return b | 5,329,427 |
def cycle_dual(G, cycles, avg_fun=None):
"""
Returns dual graph of cycle intersections, where each edge
is defined as one cycle intersection of the original graph
and each node is a cycle in the original graph.
The general idea of this algorithm is:
* Find all cycles which ... | 5,329,428 |
def main():
"""Entry point"""
if check_for_unstaged_changes(TARGET_FILE):
print("ERROR: You seem to have unstaged changes to %s that would be overwritten."
% (TARGET_FILE))
print("Please clean, commit, or stash them before running this script.")
return 1
if not path.ex... | 5,329,429 |
def resource_teardown():
""" """
dataset = Dataset('tests/test_data/test_dataset.csv')
if os.path.exists("tests/experiments"):
shutil.rmtree("tests/experiments")
if os.path.exists(dataset._internals_folder_path):
shutil.rmtree(dataset._internals_folder_path) | 5,329,430 |
def log_results(url):
"""
Generate static result metadata, which is rendered in the
Kubeflow Pipelines UI. Refer to
https://elyra.readthedocs.io/en/latest/recipes/visualizing-output-in-the-kfp-ui.html
for details.
"""
# Create result metadata
metadata = {'outputs': [
{
'stor... | 5,329,431 |
def get_timebucketedlog_reader(log, event_store):
"""
:rtype: TimebucketedlogReader
"""
return TimebucketedlogReader(log=log, event_store=event_store) | 5,329,432 |
def get_database_name(url):
"""Return a database name in a URL.
Example::
>>> get_database_name('http://foobar.com:5984/testdb')
'testdb'
:param str url: The URL to parse.
:rtype: str
"""
name = compat.urlparse(url).path.strip("/").split("/")[-1]
# Avoid re-encoding the n... | 5,329,433 |
def get_tags():
"""
在这里希望根据用户来获取,和用户有关的tag
所以我们需要做的是,获取用户所有的post,然后找到所有的tag
:return:
"""
result_tags = []
# 找到某个用户的所有的文章,把所有文章的Tag都放在一块
def append_tag(user_posts):
tmp = []
for post in user_posts:
for tag in post.tags.all():
tmp.append(tag.ta... | 5,329,434 |
def get_selinux_modules():
"""
Read all custom SELinux policy modules from the system
Returns 3-tuple (modules, retain_rpms, install_rpms)
where "modules" is a list of "SELinuxModule" objects,
"retain_rpms" is a list of RPMs that should be retained
during the upgrade and "install_rpms" is a lis... | 5,329,435 |
def a_star_search(graph, start, goal):
"""Runs an A* search on the specified graph to find a path from the ''start'' node to the ''goal'' node.
Returns a list of nodes specifying a minimal path between the two nodes.
If no path exists (disconnected components), returns an empty list.
"""
all_nodes =... | 5,329,436 |
def output_format_option(default: OutputFormat = OutputFormat.TREE):
"""
A ``click.option`` for specifying a format to use when outputting data.
Args:
default (:class:`~ape.cli.choices.OutputFormat`): Defaults to ``TREE`` format.
"""
return click.option(
"--format",
"output... | 5,329,437 |
def compute_errors(u_e, u):
"""Compute various measures of the error u - u_e, where
u is a finite element Function and u_e is an Expression.
Adapted from https://fenicsproject.org/pub/tutorial/html/._ftut1020.html
"""
print('u_e',u_e.ufl_element().degree())
# Get function space
V = u.functi... | 5,329,438 |
def save_reg(reg_list, data_name):
"""
Save the regression results for premiums and claims data, respectively.
Args:
reg_list (list): a list consisting of the results of all regressions
data_name (str): name of tables (see **wscript** file)
"""
for idx in [0, 2, 5, 7]:
reg... | 5,329,439 |
def list_to_str(input_list, delimiter=","):
"""
Concatenates list elements, joining them by the separator specified by the
parameter "delimiter".
Parameters
----------
input_list : list
List with elements to be joined.
delimiter : String, optional, default ','.
The separato... | 5,329,440 |
def learner_loop(create_env_fn,
create_agent_fn,
create_optimizer_fn,
config: learner_config.TrainingConfig,
settings: utils.MultiHostSettings,
action_distribution_config=None):
"""Main learner loop.
Args:
create_env_fn: Calla... | 5,329,441 |
def pytest_runtest_setup(item):
"""Set the number of openmp threads based on the number of workers
xdist is using to prevent oversubscription.
Parameters
----------
item : pytest item
item to be processed
"""
try:
xdist_worker_count = int(os.environ['PYTEST_XDIST_WORKER_COUN... | 5,329,442 |
def load_data_and_labels(file):
"""
Loads data from taobao crawler files, use jieba to split the data into words and generates labels.
Returns split sentences and labels.
"""
mapping = { u'书包':0, u'T恤':1, u'阔腿裤':2, u'运动鞋':3}
sentences = []
labels = []
filename = file + '.json'
for ... | 5,329,443 |
def strategy_supports_no_merge_call():
"""Returns if the current `Strategy` can operate in pure replica context."""
if not distribution_strategy_context.has_strategy():
return True
strategy = distribution_strategy_context.get_strategy()
return not strategy.extended._use_merge_call() # pylint: disable=prote... | 5,329,444 |
def process_recursively(subtree, key_name, new_value, skip_if=None):
""" Processes value with given key in the subtree.
If new_value is None, removes key from tree, otherwise replaces old value with the new one.
If skip_if is specified, it should be function(value) that returns True if this specific value should not... | 5,329,445 |
def is_group(obj):
"""Returns true if the object is a h5py-like group."""
kind = get_h5py_kind(obj)
return kind in ["file", "group"] | 5,329,446 |
def recovery_data():
"""
This function recovers data from Data Base, if server was temporarily disabled
:return:
"""
global communications
s = session()
for i in s.query(Contact).all():
first = s.query(User).filter(User.id == i.userID).first()
second = s.query(User).filter(... | 5,329,447 |
def cli():
"""Run DropSeq Data Analysis
"""
pass | 5,329,448 |
def monotonic():
""" Example 2.2. """
size = mpl.rcParams['figure.figsize']
size[0] *= 2
size[1] *= 0.5
fig, axs = plt.subplots(1, 4, figsize=size)
x = np.linspace(-1, 1, 1000)
ys = []
ys.append(x * 0.7 + 0.3)
ys.append(1/2/(x + 2) - 0.3)
_y = - x - 0.5
_y[x > 0] = -0.5
... | 5,329,449 |
def test_app_access_with_app(test_app):
"""Test that Extension.app returns the provided app."""
extension = Extension(test_app)
assert extension.app == test_app | 5,329,450 |
def analyze_page(page_url):
""" Analyzes the content at page_url and returns a list of the highes weighted
words.json/phrases and their weights """
html = fetch_html(page_url)
if not html:
return
soup = BeautifulSoup(html, "html.parser")
word_counts = {}
url_words = words_in_url(pa... | 5,329,451 |
def load_config_from_paths(config_paths: Iterable[str], strict: bool = False) -> List[dict]:
"""
Load configuration from paths containing \*.yml and \*.json files.
As noted in README.config, .json will take precedence over .yml files.
:param config_paths: Path to \*.yml and \*.json config files.
:p... | 5,329,452 |
def submit_simulation(sim_dir, job_file):
"""
Submit LAMMPS simulation with Slurm scheduler.
"""
subprocess.run(['sbatch', job_file], cwd=sim_dir)
pass | 5,329,453 |
def sort_flats(flats_unsorted: List[arimage.ARImage]):
""" Sort flat images into a dictionary with "filter" as the key """
if bool(flats_unsorted) == False:
return None
flats = { }
logger.info("Sorting flat images by filter")
for flat in flats_unsorted:
fl = flat.filter
if fl... | 5,329,454 |
def run_in_parallel(function, list_of_kwargs_to_function, num_workers):
"""Run a function on a list of kwargs in parallel with ThreadPoolExecutor.
Adapted from code by mlbileschi.
Args:
function: a function.
list_of_kwargs_to_function: list of dictionary from string to argument
value. These will be... | 5,329,455 |
def upload(host, key, path):
""" Upload one file at a time """
url= urljoin(host, 'api/files?key=' + key)
os.chdir(path[0])
f = open(path[1], 'rb')
r = requests.post(url, files={"File" : f})
r.raise_for_status()
return r.json()['id'] | 5,329,456 |
def show_project(project_id):
"""return a single project formatted according to Swagger spec"""
try:
project = annif.project.get_project(
project_id, min_access=Access.hidden)
except ValueError:
return project_not_found_error(project_id)
return project.dump() | 5,329,457 |
def pollard_rho(n: int, e: int, seed: int = 2) -> int:
"""
Algoritmo de Pollard-Rho para realizar a quebra de chave na criptografia RSA.
n - n da chave pública
e - e da chave pública
seed - valor base para executar o ciclo de testes
"""
a, b = seed, seed
p = 1
while (p == 1):
... | 5,329,458 |
def _url_from_string(url):
"""
Generate actual tile url from tile provider definition or template url.
"""
if "tileX" in url and "tileY" in url:
warnings.warn(
"The url format using 'tileX', 'tileY', 'tileZ' as placeholders "
"is deprecated. Please use '{x}', '{y}', '{z}'... | 5,329,459 |
def display_es(
data: pd.DataFrame,
ticker: str = "",
use_mean: bool = False,
distribution: str = "normal",
percentile: float = 0.999,
portfolio: bool = False,
):
"""Displays expected shortfall
Parameters
----------
data: pd.DataFrame
stock dataframe
use_mean:
... | 5,329,460 |
def get_reverse_dns(ip_address: str) -> str:
"""Does a reverse DNS lookup and returns the first IP"""
try:
rev = socket.gethostbyaddr(ip_address)
if rev:
return rev[0]
return "" # noqa
except (socket.herror, socket.gaierror, TypeError, IndexError):
return "" | 5,329,461 |
def update_sca():
"""
根据SCA数据库,更新SCA记录信息
:return:
"""
logger.info(f'SCA离线检测开始')
try:
assets = Asset.objects.all()
if assets.values('id').count() == 0:
logger.info('dependency is empty')
return
step = 20
start = 0
while True:
... | 5,329,462 |
def test_1D_180to180_to_0to360(da_1D):
"""Tests that a 1D -180to180 grid converts to 0to360."""
data = da_1D(degreesEast=False)
converted = convert_lon(data)
lonmin = converted.lon.min()
lonmax = converted.lon.max()
# Checks that it was appropriately converted, not going below 0 or above 360.
... | 5,329,463 |
def abs_path(file_path):
"""
Returns the absolute path from the file that calls this function to file_path. Needed to access other files within aide_gui when initialized by aide.
Parameters
----------
file_path: String
The relative file path from the file that calls this function.
"""
... | 5,329,464 |
def function(x: np.ndarray) -> float:
"""The ellipse function is x0^2 + 2 * x1^2 + 3 * x2^2 + ..."""
return np.linalg.norm(np.sqrt(np.arange(1, 1 + len(x))) * x) ** 2 | 5,329,465 |
def get_permission(certificate_authority_arn: Optional[str] = None,
principal: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetPermissionResult:
"""
Permission set on private certificate authority
:param str certificate_authority_arn:... | 5,329,466 |
def replace_with_encoded_bits(one_hot_matrix, enum_val, add_value, last_col_index):
"""
Generate encoded bits for a categorical data value using one hot encoding.
:param one_hot_matrix: matrix representing the encoding of categorical data value to 1-hot encoding
:param enum_val: categorical data value,... | 5,329,467 |
def cosine_similarity(n_co_elements, n_first_element, n_second_element):
"""
Description
A function which returns the cosine similarity between two elements.
Arguments
:param n_co_elements: Number of co-elements.
:type n_co_elements: int
:param n_first_element: Size of the f... | 5,329,468 |
def AddForwardEulerDynamicsConstraint(mp, A, B, x, u, xnext, dt):
"""
Add a dynamics constraint to the given Drake mathematical program mp, represinting
the euler dynamics:
xnext = x + (A*x + B*u)*dt,
where x, u, and xnext are symbolic variables.
"""
n = A.shape[0]
Aeq = np.hstack(... | 5,329,469 |
def test_variant_flexiblerollout_stickiness_100_customfield_112(unleash_client):
"""
Feature.flexible.rollout.custom.stickiness_100 and customField=112 yields yellow
"""
# Set up API
responses.add(responses.POST, URL + REGISTER_URL, json={}, status=202)
responses.add(responses.GET, URL + FEATURE... | 5,329,470 |
async def light_pure_rgb_msg_fixture(hass):
"""Return a mock MQTT msg with a pure rgb light actuator message."""
light_json = json.loads(
await hass.async_add_executor_job(load_fixture, "ozw/light_pure_rgb.json")
)
message = MQTTMessage(topic=light_json["topic"], payload=light_json["payload"])
... | 5,329,471 |
def make_header_names_thesaurus(header_names_thesaurus_file=HEADER_NAMES_THESAURUS_FILE):
"""
Get a dict mapping ideal domain-specific phrases to list of alternates.
Parameters
----------
header_names_thesaurus_file : str
Filepath.
Returns
-------
Dict of {'ideal phrase': ['alt_phrase0', 'alt_phrase1', ...]... | 5,329,472 |
def split_train_valid_test(adata_here,
training_proportion=0.6,
validation_proportion=0.2,
test_proportion=0.2,
rng=None,copy_adata=False):
"""Split cells into training, validation and test
"""
... | 5,329,473 |
def get_stock_ledger_entries(previous_sle, operator=None,
order="desc", limit=None, for_update=False, debug=False, check_serial_no=True):
"""get stock ledger entries filtered by specific posting datetime conditions"""
conditions = " and timestamp(posting_date, posting_time) {0} timestamp(%(posting_date)s... | 5,329,474 |
def test_license(client):
"""
GIVEN a user who wants to visit the license page
WHEN he access the page
THEN assert the right page is sent
"""
response = client.get("/license/")
assert response.status_code == 200
assertTemplateUsed(response, "core/license.html") | 5,329,475 |
def init_ext_scorer(language_model_path,
vocab_list, beam_alpha=5, beam_beta=1):
"""Initialize the external scorer.
:param beam_alpha: Parameter associated with language model.
:type beam_alpha: float
:param beam_beta: Parameter associated with word count.
:type beam_beta: float... | 5,329,476 |
def index(request):
""" Main index. Editor view. """
# Render editor
body = render_to_string('editor.html', {})
data = {
'body': body
}
# Render page layout
return render(request, 'index.html', data) | 5,329,477 |
def isUsdExt(ext):
""" Check if the given extension is an expected USD file extension.
:Parameters:
ext : `str`
:Returns:
If the file extension is a valid USD extension
:Rtype:
`bool`
"""
return ext.lstrip('.') in USD_EXTS | 5,329,478 |
def _get_dflt_lexicon(a_pos, a_neg):
"""Generate default lexicon by putting in it terms from seed set.
@param a_pos - set of positive terms
@param a_neg - set of negative terms
@return list(3-tuple) - list of seed set terms with uniform scores and
polarities
"""
return [(w, POSITIVE, 1.... | 5,329,479 |
def process_dst_overwrite_args(src,
dst=None,
overwrite=True,
src_to_dst_func=None):
"""
Check when overwrite is not allowed, whether the destination exists.
"""
src = os.path.abspath(src)
if dst is None:
... | 5,329,480 |
def loft(*args, **kwargs):
"""
This command computes a skinned (lofted) surface passing through a number of NURBS curves.
Returns: `string[]` Object name and node name
"""
pass | 5,329,481 |
def rct(target_t : Tensor, source_t : Tensor, target_mask_t : Tensor = None, source_mask_t : Tensor = None, mask_cutoff = 0.5) -> Tensor:
"""
Transfer color using rct method.
arguments
target_t Tensor( [N]CHW ) C==3 (BGR) float16|32
source_t Tensor( [N]CHW ) C==3 (BGR) float16|32
... | 5,329,482 |
def random_policy(num_actions):
"""
Returns a policy where all actions have equal probabilities, i.e., an uniform distribution.
"""
return np.zeros((num_actions,)) + 1 / num_actions | 5,329,483 |
def create_branch_switches(net):
""" Changes bus-bus switches with auxiliary buses into bus-branch switches and drops all
auxiliary buses. """
# initialize DataFrame to store the indices of auxiliary buses ("aux_buses"), the switch indices
# the auxiliary buses are connected to ("idx_switch"), the b... | 5,329,484 |
def _check_no_miscalled_stubs(all_calls: Sequence[BaseSpyCall]) -> None:
"""Ensure every call matches a rehearsal, if the spy has rehearsals."""
all_calls_by_id: Dict[int, List[BaseSpyCall]] = {}
for call in all_calls:
spy_id = call.spy_id
spy_calls = all_calls_by_id.get(spy_id, [])
... | 5,329,485 |
def find_object(func, name, *args, **kwargs):
"""Locate an object by name or identifier
This function will use the `name` argumetn to attempt to
locate an object. It will first attempt to find the
object by identifier and if that fails, it will attempt
to find the object by name.
Since object... | 5,329,486 |
def load_inputs(mod, switch_data, inputs_dir):
"""
Import battery data from a .dat file.
TODO: change this to allow multiple storage technologies.
"""
switch_data.load(filename=os.path.join(inputs_dir, 'batteries.dat')) | 5,329,487 |
def mkdir(path):
""" Make a directory, if the parent directory exists. """
path = abspath(path, fse.get_working().get_full_path())
parent_path, d = os.path.split(path)
parent = fse.find_dir(parent_path)
if parent:
entry = fse.create(name=d, parent=parent, depth=parent.depth+1, is_directory=True)
return f'{pa... | 5,329,488 |
def _get_cognitive_services_client() -> ImageSearchClient:
"""Get the cognitive service client to run the searches against.
Ensure there is a COGNITIVE_KEY and COGNITIVE_ENDPOINT configured in your
app setting for the function, or your local.settings.json file when running
locally.
Returns
---... | 5,329,489 |
def getZeroPadding(path):
"""Get original zero padding, so can be re-added."""
files = listVisibleFiles(path)
zero_padding = len(getNumSubString(os.path.splitext(files[0])[0]))
return zero_padding | 5,329,490 |
def weld_segments(gdf_line_net, gdf_line_gen, gdf_line_houses,
debug_plotting=False):
"""Weld continuous line segments together and cut loose ends.
This is a public function that recursively calls the internal function
weld_line_segments_(), until the problem cannot be simplified further.... | 5,329,491 |
def CreateHSpline(points, multiple=False):
"""
Construct an H-spline from a sequence of interpolation points
Args:
points (IEnumerable<Point3d>): Points to interpolate
"""
url = "rhino/geometry/nurbscurve/createhspline-point3darray"
if multiple: url += "?multiple=true"
args = [point... | 5,329,492 |
def SetRoleStageIfAlpha(role):
"""Set the role stage to Alpha if None.
Args:
role: A protorpc.Message of type Role.
"""
if role.stage is None:
role.stage = StageTypeFromString('alpha') | 5,329,493 |
def get_instance_embedding_loss(embedding,
instance_loss_type,
instance_labels,
crop_area,
crop_min_height,
num_samples=10,
simi... | 5,329,494 |
def generate_ordered_map_to_left_streamed(left: Field,
right: Field,
l_result: Field,
r_result: Field,
invalid: Union[np.int32, np.int64],
... | 5,329,495 |
def str_to_array(value):
"""
Check if value can be parsed to a tuple or and array.
Because Spark can handle tuples we will try to transform tuples to arrays
:param value:
:return:
"""
try:
if isinstance(literal_eval((value.encode('ascii', 'ignore')).decode("utf-8")), (list, tuple)):
... | 5,329,496 |
def get_current_func_name():
"""for python version greater than equal to 2.7"""
return inspect.stack()[1][3] | 5,329,497 |
def test_pseudocolor(debug, axes, tmpdir, visualize_test_data):
"""Test for PlantCV."""
# Create a tmp directory
cache_dir = tmpdir.mkdir("cache")
params.debug_outdir = cache_dir
# Input image
img = cv2.imread(visualize_test_data.small_bin_img, -1)
r, c = img.shape
# generate "bad" pixel... | 5,329,498 |
def getParmNames(parmsDef):
"""Return a list of parm names in a model parm definition
parmsDef: list of tuples, each tuple is a list of parms and a time
constraint. Call with modelDict[modelname]['Parms].
Returns: List of string parameter names
Here's an example of how to remove unused parms f... | 5,329,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.