content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def pad_sequences(sequences, maxlen=None, dtype='int32', padding='post',
truncating='post', value=0.):
""" pad_sequences.
Pad each sequence to the same length: the length of the longest sequence.
If maxlen is provided, any sequence longer than maxlen is truncated to
maxlen. Truncation... | 35,700 |
def get_regions(service_name, region_cls=None, connection_cls=None):
"""
Given a service name (like ``ec2``), returns a list of ``RegionInfo``
objects for that service.
This leverages the ``endpoints.json`` file (+ optional user overrides) to
configure/construct all the objects.
:param service... | 35,701 |
def sol_dec(day_of_year):
"""
Calculate solar declination from day of the year.
Based on FAO equation 24 in Allen et al (1998).
:param day_of_year: Day of year integer between 1 and 365 or 366).
:return: solar declination [radians]
:rtype: float
"""
_check_doy(day_of_year)
return 0... | 35,702 |
def print_mro(cls):
"""Print the Method Resolution Order of a Class"""
print(', '.join(c.__name__ for c in cls.__mro__)) | 35,703 |
def configure_logging(conf):
"""Initialize and configure logging."""
root_logger = logging.getLogger()
root_logger.setLevel(getattr(logging, conf.loglevel.upper()))
if conf.logtostderr:
add_stream_handler(root_logger, sys.stderr)
if conf.logtostdout:
add_stream_handler(root_logger, s... | 35,704 |
def makeTestSuiteV201111():
"""Set up test suite using v201111.
Returns:
TestSuite test suite using v201111.
"""
suite = unittest.TestSuite()
suite.addTests(unittest.makeSuite(NetworkServiceTestV201111))
return suite | 35,705 |
def build_series(df):
"""
Return a series tuple where:
the first element is a list of dates,
the second element is the series of the daily-type variables,
the third element is the series of the current-type variables,
the fourth element is the series of the cum-type variables.
:param df: pd.... | 35,706 |
def test_ap_recipe_does_not_exist():
"""Test raise error if recipe does not exist."""
with pytest.raises(SystemExit) as exit:
cli.ap.parse_args('does_not_exit.cfg'.split())
assert exit.type == SystemExit
assert exit.value.code == 2 | 35,707 |
def lnZ(df_mcmc):
"""
Compute log Z(1) from PTMCMC traces stored in DataFrame.
Parameters
----------
df_mcmc : pandas DataFrame, as outputted from run_ptmcmc.
DataFrame containing output of a parallel tempering MCMC
run. Only need to contain columns pertinent to computing
ln... | 35,708 |
def p2h(p, T=293., P0=1000., m=28.966, unit_p='mbar'):
""" Returns an elevation from barometric pressure
Parameters
----------
p: {float, array}
barometric pressure in mbar or torr specified with unit_p
T: float, optional
Temperature in K
P0: float, optional
Pressure at ... | 35,709 |
def upon_teardown(f: Callable):
"""
Use this decorator to mark you ploogin function as a handler to call upon teardown.
"""
return PlooginEventHandler(event=PlooginEvents.TEARDOWN, f=f) | 35,710 |
def assertRegConditionalsForPpaRefModel(registration_requests,
conditional_registration_data):
"""Check the REG Conditionals for PPA creation model and raises an exception.
Performs the assert to check installationParam present in
registrationRequests or conditional regist... | 35,711 |
def get_train_test_indices_drone(df, frac, seed=None):
""" Split indices of a DataFrame with binary and balanced labels into balanced subindices
Args:
df (pd.DataFrame): {0,1}-labeled data
frac (float): fraction of indicies in first subset
random_seed (int): random seed used as random st... | 35,712 |
def get_subs(choice, chatid, obj):
"""Return subtitle download links."""
url = "https://yts-subs.com" + obj.get_url(chatid, int(choice))
try:
reponse = requests.get(url, headers=headers)
except Exception as e:
print(e)
raise Exception("Invalid url")
soup = BeautifulSoup(repon... | 35,713 |
def get_shape(rhoa_range):
"""
Find anomaly `shape` from apparent resistivity values framed to
the best points.
:param rhoa_range: The apparent resistivity from selected anomaly bounds
:attr:`~core.erp.ERP.anom_boundaries`
:type rhoa_range: array_like or list
... | 35,714 |
def elslib_D2(*args):
"""
* For elementary surfaces from the gp package (cones, cylinders, spheres and tori), computes: - the point P of parameters (U, V), and - the first derivative vectors Vu and Vv at this point in the u and v parametric directions respectively, and - the second derivative vectors Vuu, Vvv and... | 35,715 |
def readiness():
"""Handle GET requests that are sent to /api/v1/readiness REST API endpoint."""
return flask.jsonify({}), 200 | 35,716 |
def camino_minimo(origen,dest,grafo,aeropuertos_por_ciudad,pesado=True):
"""Obtiene el camino minimo de un vertice a otro del grafo"""
camino=[]
costo=float("inf")
for aeropuerto_i in aeropuertos_por_ciudad[origen]:
for aeropuerto_j in aeropuertos_por_ciudad[dest]:
if pesado:
... | 35,717 |
def test_dict_lookup(ami_file_dict):
"""AMI lookup using json url."""
sample_dict = {
'us-east-1': {
'base_fedora': 'ami-xxxx',
},
'us-west-2': {
'tomcat8': 'ami-yyyy',
}
}
ami_file_dict.return_value = sample_dict
assert ami_lookup(region='us-e... | 35,718 |
def extract_name_from_uri_or_curie(item, schema=None):
"""Extract name from uri or curie
:arg str item: an URI or curie
:arg dict schema: a JSON-LD representation of schema
"""
# if schema is provided, look into the schema for the label
if schema:
name = [record["rdfs:label"] for record... | 35,719 |
def test_expand_to_p1(mtz_by_spacegroup):
"""Test DataSet.expand_to_p1() for common spacegroups"""
x = rs.read_mtz(mtz_by_spacegroup)
expected = rs.read_mtz(mtz_by_spacegroup[:-4] + '_p1.mtz')
expected.sort_index(inplace=True)
result = x.expand_to_p1()
result.sort_index(inplace=True)
expec... | 35,720 |
def get_gcc_timeseries(site, roilist_id, nday=3):
"""
Read in CSV version of summary timeseries and return
GCCTimeSeries object.
"""
# set cannonical dir for ROI Lists
roidir = os.path.join(config.archive_dir, site, "ROI")
# set cannonical filename
gcc_tsfile = site + "_" + roilist_id ... | 35,721 |
def download_graph(coordinates, distances):
"""
Criação do grafo de ruas do OSM a partir das coordenadas solicitadas
"""
max_distance = max(distances)
G = False
print('Fetching street network')
for coordinate in tqdm(coordinates, desc='Downloading'):
if G: # "soma" (merge) com ... | 35,722 |
def cmd_execute_io(*a):
"""parse and format opcodes"""
for cmd in a:
cmd = cmd + " > tmp.out"
os.system(cmd)
with open("tmp.out") as f:
# print("".join(x for x in f.readlines()))
a = "".join(x for x in f.readlines())
b = "".join("\\x" + a[x : x + 2] fo... | 35,723 |
def external_forces(cod_obj):
"""actual cone position"""
x_pos,y_pos,z_pos =cod_obj.pos_list[-1]
"""
Drift vector components
Drift signal//all directions
"""
divx = forcep['divxp']([x_pos,y_pos,z_pos])[0]
divy = forcep['divyp']([x_pos,y_pos,z_pos])[0]
divz = forcep['divzp... | 35,724 |
def outlier_filter(df, thrsh, rng, lim):
""""Calculate absolute value of difference for n steps in range; replace outliers > threshold with NaN, then linearly interpolate new values. Takes inputs of pandas DataFrame (df), threshold change (thrsh), steps range (rng), and limit (lim)"""
for n in np.arange(rng)*-1... | 35,725 |
def charis_font_spec_css():
"""Font spec for using CharisSIL with Pisa (xhtml2pdf)."""
return """
@font-face {{
font-family: 'charissil';
src: url('{0}/CharisSIL-R.ttf');
}}
@font-face {{
font-family: 'charissil';
font-style: italic;
src: url('{0}/CharisSIL-I.... | 35,726 |
def set_symbols(pcontracts,
dt_start="1980-1-1",
dt_end="2100-1-1",
n=None,
spec_date={}): # 'symbol':[,]
"""
Args:
pcontracts (list): list of pcontracts(string)
dt_start (datetime/str): start time of all pcontracts
dt_end ... | 35,727 |
def estimate_vol_gBM(data1, data2, time_incr=0.1):
""" Estimate vol and correlation of two geometric Brownian motion samples with time samples on a grid with mesh size time_incr using estimate_vol_2d_rv_incr, the drift parameter and mean rev paramters are set to 0.
----------
args:
data1 data array... | 35,728 |
def check_quarantine(av_quarentine_file):
"""Check if the quarantine is over."""
in_quarantine = True
try:
with open(av_quarentine_file, 'r', encoding="utf-8") as ff_av:
text = ff_av.readline()
quar_str, av_run_str = text.split(':')
quarantine = int(quar_str)
a... | 35,729 |
def step_pattern():
"""
Based on the buffer length determined through fuzzing (previous step), we will create and send
a unique pattern which will help us finding the offset
"""
global current_step
current_step = 1
show_step_banner('[1] Finding offset')
# Get length from fuzzing
show_prompt_text('Enter the len... | 35,730 |
def get_coin_total(credentials_file: str, coin: str) -> float:
"""
Get the current total amount of your coin
Args:
credentials_file: A JSON file containing Coinbase Pro credentials
coin: The coin requested
Returns:
coin_total: The total amount of the coin you hold in your accou... | 35,731 |
def datetime_to_serial(dt):
"""
Converts the given datetime to the Excel serial format
"""
if dt.tzinfo:
raise ValueError("Doesn't support datetimes with timezones")
temp = datetime(1899, 12, 30)
delta = dt - temp
return delta.days + (float(delta.seconds) + float(delta.microseconds... | 35,732 |
def shellsort(input_list):
"""Sort the given list using shellsort technique.
:param input_list: Given list of items
"""
# Find middle point
gap = len(input_list) / 2
while gap > 0:
for i in range(gap, len(input_list)):
tmp = input_list[i]
j = i
while ... | 35,733 |
def compute_transitive_closure(graph):
"""Compute the transitive closure of a directed graph using Warshall's
algorithm.
:arg graph: A :class:`collections.abc.Mapping` representing a directed
graph. The dictionary contains one key representing each node in the
graph, and this key maps t... | 35,734 |
def A_intermediate(f1, f2, f3, v1, v2, v3, d1, d3):
"""Solves system of equations for intermediate amplitude matching"""
Mat = np.array(
[
[1.0, f1, f1 ** 2, f1 ** 3, f1 ** 4],
[1.0, f2, f2 ** 2, f2 ** 3, f2 ** 4],
[1.0, f3, f3 ** 2, f3 ** 3, f3 ** 4],
[0.... | 35,735 |
def server(
ctx, root_dir, path, host, port, workers, encrypt_password, username, password
):
"""开启 HTTP 服务"""
api = _recent_api(ctx)
if not api:
return
encrypt_password = encrypt_password or _encrypt_password(ctx)
if username:
assert password, "Must set password"
start_s... | 35,736 |
def _evaluate_criterion(criterion, params, criterion_kwargs):
"""Evaluate the criterion function for the first time.
The comparison_plot_data output is needed to initialize the database.
The criterion value is stored in the general options for the tao pounders algorithm.
Args:
criterion (calla... | 35,737 |
def group_by(collection, callback=None):
"""Creates an object composed of keys generated from the results of running
each element of a `collection` through the callback.
Args:
collection (list|dict): Collection to iterate over.
callback (mixed, optional): Callback applied per iteration.
... | 35,738 |
def lemmatize_verbs(words):
"""lemmatize verbs in tokenized word list"""
lemmatizer = WordNetLemmatizer()
lemmas = []
for word in words:
lemma = lemmatizer.lemmatize(word, pos='v')
lemmas.append(lemma)
return lemmas | 35,739 |
def tempf():
""" Create a tempfile write 5 bytes
"""
_, tempf = tempfile.mkstemp()
tempf = Path(tempf)
# make a temp file with 5 bytes
tempf.write_bytes(b"tempo")
yield tempf
tempf.unlink() if tempf.exists() else None | 35,740 |
def compare_streams(
execution: riberry.model.job.JobExecution,
expected: Dict[str, Dict[str, int]]
):
""" Compares the given streams with the execution's actual streams.
Example of `expected` parameter:
{
"STREAM_NAME_1": { # stream name
"STEP_NAME_1": 1, # key:... | 35,741 |
def remove_install_type(type_func):
"""Remove the registered type_func for installing."""
try:
INSTALL_TYPES.pop(type_func)
except:
pass
try:
INSTALL_TYPES.remove(type_func)
except:
pass | 35,742 |
def loadfromensembl(homology, kingdom='fungi', sequence='cdna',
additional='type=orthologues', saveonfiles=False, normalized=False,
setnans=False, number=0, by="entropy", using="normal", getCAI=None):
"""
Load from ensembl the datas required in parameters ( look at PyCUB.... | 35,743 |
def build_json_schema_docs():
"""Build markdown from JSON Schema"""
header = "# JSON Schema for ISCC Metadata\n\n"
schemata = [
"iscc-jsonld.yaml",
"iscc-minimal.yaml",
"iscc-basic.yaml",
"iscc-embeddable.yaml",
"iscc-extended.yaml",
"iscc-technical.yaml",
... | 35,744 |
def run_executable(string_to_execute,
project_info,
verbosity,
exit_on_warning,
launcher_arguments=None,write_di=True):
""" @brief Executes script/binary
@param executable String pointing to the script/binary to execute
@par... | 35,745 |
def dereference(reference_buffer, groups):
"""
find a reference within a group
"""
if len(reference_buffer)>0:
ref_number = int(''.join(reference_buffer))-1
return groups[ref_number % len(groups)] +' '
return '' | 35,746 |
def get_main_corpora_info():
"""Create dict with the main corpora info saved in CORPORA_SOURCES
:return: Dictionary with the corpora info to be shown
:rtype: dict
"""
table = []
for corpus_info in CORPORA_SOURCES:
corpus_id = CORPORA_SOURCES.index(corpus_info) + 1
props = corpus... | 35,747 |
def _add_unreachable_server(ip=None):
""" Add ip to unreachable_servers list """
if ip:
if ip not in obj.unreachable_servers:
collectd.debug("%s adding '%s' to unreachable servers list: %s" %
(PLUGIN, ip, obj.unreachable_servers))
obj.unreachable_serve... | 35,748 |
def start_compare_analysis(api_token, project_id, kind, url, username, password, target_branch, target_revision):
"""
Get the project identifier from the GraphQL API
:param api_token: the access token to the GraphQL API
:param project_id: identifier of the project to use as source
:param kind: kind ... | 35,749 |
def _install(x: str, update: bool, quiet: bool = False):
"""Install an Earth Engine JavaScript module.
The specified module will be installed in the ee_extra module path.
Args:
x: str
update: bool
"""
if _check_if_module_exists(x) and not update:
if not quiet:
p... | 35,750 |
def ClosedNamedTemporaryFile(data: str, mode: str = "w") -> str:
"""
Temporary file that can be read by subprocesses on Windows.
Source: https://stackoverflow.com/a/46501017
"""
file = tempfile.NamedTemporaryFile(delete=False, mode=mode)
try:
with file:
file.write(data)
... | 35,751 |
def copy_package_files(from_directory, to_directory, hard_links=True):
"""
Copy package files to a temporary directory, using hard links when possible.
:param from_directory: The pathname of a directory tree suitable for
packaging with ``dpkg-deb --build``.
:param to_director... | 35,752 |
def parse():
"""Parse the command line input arguments."""
parser = argparse.ArgumentParser()
parser.add_argument('--version', action='version',
version='f90nml {0}'.format(f90nml.__version__))
parser.add_argument('--group', '-g', action='store',
help="s... | 35,753 |
def get_matrix_in_format(original_matrix, matrix_format):
"""Converts matrix to format
Parameters
----------
original_matrix : np.matrix or scipy matrix or np.array of np. arrays
matrix to convert
matrix_format : string
format
Returns
-------
matrix : scipy matrix
... | 35,754 |
def generate_batches(data,
n_epochs=5,
batch_size=64,
shuffle=True,
random_state=75894,
batches_per_group=-1,
verbose=1):
"""Generate a series of batches.
Args:
data: ... | 35,755 |
def get_haystack_response(res, debug=False, chatbot='QA'):
"""
Function that filters null answers from the haystack response. NOTE: The necessity of this suggests that
Deepset's no_ans_boost default of 0 may not be functioning for FARMReader.
:param res:
:param chatbot: Type of chatbot to get respon... | 35,756 |
def _convert_name(name, recurse=True, subs=None):
"""
From an absolute path returns the variable name and its owner component in a dict.
Names are also formatted.
Parameters
----------
name : str
Connection absolute path and name
recurse : bool
If False, treat the top level ... | 35,757 |
async def test_raises_if_hardware_module_has_gone_missing(
subject: ThermocyclerMovementFlagger,
state_store: StateStore,
hardware_api: HardwareAPI,
decoy: Decoy,
) -> None:
"""It should raise if the hardware module can't be found by its serial no."""
decoy.when(state_store.labware.get_location(... | 35,758 |
def test_dual_ne_dates(df, right):
"""
Test output for multiple conditions. `!=`
"""
filters = ["A", "Integers", "E", "Dates"]
expected = (
df.assign(t=1)
.merge(right.assign(t=1), on="t")
.query("A != Integers and E != Dates")
.reset_index(drop=True)
)
expec... | 35,759 |
def memtrace(**kwargs):
"""
Turn on memory tracing within a certain context.
Parameters
----------
kwargs : dict
Named options to pass to setup.
"""
options = _Options(**kwargs)
if options.outfile is None:
options.outfile = 'mem_trace.raw'
if options.min_mem is None:... | 35,760 |
def populate_sample_data():
""" Populates the database with sample data """
with db:
u = User(login_id="test", password=pbkdf2_sha256.hash("test"), role="ST",
email="s1@junk.ss", first_name="TEST", last_name="USER", inst_id="CSB1000")
u.save()
u = User(login_id="admin", password... | 35,761 |
def _orthogonalize(constraints, X):
"""
Orthogonalize spline terms with respect to non spline terms.
Parameters
----------
constraints: numpy array
constraint matrix, non spline terms
X: numpy array
spline terms
Returns
-------
constrained_X: num... | 35,762 |
def get_shell_output(cmd,verbose=None):
"""Function to run a shell command and return returncode, stdout and stderr
Currently (pyrpipe v 0.0.4) this function is called in
getReturnStatus(), getProgramVersion(), find_files()
Parameters
----------
cdm: list
command to run
ve... | 35,763 |
def property_removed_from_property_group_listener(sender, instance, **kwargs):
"""
This is called before a GroupsPropertiesRelation is deleted, in other
words when a Property is removed from a PropertyGroup.
Deletes all ProductPropertyValue which are assigned to the property and
the property group ... | 35,764 |
def tril(input, diagonal=0, name=None):
"""
This op returns the lower triangular part of a matrix (2-D tensor) or batch
of matrices :attr:`input`, the other elements of the result tensor are set
to 0. The lower triangular part of the matrix is defined as the elements
on and below the diagonal.
... | 35,765 |
def csv_to_objects(csvfile_path):
"""
Read a CSV file and convert it to a Python dictionary.
Parameters
----------
csvfile_path : string
The absolute or relative path to a valid CSV file.
Returns
-------
dict
A dict containing a dict of show/episode entries and a dict of movie entries.
"""
logg... | 35,766 |
def rename_and_merge_columns_on_dict(data_encoded, rename_encoded_columns_dict, **kwargs):
"""
Parameters
----------
data_encoded: pandas.DataFrame with numerical columns
rename_encoded_columns_dict: dict of columns to rename in data_encoded
**kwargs
inplace:bool, default=False
decides ... | 35,767 |
def _get_public_props(obj) -> List[str]:
"""Return the list of public props from an object."""
return [prop for prop in dir(obj) if not prop.startswith('_')] | 35,768 |
def get_vd_html(
voronoi_diagram: FortunesAlgorithm,
limit_sites: List[SiteToUse],
xlim: Limit,
ylim: Limit,
) -> None:
"""Plot voronoi diagram."""
figure = get_vd_figure(
voronoi_diagram, limit_sites, xlim, ylim, voronoi_diagram.SITE_CLASS
)
html = get_html(figure)
return ht... | 35,769 |
def handle_rssadditem(bot, ievent):
""" arguments: <feedname> <token> - add an item (token) to a feeds tokens to be displayed, see rss-scan for a list of available tokens. """
try: (name, item) = ievent.args
except ValueError: ievent.missing('<feedname> <token>') ; return
if ievent.options and ievent.op... | 35,770 |
def test_class_default_constructor(capfd):
"""Test to validate that the main method is called."""
result = "Hello World!"
hello_world = HelloWorld()
print(type(hello_world))
assert type(hello_world) is not None
hello_world.print_name()
out, err = capfd.readouterr()
assert result in out | 35,771 |
def test_chip_properties_NO_ROM_PORTS():
"""Ensure the chip has been set with the correct number of ROM ports."""
assert chip.NO_ROM_PORTS == 16 | 35,772 |
def drawimage(xmin, xmax, ymin, ymax, width, height, data, model=0):
"""
Draw an image into a given rectangular area.
**Parameters:**
`xmin`, `ymin` :
First corner point of the rectangle
`xmax`, `ymax` :
Second corner point of the rectangle
`width`, `height` :
The width... | 35,773 |
def Test(directory):
""" Main testing function """
""" Testing function to compare relation results of Canary vs the Gold Standard """
# Stores what type of files we are looking for in the directory
types = ("*txt", "*.ann")
# Stores the files that match those types (same filename has both .txt & ... | 35,774 |
def sample_normal_mean_jeffreys(s1, ndata, prec):
"""Samples the mean of a normal distribution"""
##
return rn.normal(s1 / ndata, 1 / np.sqrt(prec * ndata)) | 35,775 |
def copy_tree(
src, dst, preserve_mode=1, preserve_times=1,
preserve_symlinks=0, update=0, verbose=0, dry_run=0,
condition=None):
"""
Copy an entire directory tree 'src' to a new location 'dst'. Both
'src' and 'dst' must be directory names. If 'src' is not a
directory, raise D... | 35,776 |
def pipeline_report_build(submission: Submission, stdout: str, passed: bool, **_):
"""
POSTed json should be of the shape:
{
"stdout": "build logs...",
"passed": True
}
:param submission:
:param stdout:
:param passed:
:return:
"""
if len(stdout) > MYSQL_TEXT_MAX_LE... | 35,777 |
def flatten(episode, context_length, include_labels=True, delimiter='\n'):
"""
Flatten the data into single example episodes.
This is used to make conditional training easier and for a fair comparison of
methods.
"""
context = deque(maxlen=context_length if context_length > 0 else None)
new... | 35,778 |
def calc_binsize(num_bins, t_start, t_stop):
"""
Calculates the stop point from given parameter.
Calculates the size of bins :attr:`binsize` from the three parameter
:attr:`num_bins`, :attr:`t_start` and :attr`t_stop`.
Parameters
----------
num_bins: int
Number of bins
t_start:... | 35,779 |
def flash_leds(dur):
"""Flashes LEDs
"""
leds.on()
time.sleep(dur)
leds.off() | 35,780 |
def salutation(phrase = 'Bonjour', nom=''):
"""
Fonction qui salue quelqu'un
"""
print(phrase + ' ' + nom + ' !') | 35,781 |
def d_within(geom, gdf, distance):
"""Find the subset of a GeoDataFrame within some distance of a shapely geometry"""
return _intersects(geom, gdf, distance) | 35,782 |
def make_params(args, nmax=None):
"""Format GET parameters for the API endpoint.
In particular, the endpoint requires that parameters be sorted
alphabetically by name, and that filtering is done only on one
parameter when multiple filters are offered.
"""
if nmax and len(args) > nmax:
... | 35,783 |
def visualize_multiple_categories():
"""Example to show how to visualize images that activate multiple categories
"""
# Build the VGG16 network with ImageNet weights
model = VGG16(weights='imagenet', include_top=True)
print('Model loaded.')
# The name of the layer we want to visualize
# (se... | 35,784 |
def debug(msg: str, always: bool = False, icon: str = "🐞") -> None:
"""Print debug message."""
_echo(icon=icon, msg=msg, always=always, fg=typer.colors.MAGENTA) | 35,785 |
def create_authors(filename, obj, database):
"""
Wrapper function that extracts all authors and their affiliations
from the json object. Each of the authors and their affiliations
are created and connected.
"""
authors = []
for item in obj['metadata']['authors']:
# Iterate json obj ... | 35,786 |
def list_available_providers():
"""
Lists available providers and regions
"""
regions = config.AVAILABLE_CLOUD_REGIONS
for k,v in regions.iteritems():
print('{0:12s}: {1}'.format(k, ', '.join(regions[k].keys()))) | 35,787 |
def remap(value, oldMin, oldMax, newMin, newMax):
"""
Remaps the value to a new min and max value
Args:
value: value to remap
oldMin: old min of range
oldMax: old max of range
newMin: new min of range
newMax: new max of range
Returns:
The remapped value i... | 35,788 |
def test_suspend_user_by_id():
"""Will suspend the user for user id 1.
:return: Should return: suspended
"""
syn = syncope.Syncope(syncope_url="http://192.168.1.145:9080", username="admin", password="password")
user_data = syn.suspend_user_by_id(1)
assert user_data['status'] == "suspended" | 35,789 |
def test_sha_key():
"""
Ensure we conform to https://tools.ietf.org/html/rfc3414#appendix-A.3.2
"""
engine_id = unhexlify("000000000000000000000002")
hasher = password_to_key(hashlib.sha1, 20)
result = hasher(b"maplesyrup", engine_id)
expected = unhexlify("6695febc9288e36282235fc7151f128497b... | 35,790 |
async def construct_unit_passport(unit: Unit) -> str:
"""construct own passport, dump it as .yaml file and return a path to it"""
passport = _get_passport_dict(unit)
path = f"unit-passports/unit-passport-{unit.uuid}.yaml"
_save_passport(unit, passport, path)
return path | 35,791 |
def certification_to_csv(stats, filepath, product_id):
"""Writes certification outputs to the file specified.
Parameters
----------
stats : list of dict
list of statistical outputs from the function
`thermostat.compute_summary_statistics()`
filepath : str
filepath specificat... | 35,792 |
def get_ipns_link(name: str) -> str:
"""Get the ipns link with the name of it which we remember it by
Args:
name (str): Name we call ipns link
Returns:
str: Returns the IPNS url
Raises:
ValueError: if link not found
>>> import random
>>> key_name = str(random.getrand... | 35,793 |
def joint_sim(num_samp, num_dim, noise=0.5):
"""
Function for generating a joint-normal simulation.
:param num_samp: number of samples for the simulation
:param num_dim: number of dimensions for the simulation
:param noise: noise level of the simulation, defaults to 0.5
:return: the data matri... | 35,794 |
def main(phases=['SKS','SKKS'],batch=False,evt_sta_list=None):
"""
Main - call this function to run the interface to sheba
This function depends on the existence of a station list file specified by statlist and you have sac data alreayd downloaded
Path should point to the directory that you want the she... | 35,795 |
def test_vector_interpolation_cross_section():
"""Test cross section interpolation."""
vec = plonk.visualize.interpolation.vector_interpolation(
x_data=X_DATA,
y_data=Y_DATA,
x_position=XX,
y_position=YY,
z_position=ZZ,
extent=EXTENT,
smoothing_length=HH,
... | 35,796 |
def calculate_seasonal_tilt(axial_tilt, degrees):
"""Find the seasonal tilt offset from axial tilt and orbit (in degrees)
axial_tilt -- The planet's tilt. e.g. Earth's tilt is 23.44 degrees.
degrees -- How far along is the planet in its orbit around its star?
(between 0 and 360. 0/360 and 180 are eq... | 35,797 |
def extractWithoutOrder(query, choices, processor=default_processor, scorer=default_scorer, score_cutoff=0):
"""Select the best match in a list or dictionary of choices.
Find best matches in a list or dictionary of choices, return a
generator of tuples containing the match and its score. If a dictionary
... | 35,798 |
def mark_dts_nn(marked_dict):
"""Loops through a dictionary representation of the XML-text where determiners have been "focus"-marked.
Finds the "focus"-marked determiners and looks for their nouns from the words after the determiner until the end of the current sentence. The found noun is then marked with "foc... | 35,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.