content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def vibrateDevice(duration, sessionId="current_session"):
"""When called from the Perspective mobile app, will cause the
device to vibrate for the specified number of milliseconds.
Args:
duration (int): The duration in milliseconds to vibrate the
device.
sessionId (str): Identif... | 5,314,800 |
def rearrange(blist, flist):
"""Alligns the number of evaluations taken from the blist with the correpsning flist"""
final_b=[]
final_f=[]
for i in range(0,len(blist)): #runs over dimensions
erg_b = numpy.empty((0), float)
erg_f = [numpy.empty ((0), float), numpy.empty ((0), float), nump... | 5,314,801 |
def change_password_fields():
"""Return Change Password Fields"""
return f.Fields([
f.PasswordField('Old Password', v.required),
f.PasswordField('New Password', v.required),
f.PasswordField('Confirm New Password', v.required),
]) | 5,314,802 |
def create_fido_mfa_method(email_address):
"""Generate a WebAuthn challenge that can be used to register a new hardware token for two-factor authentication."""
pass | 5,314,803 |
def montage_stream(ims, montage_order=None, channel_order=[0, 1, 2],
clear_none=True):
"""From a sequence of single-channel field images, montage multichannels.
Suppose the input is a list:
```
ims = [green1a, blue1a, red1a, green1b, blue1b, red1b,
green2a, blue2a, red2a,... | 5,314,804 |
def ha_restart(ctx: Configuration):
"""Home Assistant ha-cli restart."""
try:
_handle(ctx, 'cli/restart', 'post')
except HomeAssistantCliError:
pass | 5,314,805 |
def hg():
"""Initialize Click Command Group."""
pass | 5,314,806 |
def load_and_prepare_cmd(filename,verbose=False): # (g, gr) = load_and_prepare_cmd('fieldA.csv')
"""
Loads in data. Returns pandas Series of g-r and r respectively.
"""
FIELD = pd.read_csv("fieldA.csv")
g = FIELD["g"] # probs slower than inital idea
gr = g - FIELD["r"]
mask = (g>14) & (g<24... | 5,314,807 |
def test_tune_random_early_stop_iteration() -> None:
"""
Runs hyperparameter random search until an early stop point between iterations.
"""
# Load hyperparameter search config.
with open(RANDOM_CONFIG_PATH, "r") as config_file:
config = json.load(config_file)
# Modify default training... | 5,314,808 |
def make_rows(cngrs_prsn):
"""Output a list of dicitonaries for each JSON object representing a
congressperson.
Each individaul dictionary will contain information about the congressperson
as well as info about their term.
"""
name = cngrs_prsn["name"]["first"] + " " + cngrs_prsn["name"]["last"]
birthd... | 5,314,809 |
def getNumProfileArgs(device):
""" Get the number of Power Profile fields for a specific device
Parameters:
device -- DRM device identifier
This varies per ASIC, so ensure that we get the right number of arguments
"""
profile = getSysfsValue(device, 'profile')
numHiddenFields = 0
if n... | 5,314,810 |
def singlePass(A,Omega,k,s=1,check=False):
"""
The single pass algorithm for the Hermitian Eigenvalues Problems (HEP) as presented in [1].
Inputs:
- :code:`A`: the operator for which we need to estimate the dominant eigenpairs.
- :code:`Omega`: a random gassian matrix with :math:`m \\geq k` co... | 5,314,811 |
def change_times(ti: str, tf: str, dt: int):
"""Change starttime and endtime in ai_picker.inp file
Parameters
----------
ti : str
Initial UTC datetime in strftime format: %Y-%m-%d %H-%M-%S
tf : str
Final UTC datetime in strftime format: %Y-%m-%d %H-%M-%S
dt : int
Delta t... | 5,314,812 |
def describe_availability_monitor_test(GatewayARN=None):
"""
Returns information about the most recent High Availability monitoring test that was performed on the host in a cluster. If a test isn\'t performed, the status and start time in the response would be null.
See also: AWS API Documentation
... | 5,314,813 |
def main():
"""
PARSE AND VALIDATE INTEGRATION PARAMS
"""
verify_certificate = not demisto.params().get('insecure', False)
proxy = demisto.params().get('proxy', False)
command = demisto.command()
LOG(f'Command being called is {demisto.command()}')
try:
client = Client(
... | 5,314,814 |
def _cons6_77(m6, L66, L67, d_byp, k, Cp, h_byp, dw1, kw1, dw2, kw2,
adiabatic_duct=False, conv_approx=False):
"""dz constrant for edge bypass sc touching 2 corner bypass sc"""
term1_out = 0.0
if not adiabatic_duct:
if conv_approx:
R2 = 1 / h_byp + dw2 / 2 / kw2
... | 5,314,815 |
def generate_response_body(
response_body, success,
response_type, data, message
):
"""Generate response_body."""
response_body['success'] = success
response_body['type'] = response_type
response_body['data'] = data
response_body['message'] = message | 5,314,816 |
def load_user(username):
"""Load user by usename."""
return User.get_by_username(username) | 5,314,817 |
def num_to_hex_string(num, size=1, little_endian=False):
"""Convert a given number to hex string.
Converts a number to a big endian hexstring of a suitable size, optionally little endian
Args:
num (int) : Input int for which we need to get the hex string
size (int) : The required size i... | 5,314,818 |
def validate(number, table=None):
"""Checks to see if the number provided passes the Damm algorithm."""
if not bool(number):
raise InvalidFormat()
try:
valid = checksum(number, table=table) == 0
except Exception:
raise InvalidFormat()
if not valid:
raise InvalidChecks... | 5,314,819 |
def download_binary_mnist(
fname: str = "binary_mnist.h5",
data_dir: Path = (PROJECT_APP_PATH.user_data / "vanilla_vae" / "data"),
):
"""
Args:
fname:
data_dir:
"""
if not data_dir.exists():
data_dir.mkdir(parents=True)
subdatasets = ["train", "valid", "test"]
... | 5,314,820 |
def get_saliva_example(sample_times: Optional[Sequence[int]] = None) -> SalivaRawDataFrame:
"""Return saliva example data.
Parameters
----------
sample_times : list of int, optional
sample times of saliva samples in minutes
Returns
-------
:obj:`~biopsykit.utils.datatype_helper.Sal... | 5,314,821 |
def boundary_points(grid: Grid, coords: List[Point]) -> List[Point]:
""" Return points on the boundary of a grid, not necessarily sorted."""
(x_min, y_min), (x_max, y_max) = grid_bounds(coords)
# Top and bottom edge
for x in range(x_min - 1, x_max + 2):
point = (x, y_min - 1)
if point i... | 5,314,822 |
def process_json_content(input_type: str,
content_array: List[str],
json_content_array: Union[List[str], None]):
"""
Process the array of json_contents
"""
if json_content_array is None:
return [''] * len(content_array)
if input_type == 'FRAM... | 5,314,823 |
def knapsack(
items: Set[Tuple[float, float]], max_weight: float
) -> FrozenSet[Tuple[float, float]]:
"""Given a set of (value, weight) pairs and a maximum weight, return the
most valuable subset of items whose total weight does not exceed the
maximum weight.
Design idea: Enumerate all subs... | 5,314,824 |
def test_subclass_nt_to_anatomical_entity(rosetta,eg):
"""named_thing -> Anatomical Entity"""
node = KNode('UBERON:0035368', type=node_types.NAMED_THING)
rosetta.synonymizer.synonymize(node)
assert eg.get_leaf_type(node,node_types.NAMED_THING)[0] == node_types.ANATOMICAL_ENTITY | 5,314,825 |
def failure(message):
"""Prints a failure message to the terminal"""
click.echo("✖️ ", color="red", err=True, nl=False)
click.echo(message, err=True) | 5,314,826 |
def get_json(query_parsed):
"""Call taskwarrior, returning objects from json"""
result, err = call_taskwarrior(
'export %s rc.json.array=on rc.verbose=nothing' % query_parsed)
return json.loads(result) | 5,314,827 |
def get_list_of_results(results):
"""Modify the outputs so that they are returned in a list format where it is
sometimes easier to be used by other functions.
Parameters
----------
results : list
A list of named tuples for each iteration
Returns
-------
list, list, list
... | 5,314,828 |
def create_diff_shift_features(df_shift, cols=[], prefix='diff_'):
"""
Create diff values between time series columns with have been shifted.
Parameters
----------
df_shift: dataframe
Dataset with columns to make apply diff.
cols: list
Columns names, in order, to apply diff.
... | 5,314,829 |
def get_dagger_of_native(gate: Gate) -> Gate:
"""
:param gate: A gate from native gate set
:return: the conjugated and transposed gate
"""
if isinstance(gate, Gate):
if gate.name == "RZ":
return RZ(-gate.params[0], gate.qubits[0])
if gate.name == "RX":
... | 5,314,830 |
def reset():
"""Reset configuration of logging (i.e. remove the default handler)"""
if log_handler is not None:
logging.getLogger("react").removeHandler(log_handler) | 5,314,831 |
def get_movies_list(request_params: dict) -> List[ShortMovie]:
"""
:param request_params: Get request query params
:return: List of movies, grabed with ElasticSearch
"""
sort_value = request_params.get('sort')
sort_order = request_params.get('sort_order')
limit = int(request_params.get('limit'))
... | 5,314,832 |
def statUniq(passwords, status):
"""produce data about unicity stats"""
unicity = {"empty":0, "non empty": 0, "unique": 0}
unicity['empty'] = passwords[status].count('')
unicity['non empty'] = len( passwords[status] ) - unicity['empty']
unicity['unique'] = len( set( passwords[status] ))
return u... | 5,314,833 |
def _read_logo(content):
""" Read info from logo in file header. """
def _read_logo(pat):
pattern = pat + r":\s+\S+"
data_str = re.compile(pattern).search(content).group()
return data_str.split(':')[1].strip()
info = {}
for pat in ['Version', 'Website']:
info[pat] = _rea... | 5,314,834 |
def test_unit_vectors_from_cross_section_given_lonlat(test_cross_lonlat):
"""Test unit vector calculation from cross section with lat/lon grid."""
unit_tangent, unit_normal = unit_vectors_from_cross_section(test_cross_lonlat['u_wind'])
true_unit_tangent = np.array([[0.66533859, 0.66533859, 0.66533859, 0.665... | 5,314,835 |
def modulate_position(timestamp):
"""
counts the position in time-sorted log of IP activity as based on the timestamp attached to
the particular log in rdd
timestamp: attached timestamp
"""
result = (INCREMENT - timestamp) % time_dimension
return result | 5,314,836 |
def resnet50(mask_init='1s', mask_scale=1e-2, threshold_fn='binarizer', **kwargs):
"""Constructs a ResNet-50 model."""
#print('resnet50 get in')
#print('resnet50 mask_init', mask_init)
model = ResNet(Bottleneck, [3, 4, 6, 3], mask_init,
mask_scale, threshold_fn, **kwargs)
return m... | 5,314,837 |
def create_channel(pvname, connect=False, auto_cb=True, callback=None):
""" create a Channel for a given pvname
creates a channel, returning the Channel ID ``chid`` used by other
functions to identify this channel.
Parameters
----------
pvname : string
the name of the PV for which a c... | 5,314,838 |
def test_cbuffer_read(in_buffer, out_buffer, out_n, remaining_data):
"""Run tests for the CBuffer.read method."""
read_buffer = np.zeros_like(out_buffer, dtype=np.float32)
n = in_buffer.read(read_buffer)
assert n == out_n
assert_almost_equal(read_buffer, out_buffer)
assert_almost_equal(in_buffe... | 5,314,839 |
def fetch_profiles(db_path, keys_ls):
"""Fetch hmm profiles from db and save in a file
Args:
db_path: String, path where db are stored
keys_ls: String, Path to file with acc-nr
Return:
ls_keys: List, strings with acc-numbers
"""
LOG.info("Fetching profiles from Pfam... | 5,314,840 |
def get_w_cmd_args():
"""Either -his or -wnh depending on system."""
try:
if (str(sys.platform).lower().startswith(str("""darwin""")) is True):
return str("""-hi""")
else:
return str("""-his""")
except Exception as someErr:
logs.log(str(type(someErr)), "Error")
logs.log(str(someErr), "Error")
logs.lo... | 5,314,841 |
def prep_for_graph(data_frame, series=None, delta_series=None, smoothing=None,
outlier_stddev=None):
"""Prepare a dataframe for graphing by calculating deltas for
series that need them, resampling, and removing outliers.
"""
series = series or []
delta_series = delta_series or []
... | 5,314,842 |
def vigenere_decryption(text: str, key: str) -> str:
"""Декодирование шифра Виженера
:param text: расшифровываемый текст
:type text: str
:param key: ключ
:type key: str
:return: исходный текст
:rtype: str
"""
result = ''.join(
[chr((ord(m) - ord(key[i % len(key)]) + 26) % 26... | 5,314,843 |
def remove_diacritics(string):
"""Removes diacritics from the given string
Parameters
----------
string : str
The string from which diacritics should be removed
Returns
-------
string : str
The string with its diacritics removed
"""
uni = unidecode(string)
# r =... | 5,314,844 |
def sql_answer_check(log_file_name, sql_answer, mac, config):
"""
Checks the response from the log server DB
"""
if 'Task failed' in sql_answer['answer']:
logging.info(sql_answer['answer'])
task_result = 'Task failed'
end_task(log_file_name, mac, task_result, config)
else:
... | 5,314,845 |
def make_knowledge_header(name: str,
version: Optional[str] = None,
description: Optional[str] = None,
authors: Optional[str] = None,
contact: Optional[str] = None,
copyright: Optional[str] ... | 5,314,846 |
def eval_chip_generalized(theta1, theta2, deltaphi, q, chi1, chi2):
"""
Generalized definition of the effective precessing spin chip, see arxiv:2011.11948. This definition retains all variations on the precession timescale.
Call
----
chip = eval_chip_generalized(theta1,theta2,deltaphi,q,chi1,chi2)
... | 5,314,847 |
def add_filter_conditions(client, report_filter, args):
"""
This function fills some attributes of the given report filter based on
the arguments which is provided in the command line.
"""
severities, checkers, file_path, dt_statuses, rw_statuses, \
bug_path_length = check_filter_values(arg... | 5,314,848 |
def strip_emails(s):
"""
Remove digits from `s` using RE_EMAILS`.
"""
RE_EMAILS = re.compile(r"\S*@\S*\s?", re.UNICODE)
return RE_EMAILS.sub("", s) | 5,314,849 |
def get_hf(sigma_val=0.8228, boxRedshift=0., delta_wrt='mean'):
"""
Halo mass function model for the MultiDark simulation.
"""
#hf0 = MassFunction(cosmo_model=cosmo, sigma_8=sigma_val, z=boxRedshift)
omega = lambda zz: cosmoMD.Om0*(1+zz)**3. / cosmoMD.efunc(zz)**2
DeltaVir_bn98 = lambda zz : (18.*n.pi**2. + 82.*(... | 5,314,850 |
def pytest_addoption(parser) -> None:
"""Get cli-arguments.
:param parser: pytest parser
:return:
"""
parser.addoption(
"--context",
action="store",
default="",
help="The context to use in the kubeconfig file.",
)
parser.addoption(
"--image",
... | 5,314,851 |
def reverse_one_hot(image):
"""
Transform a 2D array in one-hot format (depth is num_classes),
to a 2D array with only 1 channel, where each pixel value is
the classified class key.
# Arguments
image: The one-hot format image
# Returns
A 2D array with the same width and... | 5,314,852 |
def individual_utilities(
persons,
cdap_indiv_spec,
locals_d,
trace_hh_id=None, trace_label=None):
"""
Calculate CDAP utilities for all individuals.
Parameters
----------
persons : pandas.DataFrame
DataFrame of individual persons data.
cdap_indiv_spec : p... | 5,314,853 |
def _create_pd_obj(frame, res, RATIO, mode):
"""Creates a prediction objects file."""
objs = []
# This is only needed for 2D detection or tracking tasks.
# Set it to the camera name the prediction is for.
if len(res) > 0:
for re in res:
# import ipdb; ipdb.set_trace()
re = re.split(",")
obj = metrics_pb... | 5,314,854 |
def check_random_state(seed):
"""Turn `seed` into a `np.random.RandomState` instance.
Parameters
----------
seed : {None, int, `numpy.random.Generator`,
`numpy.random.RandomState`}, optional
If `seed` is None (or `np.random`), the `numpy.random.RandomState`
singleton is use... | 5,314,855 |
def set_dropout_mode(model, dropout_layer_indexes: list, train_mode: bool):
"""
Function to change the mode of the dropout layers (bool: train_mode -> train or evaluation)
Args:
model: Pytorch model
dropout_layer_indexes: Indexes of the dropout layers which should be activ... | 5,314,856 |
def init_argument_parser():
""" Creates an argument parser and adds specifications for command-line
arguments for the expression code generation program.
Returns:
arg_parser : An initialized ArgumentParser object with properties
lang, dest, cname, exprfile
"""
arg_parse... | 5,314,857 |
def serialize(message: typing.Union[structure.Call, structure.CallResult, structure.CallError]) -> typing.List:
"""Serializes an 'OCPPMessage'.
Args:
- message: 'OCPPMessage', the message to serialize
Returns:
list, an equivalent to the message, based only on JSON compatible types (string,... | 5,314,858 |
def sequence_plot(units: Sequence[Unit]):
"""Plot the temperatures of all profiles"""
fig, ax = utils.create_sequence_plot(units)
ax.set_ylabel(r"temperature $T$")
ax.set_title("Mean Profile Temperatures")
units = list(units)
if len(units) > 0:
def gen_seq():
yield -0.5, uni... | 5,314,859 |
async def save(ctx, *args, **kwargs):
"""
Saves avatar in directory
Args:
ctx:
Returns:
"""
if "all" in args:
count = 0
for member in ctx.guild.members:
try:
avatar_url = member.avatar_url
name = member.name
im... | 5,314,860 |
def format_data(data):
"""
:param data:
:return: str : this str can print to web page.
"""
return "<pre>" + change_to_str(data, rowstr="<br/>") + "</pre>" | 5,314,861 |
def compare_type_annots_to_convention(metadata, convention):
"""Check if metadata type annotation is consistent with metadata convention type
"""
metadata_names = metadata.file.columns.get_level_values(0).tolist()
type_annots = metadata.file.columns.get_level_values(1).tolist()
# if input was TSV me... | 5,314,862 |
def DAYS(date1, date2):
"""Given two strings of dates, calculate the difference in days between the two.
Parameters
----------
date1 : string
start date in the form of a string: 'YYYY-MM-DD'
date2 : string
end date in the form of a string: 'YYYY-MM-DD'
Returns
-------
i... | 5,314,863 |
def __get_column_names_from_worksheet(worksheet: Worksheet) -> List[NumberOrString]:
"""Returns list of column names (headers) from worksheet object (i.e; the values from row #1)"""
column_names = [
column.value for column in next(worksheet.iter_rows(min_row=1, max_row=1))
]
return column_names | 5,314,864 |
def plot_set(fig_num: int, to_goal_arr: list, legend_names: list, max_len: float, max_non_init_rmsd: float,
init_metr: float, bsf_arr: list, common_point: float, max_trav: float, trav_arr: list, full_cut: str,
metric: str, metr_units: str, same: str, custom_path: str, shrink: bool, non_shrink_... | 5,314,865 |
def get_fractal_patterns_NtoS_WtoE(fractal_portrait, width, height):
""" get all fractal patterns from fractal portrait, from North to South, from West to East """
fractal_patterns = []
for y in range(height):
# single fractal pattern
f_p = get_fractal_patterns_zero_amounts()
for x i... | 5,314,866 |
def _print_gs_info(it, level, cycmax, grid, norm, text):
"""Print info to log after each Gauss-Seidel smoothing step.
Parameters
----------
it : int
Iteration number.
level : int
Current coarsening level.
cycmax : int
Maximum MG cycles.
grid : :class:`emg3d.meshes... | 5,314,867 |
def lookup_dir(root, name):
"""Find a directory
"""
top = root
while osp.exists(root):
content = os.listdir(root)
for subdir in content:
if subdir == name:
return osp.join(root, subdir)
if len(content) > 1:
raise EnvironmentError('Could not... | 5,314,868 |
def getworkflowparams(ListeJsonData):
"""
< Get workflow parameters if it is possible... (advanced edit option
enable on workflow creation)
"""
aff = True
params_tools = []
for JsonData in ListeJsonData:
step_id = JsonData.step_id
tname = JsonData.tname
ttool_id = Jso... | 5,314,869 |
def test_command_with_args():
"""Test running a command with arguments.
"""
argv = ["test_command", "argument 1", "argument 2", "argument 3"]
run_test_case(argv) | 5,314,870 |
def single_stat_request(player, code, stat):
"""Actually retrieves the stat and returns the stat info in an embed"""
session = Session()
message = ""
if code == 1:
(table, col, message) = stat_dict[stat]
columns = [col]
res = session.query(*(getattr(table, column) for column in c... | 5,314,871 |
def download_uniprot(myid, path=".TPSdownloader_cache" + os.path.sep + 'uniprot' + os.path.sep):
"""Download a page like
https://www.uniprot.org/uniprot/A0A2K9RFZ2.xml
https://www.uniprot.org/uniprot/D8R8K9.xml
Some entries have multiple Accessions, like
<accession>Q6XDB5</accession>
<accessio... | 5,314,872 |
def random_string_list(num: int = 10) -> List[str]:
"""
Generate list of random strings
>>> type(random_string_list())
<class 'list'>
>>> all([True if type(obj) is str else False for obj in random_string_list()])
True
>>> len(random_string_list())
10
>>> len(random_string_list(num=0... | 5,314,873 |
def get_entity_description(entity):
"""
Realiza o mapeamento de uma entidade padrão da extracão de entidades
(named entity) retornando de forma explícita o equivalente em português
para a entidade extraída.
param : entity : <str>
return : <str>
"""
ent_map = {
'PERSON': 'pessoa'... | 5,314,874 |
def duration(utter: Utterance) -> int:
"""Get the duration of an utterance in milliseconds
Args:
utter: The utterance we are finding the duration of
"""
return utter.end_time - utter.start_time | 5,314,875 |
def label_sequential_regions(inlist):
"""Input a list of labeled tuples and return a dictionary of sequentially labeled regions.
Args:
inlist (list): A list of tuples with the first number representing the index and the second the index label.
Returns:
dict: Dictionary of labeled regions.
... | 5,314,876 |
def lines_edit_renderer(widget, data):
"""Renders text area with list value as lines.
"""
tag = data.tag
area_attrs = textarea_attributes(widget, data)
value = fetch_value(widget, data)
if value is None:
value = u''
else:
value = u'\n'.join(value)
return tag('textarea', v... | 5,314,877 |
def variantsFromAlignment(refWindow, refSeq, cssSeq,
cssQV=None, refCoverage=None):
"""
Extract the variants implied by a pairwise alignment of cssSeq to
refSeq reference. If cssQV, refCoverage are provided, they will
be used to decorate the variants with those attributes.
... | 5,314,878 |
def system_message(msg):
""" process system messages"""
if msg.topic == 'diy/system/fire':
if msg.payload == b'ON':
print("fire message")
elif msg.topic == 'diy/system/panic':
if msg.payload == b'ON':
print("panic message")
elif msg.topic == 'diy/system/who':
... | 5,314,879 |
def _read_cookie(cookie_path, is_safecookie):
"""
Provides the contents of a given cookie file.
:param str cookie_path: absolute path of the cookie file
:param bool is_safecookie: **True** if this was for SAFECOOKIE
authentication, **False** if for COOKIE
:raises:
* :class:`stem.connection.Unreadabl... | 5,314,880 |
def startAPISpecEditor(ctx):
"""starts swagger editor ui on 192.168.205.21:8080"""
cmd = "docker-compose -f env/development/swagger-editor.yml up -d"
print cmd
result = run(cmd, hide=False, warn=True) | 5,314,881 |
def test_evil():
""" Tests evil method """
seq([3, 5, 6, 9, 10, 12, 15, 17, 18, 20], evil, True,
"evil number from test sequence is not evil")
seq([1, 2, 4, 7, 8, 11, 13, 14, 16, 19], evil, False,
"not evil number is evil") | 5,314,882 |
def exception_guard(f):
"""
Middleware (guard): checks if the current authorized user can created an
exception request
"""
@wraps(f)
def decorated_function(*args, **kwargs):
if 'eid' not in kwargs.keys():
return F.abort(404)
election = meta.Election(kwargs['eid'])
... | 5,314,883 |
def return_last(responses):
"""Return last item of a list."""
return responses[-1] | 5,314,884 |
def autolink_replacements(what: str) -> List[Tuple[str, str, str]]:
"""
Create a list containing replacement tuples of the form:
(``regex``, ``replacement``, ``obj``) for all classes and methods which are
imported in ``KEDRO_MODULES`` ``__init__.py`` files. The ``replacement``
is a reStructuredText ... | 5,314,885 |
def flattenDict(dictionary, init = ()):
"""
Converts nested dicts with numeric or str keys to flat dict with tuple keys.
For example, x[1][0][2] becomes xx[(1, 0, 2)].
Based on::
http://stackoverflow.com/questions/6027558/\
flatten-nested-python-dictionaries-compressing-keys
"""
def _tuple(x):
"... | 5,314,886 |
def get_boundary_cell_count(plate_dims, exclude_outer=1):
"""Get number of wells in outer or inner edges
Parameters
----------
plate_dims : array
dimensions of plate
Returns
-------
boundary_cell_count : int
number of wells in the edges
"""
boundary_cell_count =... | 5,314,887 |
def docs_main(args=sys.argv):
""" Get/Launch Docs."""
ensure_wx_app()
result = 0
print("Launch Docs for wxPython V%s" % wx.VERSION_STRING)
pd = get_paths_dict()
location = get_item(pd['wxDocs'], pd['Docs_URL'], pd['Cache'],
pd['Docs_Name'], pd['Ext'], forced="--force" in ... | 5,314,888 |
def _is_false(x):
"""Evaluates false for bool(False) and str("false")/str("False").
The function is vectorized over numpy arrays or pandas Series.
Everything that is NA as defined in `is_na()` evaluates to False.
but also works for single values. """
x = np.array(x).astype(object)
ret... | 5,314,889 |
def compute_border_indices(log2_T, J, i0, i1):
"""
Computes border indices at all scales which correspond to the original
signal boundaries after padding.
At the finest resolution,
original_signal = padded_signal[..., i0:i1].
This function finds the integers i0, i1 for all temporal subsamplings... | 5,314,890 |
def get(data_ids):
"""
Get a object(s) associated with `data_ids` from the shared object storage.
Parameters
----------
data_ids : unidist.core.backends.common.data_id.DataID or list
An ID(s) to object(s) to get data from.
Returns
-------
object
A Python object.
"""... | 5,314,891 |
def pass_time(grid, minutes):
"""Pass number of minutes on grid."""
cur_grid = copy_grid(grid)
grid_set = get_grid_for_set(cur_grid)
grid_set_to_minute = {grid_set: 0}
minute_to_grid_set = {0: grid_set}
for minute in range(1, minutes + 1):
cur_grid = pass_minute(cur_grid)
cur_gri... | 5,314,892 |
def njoin(n):
"""Join with newlines."""
return join(os.linesep, n) | 5,314,893 |
def test_matcher_pipe_with_context(nlp: Language) -> None:
"""It returns a stream of Doc objects as tuples with context."""
doc_stream = (
(nlp("test doc 1: Corvold"), "Jund"),
(nlp("test doc 2: Prosh"), "Jund"),
)
matcher = TokenMatcher(nlp.vocab)
output = matcher.pipe(doc_stream, a... | 5,314,894 |
def test_subscribe_email(mailgun, mailing_list, test_request):
"""Subscribe an email address without a user."""
subscribe_email(test_request, "example@example.com")
paginator = mailgun.list_members(mailing_list)
items = paginator["items"]
assert len(items) == 1
assert items[0]["address"] == "e... | 5,314,895 |
def test_hamiltonian_matmul():
"""Test matrix multiplication between Hamiltonians and state vectors."""
H1 = hamiltonians.TFIM(nqubits=3, h=1.0)
H2 = hamiltonians.Y(nqubits=3)
m1 = K.to_numpy(H1.matrix)
m2 = K.to_numpy(H2.matrix)
K.assert_allclose((H1 @ H2).matrix, m1 @ m2)
K.assert_allclos... | 5,314,896 |
def error_rate(predictions, labels):
"""Return the error rate based on dense predictions and sparse labels."""
return 100.0 - (100.0 * np.sum(np.argmax(predictions, 1) == labels) / predictions.shape[0]) | 5,314,897 |
def test_created(tmpdir, injections):
""" Test the injection creates a file if it does not exist """
new_file = os.path.join(tmpdir.strpath, "testcreated")
injections.inject(new_file, TEST_INJECTION)
injections.commit()
assert os.path.exists(new_file), "File was not generated on injection!" | 5,314,898 |
def read_gudb(
offline: bool = False,
data_dir: Optional[Union[str, Path]] = None,
) -> Iterator[ECGRecord]:
"""
Lazily reads records from GUDB (https://berndporr.github.io/ECG-GUDB/).
Required files are downloaded if not present in `'<data_dir>/gudb'`.
Parameters
----------
offline : ... | 5,314,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.