content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_routes_by_tunnel(compute, project, region, tunnel, restore, debug):
""" Filters all routes to a specific project, region and tunnel."""
match = '%s/regions/%s/vpnTunnels/%s' % (project, region, tunnel)
routes_all = list_routes(compute, project, debug)
routes = []
for route in routes_all:
if route.... | 5,350,900 |
def fcard(card):
"""Create format string for card display"""
return f"{card[0]} {card[1]}" | 5,350,901 |
def replaceUnresolvedLinks(root):
""" This transformation replaces all a.external-link
nodes with a proper footnote.
Used for PDF generation only (html_mode = 'split')
"""
for link in CSSSelector('a.external-link')(root):
href = link.attrib['href']
span1 = lxml.html.Element... | 5,350,902 |
def resetChapterProgress(chapterProgressDict, chapter, initRepeatLevel):
"""This method resets chapter progress and sets initial level for repeat routine.
Args:
chapterProgressDict (dict): Chapter progress data.
chapter (int): Number of the chapter.
initRepeatLevel (int): Initial level ... | 5,350,903 |
def aStarSearch(problem, heuristic=nullHeuristic):
"""Search the node that has the lowest combined cost and heuristic first."""
"*** YOUR CODE HERE ***"
priorityqueue = util.PriorityQueue()
priorityqueue.push( (problem.getStartState(), [], 0), heuristic(problem.getStartState(), problem) )
checkedsta... | 5,350,904 |
def index_referenced_records(series):
"""Index referenced records."""
indexer = ReferencedRecordsIndexer()
indexed = dict(pid_type=SERIES_PID_TYPE, record=series)
indexer.index(indexed, get_related_records(series["pid"])) | 5,350,905 |
def main(client, customer_id, merchant_center_account_id):
"""Demonstrates how to reject a Merchant Center link request.
Args:
client: An initialized Google Ads client.
customer_id: The Google Ads customer ID.
merchant_center_account_id: The Merchant Center account ID for the
... | 5,350,906 |
def draw_lines(img, lines, color=[255, 0, 0], thickness=2):
"""
NOTE: this is the function you might want to use as a starting point once you want to
average/extrapolate the line segments you detect to map out the full
extent of the lane (going from the result shown in raw-lines-example.mp4
to that ... | 5,350,907 |
def gen_flag(p1=0.5, **_args):
"""
Generates a flag.
:param p1: probability of flag = 1
:param _args:
:return: flag
"""
return 1 if np.random.normal(0, 100) <= p1 * 100 else 0 | 5,350,908 |
def load_migrations(path):
"""
Given a path, load all migrations in that path.
:param path: path to look for migrations in
:type path: pathlib.Path or str
"""
migrations = OrderedDict()
r = re.compile(r'^[0-9]+\_.+\.py$')
filtered = filter(
lambda x: r.search(x) is not None,
... | 5,350,909 |
def filterkey(e, key, ns=False):
"""
Gibt eine Liste aus der Liste C{e} mit dem Attribut C{key} zurück.
B{Beispiel 1}: Herauslesen der SRS aus einer Liste, die C{dict}'s enthält.
>>> e = [{'SRS':'12345', 'Name':'WGS-1'}, {'SRS':'54321', 'Name':'WGS-2'}]
>>> key = "SRS"
>>> filterkey(e, key)
... | 5,350,910 |
def validate_profile(profile_id, profile):
"""
Validates and normalises the given profile dictionary.
As side effects to the input dict:
* Fields that are set to None in rules are removed completely.
* Selectors are replaced with SelectorExpression objects. Parsing now
ensures that the sele... | 5,350,911 |
def get_runtime_preinstalls(internal_storage, runtime):
"""
Download runtime information from storage at deserialize
"""
if runtime in default_preinstalls.modules:
logger.debug("Using serialize/default_preinstalls")
runtime_meta = default_preinstalls.modules[runtime]
preinstalls ... | 5,350,912 |
def test_join_network(mock_cli, network_id, outcome):
""" Ensures that a ValueError is reaised on invalid id """
if isinstance(outcome, str):
mock_cli.return_value = outcome
assert zerotier.join_network(network_id) == outcome
else:
with pytest.raises(outcome):
zerotier.jo... | 5,350,913 |
def test_parse_feature_with_scenarios(parser):
"""
Test parsing a Feature with multiple Scenarios and Steps
"""
# when
feature = parser.parse()
# then
assert len(feature.scenarios) == 2
assert len(feature.scenarios[0].steps) == 3
assert len(feature.scenarios[1].steps) == 3 | 5,350,914 |
def set_warnings():
"""Configure warnings to show while running tests."""
warnings.simplefilter("default")
warnings.simplefilter("once", DeprecationWarning)
# Warnings to suppress:
# How come these warnings are successfully suppressed here, but not in setup.cfg??
# setuptools/py33compat.py:5... | 5,350,915 |
def update_graph(slider_value):
"""
Update the graph depending on which value of the slider is selected
Parameters
----------
slider_value: the current slider value, None when starting the app
Returns
-------
dcc.Graph object holding the new Plotly Figure as given by the plot_slice fun... | 5,350,916 |
def on_coordinator(f):
"""A decorator that, when applied to a function, makes a spawn of that function happen on the coordinator."""
f.on_coordinator = True
return f | 5,350,917 |
def redirect_subfeed(match):
"""
URL migration: my site used to have per-category/subcategory RSS feeds
as /category/path/rss.php. Many of the categories have Path-Aliases
in their respective .cat files, but some of the old subcategories no
longer apply, so now I just bulk-redirect all unaccounted-f... | 5,350,918 |
def _train_test_split_dataframe_strafified(df:pd.DataFrame, split_cols:List[str], test_ratio:float=0.2, verbose:int=0, **kwargs) -> Tuple[pd.DataFrame, pd.DataFrame]:
"""
ref. the function `train_test_split_dataframe`
"""
df_inspection = df[split_cols]
for item in split_cols:
all_entities = ... | 5,350,919 |
def index():
"""
This route will render a template.
If a query string comes into the URL, it will return a parsed
dictionary of the query string keys & values, using request.args
"""
args = None
if request.args:
args = request.args
return render_template("p... | 5,350,920 |
def load_from_string(xml_string, header_line):
"""
load document string, the string might contain multiple xml files
params:
xml_string (string): input xml strings
output:
xml string: a iterator object to generate xml string
"""
xml_lines = []
for line in xml_string.splitli... | 5,350,921 |
def multi_from_dict(cls: Type[T_FromDict], data: dict, key: str) -> List[T_FromDict]:
"""
Converts {"foo": [{"bar": ...}, {"bar": ...}]} into list of objects using the cls.from_dict method.
"""
return [cls.from_dict(raw) for raw in data.get(key, [])] | 5,350,922 |
def authenticate(user, passwd):
"""Authenticate via LDAP."""
caCertStr = zlib.decompress(base64.b64decode(encodedCompressedCaCert))
certFile = mktemp('.pem')
open(certFile, 'w').write(caCertStr)
try:
ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, certFile)
l = ldap.open("ldap.jpl.nasa.g... | 5,350,923 |
def infer_signature(func, class_name=''):
"""Decorator that infers the signature of a function."""
# infer_method_signature should be idempotent
if hasattr(func, '__is_inferring_sig'):
return func
assert func.__module__ != infer_method_signature.__module__
try:
funcfile = get_defi... | 5,350,924 |
def field_wrapper(col):
"""Helper function to dynamically create list display method
for :class:`ViewProfilerAdmin` to control value formating
and sort order.
:type col: :data:`settings.ReportColumnFormat`
:rtype: function
"""
def field_format(obj):
return col.format.format(getattr(... | 5,350,925 |
def __alarm_handler(*_args):
"""
Handle an alarm by calling any due heap entries and resetting the alarm.
Note that multiple heap entries might get called, especially if calling an
entry takes a lot of time.
"""
try:
nextt = __next_alarm()
while nextt is not None and nextt <= 0:... | 5,350,926 |
def is_isotropic(value):
""" Determine whether all elements of a value are equal """
if hasattr(value, '__iter__'):
return np.all(value[1:] == value[:-1])
else:
return True | 5,350,927 |
def grouper(iterable, n, fillvalue=None):
"""Iterate over a given iterable in n-size groups."""
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue) | 5,350,928 |
def format_gro_coord(resid, resname, aname, seqno, xyz):
""" Print a line in accordance with .gro file format, with six decimal points of precision
Nine decimal points of precision are necessary to get forces below 1e-3 kJ/mol/nm.
@param[in] resid The number of the residue that the atom belongs to
@pa... | 5,350,929 |
def return_as_list(ignore_nulls: bool = False):
"""
Enables you to write a list-returning functions using a decorator. Example:
>>> def make_a_list(lst):
>>> output = []
>>> for item in lst:
>>> output.append(item)
>>> return output
Is equivalent to:
>>> @retur... | 5,350,930 |
def get_pingback_url(target_url):
"""
Grabs an page, and reads the pingback url for it.
"""
logger.debug("get_pingback_url called...")
logger.debug("grabbing " + str(target_url))
html = urlopen(target_url).read()
logger.info( "Got %d bytes" % len(html))
soup = bs(html, 'html.parser')
... | 5,350,931 |
def onedim_phasecurves(left, right, singpoints, directions,
orientation='vertical', shift=0,
delta=0.05, **kwargs):
"""
Draws phase curves of one-directional vector field;
left and right are borders
singpoints is a list of singular points (equilibria)
... | 5,350,932 |
def assemble_insert_msg_content(row, column, digit):
"""Assemble a digit insertion message."""
return str(row) + CONTENT_SEPARATOR + str(column) + CONTENT_SEPARATOR + str(digit) | 5,350,933 |
def get_difference_of_means(uni_ts: Union[pd.Series, np.ndarray]) -> np.float64:
"""
:return: The absolute difference between the means of the first and the second halves of a
given univariate time series.
"""
mid = int(len(uni_ts) / 2)
return np.abs(get_mean(uni_ts[:mid]) - get_mean(un... | 5,350,934 |
async def test_binary_sensors(hass, mock_asyncsleepiq):
"""Test the SleepIQ binary sensors."""
await setup_platform(hass, DOMAIN)
entity_registry = er.async_get(hass)
state = hass.states.get(
f"binary_sensor.sleepnumber_{BED_NAME_LOWER}_{SLEEPER_L_NAME_LOWER}_is_in_bed"
)
assert state.s... | 5,350,935 |
def user_collection():
"""
用户的收藏页面
1. 获取参数
- 当前页
2. 返回数据
- 当前页
- 总页数
- 每页的数据
:return:
"""
user = g.user
if not user:
return "请先登录"
# 获取当前页
page = request.args.get('p', 1)
page_show = constants.USER_COLLECTION_MAX_NEWS
# 校验参数
t... | 5,350,936 |
def activity(*, domain, name, version):
"""Decorator that registers a function to `ACTIVITY_FUNCTIONS`
"""
def function_wrapper(func):
identifier = '{}:{}:{}'.format(name, version, domain)
ACTIVITY_FUNCTIONS[identifier] = func
return function_wrapper | 5,350,937 |
def OEDParser(soup, key):
""" The parser of Oxford Learner's Dictionary. """
rep = DicResult(key)
rep.defs = parseDefs(soup)
rep.examples = parseExample(soup)
return rep | 5,350,938 |
def main():
"""CLI main entry."""
# We parse it from sys.argv instead of argparse parser because we want
# to run the app parser only once, after we update it with the loaded
# arguments from the CI models based on the loaded configuration file
config_file_path = get_config_file_path(sys.argv)
... | 5,350,939 |
def X_SIDE_GAP_THREE_METHODS(data):
"""
Upside/Downside Gap Three Methods
:param pd.DataFrame data: pandas DataFrame with open, high, low, close data
:return pd.Series: with indicator data calculation results
"""
fn = Function('CDLXSIDEGAP3METHODS')
return fn(data) | 5,350,940 |
def fix_legacy_database_uri(uri):
""" Fixes legacy Database uris, like postgres:// which is provided by Heroku but no longer supported by SqlAlchemy """
if uri.startswith('postgres://'):
uri = uri.replace('postgres://', 'postgresql://', 1)
return uri | 5,350,941 |
def create_need():
"""
Créé le besoin en db
:return:
"""
student = Student.query.filter_by(id_user=session['uid']).first()
title = request.form.get('title')
description = request.form.get('description')
speaker_id = request.form.get('speaker_id')
estimated_tokens = int(request.form.... | 5,350,942 |
def insert_rolling_mean_columns(data, column_list, window):
"""This function selects the columns of a dataframe
according to a provided list of strings, re-scales its
values and inserts a new column in the dataframe with the
rolling mean of each variable in the column list and the
provided window le... | 5,350,943 |
def get_url_names():
""" Получение ссылок на контент
Returns:
Здесь - список файлов формата *.str
"""
files = ['srts/Iron Man02x26.srt', 'srts/Iron1and8.srt']
return files | 5,350,944 |
def test_delete_password_policy_false():
"""Will delete an password policy (Wrong password).
:return: Should return: False
"""
syn = syncope.Syncope(syncope_url="http://192.168.1.145:9080", username="admin", password="passwrd")
assert syn.delete_password_policy("json") == False | 5,350,945 |
def unix_utc_now() -> int:
"""
Return the number of seconds passed from January 1, 1970 UTC.
"""
delta = datetime.utcnow() - datetime(1970, 1, 1)
return int(delta.total_seconds()) | 5,350,946 |
def clear_ulog_cache():
""" clear/invalidate the ulog cache """
load_ulog_file.cache_clear() | 5,350,947 |
def _preload_specific_vars(env_keys: Set[str]) -> Store:
"""Preloads env vars from environ in the given set."""
specified = {}
for env_name, env_value in environ.items():
if env_name not in env_keys:
# Skip vars that have not been requested.
continue
specified[env_n... | 5,350,948 |
def _format_workflow_id(id):
"""
Add workflow prefix to and quote a tool ID.
Args:
id (str): ...
"""
id = urlparse.unquote(id)
if not re.search('^#workflow', id):
return urlparse.quote_plus('#workflow/{}'.format(id))
else:
return urlparse.quote_plus(id) | 5,350,949 |
def calc_log_sum(Vals, sigma):
"""
Returns the optimal value given the choice specific value functions Vals.
Parameters
----------
Vals : [numpy.array]
A numpy.array that holds choice specific values at common grid points.
sigma : float
A number that controls the variance of the ... | 5,350,950 |
def comment_create(request, post_pk):
"""記事へのコメント作成"""
post = get_object_or_404(Post, pk=post_pk)
form = CommentForm(request.POST or None)
if request.method == 'POST':
comment = form.save(commit=False)
comment.post = post
comment.save()
return redirect('blog:post_detail'... | 5,350,951 |
def tensor_from_var_2d_list(target, padding=0.0, max_len=None, requires_grad=True):
"""Convert a variable 2 level nested list to a tensor.
e.g. target = [[1, 2, 3], [4, 5, 6, 7, 8]]
"""
max_len_calc = max([len(batch) for batch in target])
if max_len == None:
max_len = max_len_calc
i... | 5,350,952 |
def make_w3(gateway_config=None):
"""
Create a Web3 instance configured and ready-to-use gateway to the blockchain.
:param gateway_config: Blockchain gateway configuration.
:type gateway_config: dict
:return: Configured Web3 instance.
:rtype: :class:`web3.Web3`
"""
if gateway_config is... | 5,350,953 |
def _log2_ratio_to_absolute(log2_ratio, ref_copies, expect_copies, purity=None):
"""Transform a log2 ratio to absolute linear scale (for an impure sample).
Does not round to an integer absolute value here.
Math::
log2_ratio = log2(ncopies / ploidy)
2^log2_ratio = ncopies / ploidy
... | 5,350,954 |
def test_eap_canned_failure_before_method(dev, apdev):
"""EAP protocol tests for canned EAP-Failure before any method"""
params = int_eap_server_params()
hapd = hostapd.add_ap(apdev[0], params)
bssid = apdev[0]['bssid']
hapd.request("SET ext_eapol_frame_io 1")
dev[0].connect("test-wpa2-eap", key... | 5,350,955 |
def fixt():
"""
Create an Exchange object that will be re-used during testing.
"""
mesh = df.UnitCubeMesh(10, 10, 10)
S3 = df.VectorFunctionSpace(mesh, "DG", 0)
Ms = 1
A = 1
m = df.Function(S3)
exch = ExchangeDG(A)
exch.setup(S3, m, Ms)
return {"exch": exch, "m": m, "A": A, ... | 5,350,956 |
def touch_emulator(ev, x, y):
"""
This emulates a touch-screen device, like a tablet or smartphone.
"""
if ev.type == pygame.MOUSEBUTTONDOWN:
if ev.button != 1:
return None, x, y
elif ev.type == pygame.MOUSEBUTTONUP:
if ev.button != 1:
return None, x, y
... | 5,350,957 |
def check_python_version() -> bool:
"""Check minimum Python version is being used.
Returns:
True if version is OK.
"""
if sys.version_info.major == 3 and sys.version_info.minor >= 6:
return True
logger.error(
"Aborting... Python version 3.6 or greater is required.\n"
... | 5,350,958 |
def output_matrix(matrix: list, padding_space: int):
"""
Build the status table shown by the sequencer.
Parameters
----------
matrix: list
padding_space: int
"""
max_field_length = []
for row in matrix:
for j, col in enumerate(row):
if matrix.index(row) == 0:
... | 5,350,959 |
def invert_dict(d):
"""
Invert dictionary by switching keys and values.
Parameters
----------
d : dict
python dictionary
Returns
-------
dict
Inverted python dictionary
"""
return dict((v, k) for k, v in d.items()) | 5,350,960 |
def run_trials(p, args):
"""
Run trials.
"""
# Model
m = p['model']
# Number of trials
try:
ntrials = int(args[0])
except:
ntrials = 100
ntrials *= m.nconditions
# RNN
rng = np.random.RandomState(p['seed'])
rnn = RNN(p['savefile'], {'dt': p['dt']}, verb... | 5,350,961 |
def init_output_dir(output_dir, force_overwrite):
"""Create output directory (and all intermediate dirs on the path) if it doesn't exist.
Args:
output_dir (str): output directory path.
force_overwrite (bool): If False and output dir is complete, raise RuntimeError.
Raises:
RuntimeE... | 5,350,962 |
def atom_present_in_geom(geom, b, tol=DEFAULT_SYM_TOL):
"""Function used by set_full_point_group() to scan a given geometry
and determine if an atom is present at a given location.
"""
for i in range(len(geom)):
a = [geom[i][0], geom[i][1], geom[i][2]]
if distance(b, a) < tol:
... | 5,350,963 |
def atof(value):
"""
locale.atof() on unicode string fails in some environments, like Czech.
"""
if isinstance(value, unicode):
value = value.encode("utf-8")
return locale.atof(value) | 5,350,964 |
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the Fibaro covers."""
async_add_entities(
[FibaroCover(device) for device in hass.data[FIBARO_DEVICES]["cover"]], True
) | 5,350,965 |
def r_group_list(mol, core_mol):
"""
This takes a mol and the common core and finds all the R-groups by
replacing the atoms in the ligand (which make up the common core) with
nothing.
This fragments the ligand and from those fragments we are able to
determine what our R-groups are. for any comm... | 5,350,966 |
def set_execution_target(backend_id='simulator'):
"""
Used to run jobs on a real hardware
:param backend_id: device name. List of available devices depends on the provider
example usage.
set_execution_target(backend_id='arn:aws:braket:::device/quantum-simulator/amazon/sv1')
"""
global dev... | 5,350,967 |
def add_submissions(contest_name, task_name, username, items):
"""
Add submissions from the given user to the given task
in the given contest. Each item corresponds to a submission,
and should contain a dictionary which maps formatted file names
to paths. For example, in batch tasks the format is "T... | 5,350,968 |
def multiply_table_f(x):
""" Takes an input and creates a multiplication table - uses f''
Parameters
___________
:param x: int: a number
Returns
___________
:return: Returns a multiplication table
"""
for i in range(1,x+1):
print(f'{x} * {i} = {x*i}')
return | 5,350,969 |
def segregate(str):
"""3.1 Basic code point segregation"""
base = bytearray()
extended = set()
for c in str:
if ord(c) < 128:
base.append(ord(c))
else:
extended.add(c)
extended = sorted(extended)
return bytes(base), extended | 5,350,970 |
def count_tetrasomic_indivs(lis) -> dict:
""" Count number of times that a chromosome is tetrasomic (present in four copies)
:returns counts_of_tetrasomic_chromosomes"""
counts_of_tetrasomic_chromosomes = {k: 0 for k in chr_range}
for kary_group in lis:
for index, chr_type in enumerate(chr_rang... | 5,350,971 |
def test_feature_multiStrategies_c_unknown(unleash_client):
"""
Feature.multiStrategies.C disabled for unknown users
"""
# Set up API
responses.add(responses.POST, URL + REGISTER_URL, json={}, status=202)
responses.add(responses.GET, URL + FEATURES_URL, json=json.loads(MOCK_JSON), status=200)
... | 5,350,972 |
def make_image_grid(images: np.ndarray, nrow: int = 1) -> np.ndarray:
"""Concatenate multiple images into a single image.
Args:
images (np.array):
Images can be:
- A 4D mini-batch image of shape [B, C, H, W].
- A 3D RGB image of shape [C, H, W].
... | 5,350,973 |
def drive_time_shapes(drive_time):
"""Simplify JSON response into a dictionary of point lists."""
isochrones = {}
try:
for shape in drive_time['response']['isoline']:
uid = str(int(shape['range'] / 60)) + ' minutes'
points = shape['component'][0]['shape']
point... | 5,350,974 |
def compute_transformation_sequence_case_1(cumprod, local_shape, ind,
sharded_leg_pos, pgrid):
"""
Helper function for `pravel`, see `pravel` for more details.
"""
ops = []
ndev = np.prod(pgrid)
if ndev % cumprod[ind - 1] != 0:
raise ValueError("reshaping not p... | 5,350,975 |
def fix_join_words(text: str) -> str:
"""
Replace all join ``urdu`` words with separate words
Args:
text (str): raw ``urdu`` text
Returns:
str: returns a ``str`` object containing normalized text.
"""
for key, value in WORDS_SPACE.items():
text = text.replace(key, value... | 5,350,976 |
def degree_of_appropriateness(attr_list,data_list,summarizers,summarizer_type,t3,letter_map_list,alpha_sizes,age,activity_level,flag=None,goals=None):
"""
Inputs:
- data: the database
- summarizer: the conclusive phrase of the summary
- summarizer_type: the type of summarizer
- t3: the de... | 5,350,977 |
def update_task_prices(task, discounts):
"""Update prices in task with given discounts and proper taxes."""
taxes = get_taxes_for_address(task.delivery_address)
for line in task:
if line.variant:
line.unit_price = line.variant.get_price(discounts, taxes)
line.tax_rate = get_... | 5,350,978 |
def constitutive_exp_normalization_raw(gene_db,constitutive_gene_db,array_raw_group_values,exon_db,y,avg_const_exp_db):
"""normalize expression for raw expression data (only for non-baseline data)"""
#avg_true_const_exp_db[affygene] = [avg_const_exp]
temp_avg_const_exp_db={}
for probeset in ar... | 5,350,979 |
def aws_env_variables(monkeypatch):
"""
When running in AWS Lambda, there are some environment variables that AWS creates and the tracer uses.
This fixture creates those environment variables.
"""
monkeypatch.setenv(
"_X_AMZN_TRACE_ID",
"RequestId: 4365921c-fc6d-4745-9f00-9fe9c516ede... | 5,350,980 |
def parse_rummager_topics(results):
"""
Parse topics from rummager results
"""
pages = []
for result in results:
pages.append(
Topic(
name=result['title'],
base_path=result['slug'],
document_type=DocumentType[result['format']]
... | 5,350,981 |
def test_get_all_links() -> None:
"""Test get_all_links func by adding
a link and retrieve it"""
delete_all_collections_datas()
prep_db_if_not_exist()
node_name: str = "test_node"
neigh_name: str = "test_neigh"
iface_name: str = "e1/1"
neigh_iface_name: str = "e2/1"
add_link(node_na... | 5,350,982 |
def format_last_online(last_online):
"""
Return the upper limit in seconds that a profile may have been
online. If last_online is an int, return that int. Otherwise if
last_online is a str, convert the string into an int.
Returns
----------
int
"""
if isinstance(last_online, str):
... | 5,350,983 |
def plot_inspection_data(table: pd.DataFrame, title: str, ylabel: str, decimals: int = 0) -> None:
"""
plots the inspection data for inspection tear sheets
:param table: the table to plot
:param title: the title for the plot
:param ylabel: y label for plot
:param decimals: amount of decimals to ... | 5,350,984 |
def get_currency_cross_historical_data(currency_cross, from_date, to_date, as_json=False, order='ascending', interval='Daily'):
"""
This function retrieves recent historical data from the introduced `currency_cross` from Investing
via Web Scraping. The resulting data can it either be stored in a :obj:`panda... | 5,350,985 |
def gen_project(project_name, project_revision, target, template, working_dir):
"""Generate and compiles the project defined in make_project.tcl.
Parameters
----------
working_dir : string
Working directory of the generation process
"""
gen_project_tcl(project_name, project_revision,
... | 5,350,986 |
def load_target(target_name, base_dir, cloud=False):
"""load_target load target from local or cloud
Parameters
----------
target_name : str
target name
base_dir : str
project base directory
cloud : bool, optional
load from GCS, by default False
Returns
-------
... | 5,350,987 |
def test_aspect_transfer_function():
"""
Assert aspect transfer function
"""
da = xr.DataArray(data_gaussian, dims=['y', 'x'], attrs={'res': 1})
da_aspect = aspect(da)
# default name
assert da_aspect.name == 'aspect'
assert da_aspect.dims == da.dims
assert da_aspect.attrs == da.attrs... | 5,350,988 |
def gradient(pixmap, ca, cb, eff, ncols):
""" Returns a gradient width the start and end colors.
eff should be Gradient.Vertical or Gradient.Horizontal
"""
x=0
y=0
rca = ca.red()
rDiff = cb.red() - rca
gca = ca.green()
gDiff = cb.green() - gca
bca = ca.blue()... | 5,350,989 |
def validate_filters(filters):
"""
>>> validate_filters('{"fileName": {"is": ["foo.txt"]}}')
>>> validate_filters('"')
Traceback (most recent call last):
...
chalice.app.BadRequestError: BadRequestError: The `filters` parameter is not valid JSON
>>> validate_filters('""')
Traceback (mo... | 5,350,990 |
def option_to_text(option):
"""Converts, for example, 'no_override' to 'no override'."""
return option.replace('_', ' ') | 5,350,991 |
def login(email, password):
"""
:desc: Logs a user in.
:param: email - Email of the user - required
password - Password of the user - required
:return: `dict`
"""
if email == '' or password == '':
return {'success': False, 'message': 'Email/Password field left blank.'}
... | 5,350,992 |
def test_tox_environments_use_max_base_python():
"""Verify base Python version specified for Tox environments.
Every Tox environment with base Python version specified should
use max Python version.
Max Python version is assumed from the .python-versions file.
"""
pyenv_version = max(
... | 5,350,993 |
def test_idempotence_after_controller_death(ray_start_stop, use_command: bool):
"""Check that CLI is idempotent even if controller dies."""
config_file_name = os.path.join(
os.path.dirname(__file__), "test_config_files", "basic_graph.yaml"
)
success_message_fragment = b"Sent deploy request succ... | 5,350,994 |
def register():
"""Register this generator.
"""
import agx.generator.uml
from agx.core.config import register_generator
register_generator(agx.generator.uml) | 5,350,995 |
def _cons8_89(m8, L88, L89, d_gap, k, Cp, h_gap):
"""dz constrant for edge gap sc touching edge, corner gap sc"""
term1 = 2 * h_gap * L88 / m8 / Cp # conv to inner/outer ducts
term2 = k * d_gap / m8 / Cp / L88 # cond to adj bypass edge
term3 = k * d_gap / m8 / Cp / L89 # cond to adj bypass corner
... | 5,350,996 |
def categories_split(df):
""" Separate the categories in their own columns. """
ohe_categories = pd.DataFrame(df.categories.str.split(';').apply(
lambda x: {e.split('-')[0]: int(e.split('-')[1]) for e in x}).tolist())
return df.join(ohe_categories).drop('categories', axis=1) | 5,350,997 |
def build_received_request(qparams, variant_id=None, individual_id=None, biosample_id=None):
""""Fills the `receivedRequest` part with the request data"""
request = {
'meta': {
'requestedSchemas' : build_requested_schemas(qparams),
'apiVersion' : qparams.apiVersion,
},
... | 5,350,998 |
def is_router_bgp_configured_with_four_octet(
device, neighbor_address, vrf, max_time=35, check_interval=10
):
""" Verifies that router bgp has been enabled with four
octet capability and is in the established state
Args:
device('obj'): device to check
vrf('vrf'): vrf to... | 5,350,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.