content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def is_phone_in_call_video_tx_enabled(log, ad):
"""Return if phone in tx_enabled video call.
Args:
log: log object.
ad: android device object
Returns:
True if phone in tx_enabled video call.
"""
return is_phone_in_call_video_tx_enabled_for_subscription(
log, ad, get... | 40,000 |
def fit_t1_results(times: Sequence[float], z_expectations: Sequence[float],
z_std_errs: Sequence[float] = None, param_guesses: tuple = (1.0, 15, 0.0)) \
-> ModelResult:
"""
Wrapper for fitting the results of a T1 experiment for a single qubit; simply extracts key
parameters and pa... | 40,001 |
def find_mapping_net_assn(context, network_id, host_id):
"""
Takes in a network id and the host id to return an SEA that creates that
mapping. If there's no association found, a None is returned
:context: The context used to call the dom API
:network_id: The neutron network id.
:host_id: The Ho... | 40,002 |
def get_emergency_passphrase():
"""Returns emergency passphrase provided in environment variable"""
passphrase = os.environ.get(EMERGENCY_PASSPHRASE_VARIABLE)
if passphrase is None:
raise MissingVariableError(EMERGENCY_PASSPHRASE_VARIABLE)
return passphrase | 40,003 |
def bubble_sort(seq):
"""Inefficiently sort the mutable sequence (list) in place.
seq MUST BE A MUTABLE SEQUENCE.
As with list.sort() and random.shuffle this does NOT return
"""
changed = True
while changed:
changed = False
for i in xrange(len(seq) - 1):
if seq... | 40,004 |
def numba_cuda_DeviceNDArray(xd_arr):
"""Return cupy.ndarray view of a xnd.xnd in CUDA device.
"""
cbuf = pyarrow_cuda_buffer(xd_arr)
# DERIVED
return pyarrow_cuda_buffer_as.numba_cuda_DeviceNDArray(cbuf) | 40,005 |
def create_dataset(project, dataset_id, description, tags, app_creds):
"""
Create a dataset with the given parameters.
:param project: The project_id used to define the dataset.
:param dataset_id: The string to name the dataset with.
:param description: A string to use to describe the dataset.
... | 40,006 |
def deg2rad(dd):
"""Convertit un angle "degrés décimaux" en "radians"
"""
return dd/180*pi | 40,007 |
def createView(database, view_name, map_func):
"""
Creates and returns a Cloudant view.
"""
my_design_document = design_document.DesignDocument(database, "_design/names")
my_design_document.add_view(view_name, map_func)
return view.View(my_design_document, view_name, map_func) | 40,008 |
def find_modifiable_states(state_data):
""" Find indices into the state_data array,
Args:
state_data (ndarray): States array, in the form returned by cmd_states.get_cmd_states.fetch_states
Returns:
(ndarray): Numeric index of states that represent dwells with modifiable chip counts
... | 40,009 |
def get_tool_def( trans, hda ):
""" Returns definition of an interactive tool for an HDA. """
job = get_dataset_job( hda )
# TODO: could use this assertion to provide more information.
# assert job is not None, 'Requested job has not been loaded.'
if not job:
return None
tool = tran... | 40,010 |
def clean_object_caches(obj):
"""
Clean all object caches on the given object
"""
global _TYPECLASSMODELS, _OBJECTMODELS
if not _TYPECLASSMODELS:
from src.typeclasses import models as _TYPECLASSMODELS
#if not _OBJECTMODELS:
# from src.objects import models as _OBJECTMODELS
#p... | 40,011 |
async def async_turn_on(
hass,
entity_id=ENTITY_MATCH_ALL,
) -> None:
"""Turn all or specified humidifier on."""
data = {ATTR_ENTITY_ID: entity_id} if entity_id else {}
await hass.services.async_call(DOMAIN, SERVICE_TURN_ON, data, blocking=True) | 40,012 |
def create_multi_file_info(directory,
files,
piece_length):
"""
Return dictionary with the following keys:
- pieces: concatenated 20-byte-sha1-hashes
- name: basename of the directory (default name of all torrents)
- files: a list of dic... | 40,013 |
def get_datasource_bounding_box(datasource_uri):
"""Get datasource bounding box where coordinates are in projected units.
Args:
dataset_uri (string): a uri to a GDAL dataset
Returns:
bounding_box (list):
[upper_left_x, upper_left_y, lower_right_x, lower_right_y] in
... | 40,014 |
def set_inline_label(ax, line, label=None,
xval=None, size=6, alpha=ALPHAS['translucent'],
color=None, ha='center', va='center',
bbox=dict(facecolor=COLORS['white'],
edgecolor=COLORS['white'],
al... | 40,015 |
def instance_id(instance):
"""
Return id of instance in hex form.
Helps in logs/debugs/development troubleshooting.
"""
instance_id = hex(id(instance))[2:] # remove leading 0x
return instance_id | 40,016 |
def distributions_to_lower_upper_bounds(model, negative_allowed=[], ppf=(0.05,0.95), save_to_model=False):
"""
Converts distributions to uniform distributions by taking specified ppf
Args:
model: The model object
negative_allowed: list of params which are allowed to be negative
ppf:... | 40,017 |
def refresh_database(engine, server, jobs, source_obj, container_obj):
"""
This function actually performs the refresh
engine:
server: Engine object
jobs: list containing running jobs
source_obj: source object used to refresh from snapshot or timeflow
container_obj: VDB container
"""
... | 40,018 |
def create_feature_indices(header):
"""
Function to return unique features along with respective column indices
for each feature in the final numpy array
Args:
header (list[str]): description of each feature's possible values
Returns:
feature_indices (dict): unique feature names as... | 40,019 |
def lower(word):
"""Sets all characters in a word to their lowercase value"""
return word.lower() | 40,020 |
def band_pass(data, scale_one, scale_two):
"""
Band pass filter
Difference of two gaussians
G(data, s1) - G(data, s2)
"""
bp = gaussian(data, scale=scale_one) - gaussian(data, scale=scale_two)
return bp | 40,021 |
def _in_dir(obj, attr):
"""Simpler hasattr() function without side effects."""
return attr in dir(obj) | 40,022 |
def file_exists(work_dir, path):
"""
goal: check if file exists
type: (string, string) -> bool
"""
prev_dir = os.getcwd()
try:
os.chdir(work_dir)
if os.path.exists(path) and os.path.isfile(path):
return True
else:
return False
os.chdir(pr... | 40,023 |
def write_intermediate_inputs(synthesis_dir, model_wrapper, targets):
"""Write intermediate inputs"""
with open(f"{synthesis_dir}/{constants.MODEL_WRAPPER_FILENAME}", "wb") as model_wrapper_file:
cloudpickle.dump(model_wrapper, model_wrapper_file)
targets = np.save(f"{synthesis_dir}/{constants.TARGE... | 40,024 |
def save_speech(data, p):
""" Saves mic data to temporary WAV file. Returns filename of saved
file """
filename = 'output'
# writes data to WAV file
data = ''.join(data)
wf = wave.open(filename + '.wav', 'wb')
wf.setnchannels(1)
wf.setsampwidth(p.get_sample_size(pyaudio.paInt16))
... | 40,025 |
def job_submit(address: Optional[str], job_id: Optional[str],
runtime_env: Optional[str], runtime_env_json: Optional[str],
working_dir: Optional[str], entrypoint: Tuple[str]):
"""Submits a job to be run on the cluster.
Example:
>>> ray job submit -- python my_script.py --a... | 40,026 |
def load_stat_features_others_windows(patient_list, data_path="statistic_features.csv",
statistics_list=["std_x", "std_y", "std_z"], n_others_windows=40):
"""
Returns:
X_all_data - ndarray of shape(n_records, n_new_features), feature-vector consist of features of curre... | 40,027 |
def map_format(value, pattern):
"""
Apply python string formatting on an object:
.. sourcecode:: jinja
{{ "%s - %s"|format("Hello?", "Foo!") }}
-> Hello? - Foo!
"""
return soft_unicode(pattern) % (value) | 40,028 |
def Cadzow(Xk, K, N, tol_ratio=10000, max_iter=10):
"""
Implement Cadzow denoising
Parameters
----------
Xk : signal to denoise
K : number of most significant members to take
N : number of samples in the signal
tol_ratio : min ratio of (K+1)th singular value / Kth singular value
... | 40,029 |
def toposortGroup(candidateIrefs):
"""Given a set of IRefs, returns a list of irefs toposorted based on the include graph."""
graph = {}
for iRef in candidateIrefs:
graph[iRef] = set(includePaths(iRef))
candidateSet = set(candidateIrefs)
output = []
for group in toposort.toposort(graph):... | 40,030 |
def make_template(template):
"""Given an OpenSearch template, return a Template instance for it.
>>> template = make_template('http://localhost/search?q={term}')
>>> template.substitute(term='opensearch syntax')
'http://localhost/search?q=opensearch+syntax'
>>>
"""
terms = decompose_templat... | 40,031 |
def search(T, dist, w, i=0):
"""Searches for w[i:] in trie T with distance at most dist
"""
if i == len(w):
if T is not None and T.is_word and dist == 0:
return ""
else:
return None
if T is None:
return None
f = search(T.s[w[i]], dist, w, i + 1) ... | 40,032 |
def get_weighted_embeddings(embeddings, weights):
"""Multiply a sequence of word embeddings with their weights
:param embeddings: a sequence of word embeddings got from
embedding_lookup, size of [batch_size, seq_len, embed_dim]
:param weights: a sequence of weights for each word, size of [batch_size,... | 40,033 |
def importWidgetModules(basicWidgets):
""" importWidgetModules(basicWidgets: widget) -> None
Find all widget package under ./widgets/* to add to the spreadsheet registry
"""
packageName = __name__.lower().endswith('.init') and \
__name__[:-5] or __name__
widgetDir = os.path.join(
... | 40,034 |
def merge_pdfs(input_pdfs, output_pdf):
"""Combine multiple pdfs to single pdf.
Args:
input_pdfs (list): List of path files.
output_pdf (str): Output file.
"""
pdf_merger = PdfFileMerger()
for path in input_pdfs:
pdf_merger.append(path)
with open(output_pdf, 'wb') as fi... | 40,035 |
def _adjust_values(females, males):
"""
Adjusting the values as the man moves in with the woman
"""
females = females.copy()
males = males.copy()
males.loc[:,"hid"] = females["hid"].tolist()
males.loc[:,"east"] = females["east"].tolist()
males.loc[:,"hhweight"] = females["hhweight"].tol... | 40,036 |
def create_other_features(data):
"""Create columns for each other feature extracted."""
# Features list
features_list = ['Fibra_ottica', 'Cancello_elettrico', 'Cantina',
'Impianto_di_allarme', 'Mansarda', 'Taverna',
'Cablato', 'Idromassaggio', 'Piscina']
# Crea... | 40,037 |
def test_local_retrieve():
"""Test retrieving the stored data from the local file system"""
local = Local(directory='tmp/')
local.persist(path='foobar.pickle', data=pickle.dumps({'foo': 'bar'}))
response = local.retrieve(path="foobar.pickle")
assert pickle.loads(response)
os.remove('tmp/fooba... | 40,038 |
def handler_good():
"""Return True for a good event handler."""
return True | 40,039 |
def form_gov():
"""
Collects the data from the government form and
redirects them to the appropriate results page to report
the final results
"""
collected_data = []
form_gov = InputData_gov()
if request.method == "POST":
try:
collected_data.append("Government")
... | 40,040 |
def convert_to_grayscale(buffer):
"""Converts the image in the given StringIO object to grayscale.
Args:
buffer (StringIO): The original image to convert. Must be in RGB mode.
Returns:
StringIO: The grayscale version of the original image.
Raises:
ValueError: If the provided image is not in RGB m... | 40,041 |
def test_runner_with_db(dataset, time_start, time_diff):
"""Adding in db_connector
add in a DB Connector as the next step
so that we can test out the functionality together
"""
session = dataset
end_date = datetime.datetime(2020, 5, 17, 13, 0, 5)
replay_rate = 1.0
db_connector_te... | 40,042 |
def line_visible(plaza_geometry, line, delta_m):
""" check if the line is "visible", i.e. unobstructed through the plaza"""
intersection_line = plaza_geometry.intersection(line)
# a line is visible if the intersection has the same length as the line itself, within a given delta
delta = meters_to_degree... | 40,043 |
def log_mail_message(message, app):
"""If mails are disabled, their content will be outputted in the debug output"""
app.logger.debug(
f"A mail was supposed to be send:\n"
f"[SUBJECT]:\n{message.subject}\n"
f"[BODY]:\n{message.body}\n"
f"[END]"
) | 40,044 |
def explain_clusters(M, X, documents):
"""
Pick examples that are close to each cluster center.
"""
_, D = X.shape
K, D_ = M.shape
assert D == D_
for k in range(K):
print("Topic #{}".format(k))
D = ((X - M[k])**2).sum(1)
for idx in D.argsort()[:10]:
print... | 40,045 |
def get_event_keywords(dict_event_windows, result_folder, args, analysis_mode=False):
"""
Get event keywords in each event window
parameters
-----------
:param dict_event_windows: dictionary
Dictionary of list of EventWindows
key - frequency_threshold-change_threshold
:param res... | 40,046 |
def bad_gateway(message="Bad gateway"):
"""
A shortcut for creating a :class:`~aiohttp.web.Response` object with a ``502`` status and the JSON body
``{"message": "Bad gateway"}``.
:param message: text to send instead of 'Bad gateway'
:type message: str
:return: the response
:rtype: :class:... | 40,047 |
def chromatic_induction_factors(n: FloatingOrArrayLike) -> NDArray:
"""
Return the chromatic induction factors :math:`N_{bb}` and :math:`N_{cb}`.
Parameters
----------
n
Function of the luminance factor of the background :math:`n`.
Returns
-------
:class:`numpy.ndarray`
... | 40,048 |
def get_correctly_labeled_entries(all_entries):
"""Get entries that are labeled and evaluated as correct."""
return [
entry for entry in all_entries if convert_to_bool(entry[9]) and convert_to_bool(entry[10])
] | 40,049 |
def data_context_connectivity_context_connectivity_serviceuuid_latency_characteristictraffic_property_name_delete(uuid, traffic_property_name): # noqa: E501
"""data_context_connectivity_context_connectivity_serviceuuid_latency_characteristictraffic_property_name_delete
removes tapi.topology.LatencyCharacteris... | 40,050 |
def test_bootstrap_reproducibility(random):
"""Test that bootstrapping uses the internal random state."""
data = np.random.randn(50)
boots1 = algo.bootstrap(data, seed=100)
boots2 = algo.bootstrap(data, seed=100)
assert_array_equal(boots1, boots2)
with pytest.warns(UserWarning):
# Depre... | 40,051 |
def test__parser__grammar_oneof(seg_list):
"""Test the OneOf grammar."""
fs = KeywordSegment.make('foo')
bs = KeywordSegment.make('bar')
g = OneOf(fs, bs, code_only=False)
c = ParseContext()
# Check directly
assert g.match(seg_list, parse_context=c).matched_segments == (bs('bar', seg_... | 40,052 |
def tag_state_quantities(blocks, attributes, labels, exception=False):
""" Take a stream states dictionary, and return a tag dictionary for stream
quantities. This takes a dictionary (blk) that has state block labels as
keys and state blocks as values. The attributes are a list of attributes to
tag. ... | 40,053 |
def optional_list():
"""Return an OptionalList action."""
class OptionalList(argparse.Action):
"""An action that supports an optional list of arguments.
This is a list equivalent to supplying a const value with nargs='?'. Which itself only allows a single optional
value.
"""
... | 40,054 |
def test_exercise_2():
"""Solution for exercise 2."""
dirname = os.path.dirname(os.path.realpath(__file__))
df = pd.read_pickle(f"{dirname}/material/data-consumption-function.pkl")
def construct_predicted_values(income, alpha, beta, gamma):
return alpha + beta * income ** gamma
mock_rslt =... | 40,055 |
def test_get_adviser_by_sso_email_non_staff_or_active(flags):
"""
Test that AuthenticationFailed is raised if SSO email matches and user has neither
is_staff nor is_active flags set.
"""
AdviserFactory(email='some@email', **flags)
with pytest.raises(AuthenticationFailed) as excinfo:
get_... | 40,056 |
def instancesUserLookup(query=None, query_type=None):
"""
Return a list of sites to which the requested user belongs
Display on /search
"""
if query_type == 'username':
kwargs = {'$or': [{'users.username.site_owner': {'$regex': query, '$options': 'i'}}, {'users.username.site_editor': {'$re... | 40,057 |
def volume_kerucut_melingkar(radius: float, tinggi: float) -> float:
"""
referensi dari kerucut melingkar
https://en.wikipedia.org/wiki/Cone
>>> volume_kerucut_melingkar(2, 3)
12.566370614359172
"""
return pi * pow(radius, 2) * tinggi / 3.0 | 40,058 |
def vgg19(pretrained=False, **kwargs):
"""VGG 19-layer model (configuration "E")
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
if pretrained:
kwargs['init_weights'] = False
model = VGG(make_layers(cfg['E']), **kwargs)
if pretrained:
model.... | 40,059 |
def xmprv_from_seed(seed: Octets, version: Octets, decode: bool = True) -> bytes:
"""derive the master extended private key from the seed"""
if isinstance(version, str): # hex string
version = bytes.fromhex(version)
if version not in PRV:
m = f"invalid private version ({version})"
... | 40,060 |
def load_empty_config_setup() -> DictConfig:
"""Return a dictionary containing all the MLOQ setup config values set to None."""
return OmegaConf.load(setup_yml.src) | 40,061 |
def list_devices():
"""List available pointer devices."""
devices = xi.get_pointer_devices()
for device in devices:
click.echo(message=device) | 40,062 |
def apply_dfg(dfg: Dict[Tuple[str, str], int], start_activities: Dict[str, int], end_activities: Dict[str, int], activities: Dict[str, int], parameters=None, variant=DEFAULT_VARIANT_DFG) -> Tuple[PetriNet, Marking, Marking]:
"""
Apply the chosen IM algorithm to a DFG graph obtaining a Petri net along with an in... | 40,063 |
def make_extrap_log_func(func, extrap_x_l=None):
"""
Generate a version of func that extrapolates to infinitely many gridpoints.
Note that extrapolation here is done on the *log* of the function result,
so this will fail if any returned values are < 0. It does seem to be better
behaved for SFS calc... | 40,064 |
def get_logger(name):
"""每次调用,都是一个新的
"""
return LogCollector(name) | 40,065 |
def test_train_ws_tknzr_on_wiki_text_2(
cfg_file_path: str,
exp_name: str,
is_uncased: bool,
max_vocab: int,
min_count: int,
seed: int,
tknzr_file_path: str,
) -> None:
"""Must successfully train :py:class:`lmp.tknzr.WsTknzr` on :py:class:`lmp.dset.WikiText2Dset`."""
argv = [
WsTknzr.tknzr_name,
... | 40,066 |
def ShowString(name, msg):
"""Return a html page listing a file and a 'back' button"""
return """
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<html>
<head>
<title>%s</title>
</head>
<body>
<FORM><INPUT TYPE="BUTTON" VALUE="%s" ONCLICK="history.go(-1)"></FORM>
<h3>%s</h3>
... | 40,067 |
def game_loop(screen, buttons, items, music, sound, g_settings, particles=None, percentthing=None):
"""Manage events, return a gamestate change if it happens, and update the screen"""
while True:
# Check and manage event queue
gs_change = gf.check_events(buttons, music, sound, g_settings)
... | 40,068 |
def fake_request(method, url, **kwargs):
"""Constructs and sends a :class:`Request <Request>`.
:param method: method for the new :class:`Request` object.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Requ... | 40,069 |
def assert_step_match(
step: Step,
expected_step_func: str,
expected_step_arguments: List[Dict[str, Any]],
step_registry: StepRegistry,
):
"""Assert that the Step correctly matches in the Registry"""
print(
"{} STEP '{}' SHOULD MATCH {}".format(
cf.orange(">>"),
c... | 40,070 |
def get_grafana_dashboards_url(admin: bool) -> List[Dict]:
"""
Get a list of dashboard available to the tenant.
:admin (bool) A boolean representing admin status.
Return a list of dashboards dictionaries.
"""
urls = []
req = format_grafana_admin_request('/api/search?query=[Grafonnet]')
... | 40,071 |
def assert_binance_trades_result(
trades: List[Dict[str, Any]],
trades_to_check: Optional[Tuple[int, ...]] = None,
) -> None:
"""Convenience function to assert on the trades returned by binance's mock
'trades_to_check' is a tuple of indexes indicating which trades should be checked.
For exa... | 40,072 |
def validate_comma_separated_list(argument):
"""Convert argument to a list."""
if not isinstance(argument, list):
argument = [argument]
last = argument.pop()
items = [i.strip(u' \t\n') for i in last.split(u',') if i.strip(u' \t\n')]
argument.extend(items)
return argument | 40,073 |
def test_core_profile_constraint(entity):
"""Test that multiple profiles with the same schema cannot be added"""
with raises(Exception):
CoreProfile(entity=entity, identity="http://bad.example.com").save() | 40,074 |
def get_view(brain):
"""Setup for view persistence test"""
fig = brain._figures[0][0]
if mlab.options.backend == 'test':
return
fig.scene.camera.parallel_scale = 50
assert fig.scene.camera.parallel_scale == 50
view, roll = brain.show_view()
return fig.scene.camera.parallel_scale, vie... | 40,075 |
def model_description(formula):
"""Interpret model formula and obtain a model description.
This function receives a string with a formula describing a statistical
model and returns an object of class ModelTerms that describes the
model interpreted from the formula.
Parameters
----------
fo... | 40,076 |
def setup():
"""
Parse command line arguments
Returns parsed arguments
"""
parser = argparse.ArgumentParser(description='Search Reddit Thing')
parser.add_argument(
'subreddit',
help="Enter the name of the subreddit to search.")
parser.add_argument(
'query',
h... | 40,077 |
def eintragen_kaeufe(kliste, id_zu_objekt, id_zu_profil):
""" bekommt eine Liste von dicts mit dem Inhalt von je einer Zeile der
registration-Tabelle der alten db. Außerdem ein mapping der produkt_id
der alten db zu model-Instanzen der neuen. Trägt entsprechende Käufe ein
und gibt dict produkt_id -> mo... | 40,078 |
def update_status(payload: Something, context: EventContext) -> Something:
"""
Updates status of payload to PROCESSED and puts previous status in history.
:param payload: Something, object
:param context: EventContext
"""
logger.info(context, "updating something status", extra=extra(something_i... | 40,079 |
def get_holdout_set(train, target_column):
"""This is a sample callable to demonstrate how the Environment's `holdout_dataset` is evaluated. If you do provide a
callable, it should expect two inputs: the train_dataset (pandas.DataFrame), and the target_column name (string). You should
return two DataFrames:... | 40,080 |
def field_type(value):
"""Return the type of the field, using the Ref object"""
if isinstance(value, Ref):
return "RefValue"
else:
return "StringValue" | 40,081 |
def test_read_covars_manual_input(tmp_observe_class,
covar_details_mapped_covar_mapped_names_tmp_observe_class,
additional_text, monkeypatch):
"""
test reading of covars from manual input by user. Monkeypatches reliance on function 'input'
... | 40,082 |
def remove_overlapping_squares_v2(squares_dict, array_type):
"""
removes squares with min_x and min_y that are both within 40 pixels of each other
:param squares_dict: dict with overlapping squares
:param array_type: "Air_100" is the only one currently supported
:return: dict of squares and datafram... | 40,083 |
def depth_to_space(x, scale, use_default=False):
"""Depth to space function."""
if use_default:
out = tf.depth_to_space(x, scale)
else:
b, h, w, c = list(map(int, x.shape))
out = tf.reshape(x, [b, h, w, scale, scale, -1])
out = tf.transpose(out, [0, 1, 3, 2, 4, 5])
ou... | 40,084 |
def camelcase(key_name):
"""Convert snake-case to camel-case."""
parts = iter(key_name.split('_'))
return next(parts) + ''.join(i.title() for i in parts) | 40,085 |
def get_spectrum_from_grid(config: str, values: bool, **kwargs):
"""Prints info about grid given in config.
Args:
config: Config to build grid from.
values: If True, print all values per axis.
"""
# create grid
with open(config, 'r') as f:
cfg = yaml.safe_load(f)
grid =... | 40,086 |
def calculate_sigmoid(alpha_value = 1, TDE = 0, sigma=.1):
"""
SOFTMAX VBDE: f(s, a, \sigma) = \frac{2e^{-|\alpha TDE| / \sigma}}{1-e^{-|\alpha TDE|/\sigma}}
:return:
"""
temp = np.exp(-np.abs(alpha_value *TDE + 1e-16) / sigma)
return 2*temp / (1-temp) | 40,087 |
def getprop(obj, string):
"""
Par exemple 'position.x'
:param string:
:return:
"""
tab = string.split('.')
curr_val = obj
for str in tab:
curr_val = getattr(curr_val, str)
return curr_val | 40,088 |
def config_aws_region_name(aws_region_name="us-east-1"):
"""Adds region to cfncluster configuration file.
If the configuration file doesn't exist the template version is
created with make_config_file. The "aws_region_name" field of
the configuration file is rewritten based on the function args.
... | 40,089 |
def _StartWWW(run_callback, scan_ops):
"""Starts services necessary for operating in the Viewfinder WWW server environment. Invokes
'run_callback' asynchronously.
"""
client = db_client.DBClient.Instance()
# Log emails and texts to the console in local mode.
if options.options.local_services:
EmailMana... | 40,090 |
def test_git_clone(mock_popen):
"""Test git_clone()."""
expected_git_url = 'ssh://git@git.example.com:test.git'
expected_git_clone_dir = '/no/dir'
expected_popen_args = [
'git',
'clone',
expected_git_url,
expected_git_clone_dir,
]
# Setup mocked subprocess.Popen
... | 40,091 |
def get_options():
"""Parses options."""
parser = argparse.ArgumentParser(
description="Dynamic inventory for Decapod.")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument(
"-l", "--list",
help="List all inventory.",
action="store_true",
... | 40,092 |
def extend(vals, inds, shape):
""" Makes an array of shape `shape` where indices `inds` have vales `vals`
"""
z = np.zeros(shape, dtype=vals.dtype)
z[inds] = vals
return z | 40,093 |
def check_model(model_name, model, model_type):
"""
Check the type of input `model` .
Args:
model_name (str): Name of model.
model (Object): Model object.
model_type (Class): Class of model.
Returns:
Object, if the type of `model` is `model_type`, return `model` itself.... | 40,094 |
def load_score_map(input_prefix, day, epsilon=0.000000001, excluded_indices=None, restricted_indices=None):
"""TODO: The centrality maps were pre-sorted in decreasing order???"""
score_file_path = input_prefix + '_%i.csv' % day
if not os.path.exists(score_file_path):
raise IOError("File is missing: ... | 40,095 |
def compute_tnacs( hvib ):
"""
Computes the time-averaged nonadiabatic couplings for a given hvib.
hvib ( list of list of matrices ): The vibronic hamiltonian for all timesteps
returns: a matrix of time-averaged nonadiabatic couplings between all electronic states
in meV
"""
nst... | 40,096 |
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up config entry."""
session = aiohttp_client.async_get_clientsession(hass)
hass.data.setdefault(DOMAIN, {})
printer = SyncThru(
entry.data[CONF_URL], session, connection_mode=ConnectionMode.API
)
async... | 40,097 |
def center_binned_stats(*args, **kwargs):
"""
Same as scipy.stats.binned_statistic, but returns
the bin centers (matching length of `statistic`)
instead of the binedges.
See docs.scipy.org/doc/scipy/reference/generated/scipy.stats.binned_statistic.html
"""
stat, binedges, binnumber = bi... | 40,098 |
def create_account():
"""
Handles the user signing up to create an account
Redirects them to the log in page with a message after if successful
"""
signUpForm = forms.RegisterFormFactory()
if signUpForm.validate_on_submit():
netid,name,duke_email,phone_number,affiliation,password=extrac... | 40,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.