content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def mels_spectrogram(spec, sr, n_mels,
fmin=64, fmax=None, top_db=80.0):
""" Extracting mel-filter bands from power spectrum
(i.e. the output from function
`odin.preprocessing.signal.power_spectrogram`)
Parameters
----------
spec : array [nb_samples, n_fft]
power spectrum array
s... | 68,900 |
def create_data_loader(data, batch_size=32, shuffle=True, drop_last=False):
""" Create a data loader given numpy array x and y
Args:
data: a tuple (x, y, z, ...) where they have common first shape dim.
Returns: Pytorch data loader
"""
if drop_last:
batch_size = min(batch_size, dat... | 68,901 |
def set_order(order):
"""decorator to set callback's method order
usage:
@set_order(100)
def method(self):
pass
"""
def inner(meth):
def fn(*args, **kwargs):
return meth(*args, **kwargs)
fn._order = order
return fn
return inner | 68,902 |
def calculate_ci(
values: np.ndarray,
ci_level: float,
**kwargs,
) -> Tuple[np.ndarray, np.ndarray]:
"""Calculate confidence/credibility levels using percentiles.
Parameters
----------
values:
The values used to calculate percentiles.
ci_level:
Lower tail probability.
... | 68,903 |
def plot__02__a(
results: pd.DataFrame, ks: Optional[Union[List[int], int]] = None, min_class_support: int = 50,
colormap_name: str = "fixed", sharey: str = "all", cf_level: str = "superclass", n_samples: int = 50,
topk_method: str = "csi", fig_width: int = 6, fig_height: int = 4, label_rot_angl... | 68,904 |
def display_calibration(probs,
actual,
*,
figure=None,
bins=100,
label=None,
show_ici=True,
alpha=0.05,
n_resamples=None,
... | 68,905 |
def max_crossing_subarray(given_array, start_index, mid_index, end_index):
"""Function To Calculate The Mid Crossing Sub Array Sum"""
max_left_sum = - math.inf # Used For Sentinel Value
max_right_sum = - math.inf # Used For Sentinel Value
cross_start = None # Just used for variable pre assignment.
... | 68,906 |
def plot_learn_set_ckan():
"""
Simply plot the learnset, this is all the data that is in the data folders, didn't feel
like creating something to read it all.
"""
headers_dict = { 'has_description': 2400,
'has_identifier_has_URI': 2400,
'has_identifier_has_id_value': 2400,
'has_identifier_is_sourc... | 68,907 |
def ignore_warnings(obj=None, category=Warning):
"""Context manager and decorator to ignore warnings.
Note. Using this (in both variants) will clear all warnings
from all python modules loaded. In case you need to test
cross-module-warning-logging this is not your tool of choice.
Parameters
----... | 68,908 |
def WriteComplexView(OutFH, PyMOLObjectNames):
"""Write out PML for viewing polymer complex along with electron density."""
# Setup complex...
PML = PyMOLUtil.SetupPMLForPolymerComplexView(PyMOLObjectNames["Complex"], OptionsInfo["Infile"], True)
OutFH.write("""\n""\n"Loading %s and setting up view for... | 68,909 |
def create_sort_spec(model, sort_by, descending):
"""Creates sort_spec."""
sort_spec = []
if sort_by and descending:
for field, direction in zip(sort_by, descending):
direction = "desc" if direction else "asc"
# we have a complex field, we may need to join
if "."... | 68,910 |
def css_classes():
"""return settings or default"""
return getattr(project_settings, 'DJALOHA_CSS_CLASSES', ()) | 68,911 |
def load_position(dir_path: str, label_file: str) -> array:
"""Loads position of an object from a file.
Parameters
----------
dir_path : str
Folder of the file.
label_file : str
File name.
Returns
-------
array
Position of an object defined by a bounding box.
... | 68,912 |
def camel_2_snake_case(word):
"""
>>> camel_2_snake_case("HTTPResponseCodeXYZ")
'http_response_code_xyz'
From https://stackoverflow.com/a/1176023/548792
"""
return re.sub(r"((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))", r"_\1", word).lower() | 68,913 |
def copy_to_device(target_device, source_device="/cpu:0"):
"""A transformation that copies dataset elements to the given `target_device`.
Args:
target_device: The name of a device to which elements will be copied.
source_device: The original device on which `input_dataset` will be placed.
Returns:
A... | 68,914 |
def get_run_info():
"""
get run base info
"""
return _global_dict["run_info"] | 68,915 |
def generate_configs(experiment_config):
"""Generate parameter configurations based on an input configuration.
Input is a nested configuration where on each level there can be 'fixed', 'grid', and 'random' parameters.
In essence, we take the cartesian product of all the `grid` parameters and take random s... | 68,916 |
def now_str(time=False):
"""Return string to be used as time-stamp."""
now = datetime.now()
return now.strftime(f"%Y-%m-%d{('_%H:%M:%S' if time else '')}") | 68,917 |
def set_ai_character(controller, character, gamestate, port,
opponent_port):
"""Set the given controller to the STANDARD state playing as the given character.
This is to be called repeatedly each frame while in the character selection menu.
Returns true once it is complete."""
if ga... | 68,918 |
def camino_minimo(inicio, fin, rutas, ciudades, grafo):
"""Devuelve una lista con el camino mas corto y de menor coste entre inicio y fin (ambas ciudades de nuestro grafo)
Pre: inicio, fin son las IDs de las ciudades; rutas es un diccionario con objetos Ruta (rutas[id_ciudad1][id_ciudad2]), y ciudades es un dic... | 68,919 |
def get_custom_refinfo(*args):
"""
get_custom_refinfo(crid) -> custom_refinfo_handler_t const *
Get definition of a registered custom refinfo type.
@param crid (C++: int)
"""
return _ida_nalt.get_custom_refinfo(*args) | 68,920 |
def test_scenario2(address12):
"""Test JUN instruction failure."""
chip_test = Processor()
chip_base = Processor()
# Simulate conditions at START of operation in base chip
# chip should have not had any changes as the operations will fail
# N/A
# Simulate conditions at END of operation in ... | 68,921 |
def re_tester(regex, flags=0):
"""Creates a predicate testing passed string with regex."""
if not isinstance(regex, _re_type):
regex = re.compile(regex, flags)
return lambda s: bool(regex.search(s)) | 68,922 |
def objective_function(n_splits, PopFrenetPath, curv_smoother, tors_smoother, hyperparam, smoothing, alignment, lam, parallel):
"""
Objective function that do the cross validation.
...
"""
print(hyperparam)
# kf = KFold(n_splits=n_splits, shuffle=True, random_state=1)
kf = KFold(n_splits=n_s... | 68,923 |
def from_file(path: str) -> set:
"""
Read conditions from a file. Each line contains a separate condition.
:param path: Path to file.
:return: Read conditions.
"""
conditions = set()
with open(path) as f:
for line in f:
conditions.add(line)
return conditions | 68,924 |
def clean(params):
"""
Remove temporary files
"""
elevation.datasource.distclean(cache_dir=params.tmp) | 68,925 |
def from_gca_point(gca_obj, name_header, folder_name, folder_description='',
altitude_mode="ctg", style_to_use=None, pt_hidden=False, folder_collapsed=True):
"""
Save features from GCA object into a kml folder
Parameters
----------
gca_obj : GCA
name_header : str
The ... | 68,926 |
def join_positions(pos1,pos2):
""" Merge two positions and return as a list of strings
pos1: iterable object containing the first positions data
pos2: iterable object containing the second positions data
Example:
>>> join_positions('ABCD','1234')
['A1', 'B2', 'C... | 68,927 |
def netdev_down(netdev):
"""Bring down a bare network device"""
if not netdev_exists(netdev):
log("netdev: down: device %s does not exist, ignoring" % netdev)
return
run_command(["/sbin/ifconfig", netdev, 'down']) | 68,928 |
def get_corrcal_gainsol(data,ant1,ant2,gain_int,noise,sky_cov_vecs,src_vecs,block_edges,gain_fac,maxiter=1000):
"""
This fuction solve for antenna gain per frequency.
Method : Conjugate-gradient Method
Software : python scipy.optimize --- fmin_cg
Parameters
----------
data : array; sh... | 68,929 |
def writePQR(filename, atoms):
"""Write *atoms* in PQR format to a file with name *filename*. Only
current coordinate set is written. Returns *filename* upon success. If
*filename* ends with :file:`.gz`, a compressed file will be written."""
if not isinstance(atoms, Atomic):
raise TypeError(... | 68,930 |
def output(line):
"""Output normal message"""
sys.stdout.write('{}\n'.format(line)) | 68,931 |
def start(urls, output_dir=None, cover_path=None, out_format='epub'):
"""
start the job using url
Args:
urls: A string represent the urls which was input by user
output_dir: A string represent the path of the output EPUB file
cover_path: A string represent the path of the EPUB cover... | 68,932 |
def test_initialize():
"""A test for the initialize() function"""
assert(plotting.initialize() is None) | 68,933 |
def retrieve_vlan_id():
"""
Retrieves VLAN ids of in-band interfaces.
This function fetchs vlan ids from OLT /broadcom/bal_config.ini file.
:return : vlan id of in-band interface if successfull and None in case of failure.
:rtype : integer(valid vlan_id) in case of success, else None in case of fa... | 68,934 |
def read_intersections(fname1, fname2, band1=None, band2=None):
"""Read in the intersection of 2 files as an array"""
bounds = get_intersection_bounds(fname1, fname2)
print(f"bounds: {bounds}")
im1 = copy_vrt(fname1, out_fname="", bbox=bounds)
im2 = copy_vrt(fname2, out_fname="", bbox=bounds)
re... | 68,935 |
def transformer(vocab_size, num_layers, units, d_model,
num_heads, dropout, name="transformer"):
"""
transformer的粗粒度的结构实现,在忽略细节的情况下,看作是
encoder和decoder的实现,这里需要注意的是,因为是使用self_attention,
所以在输入的时候,这里需要进行mask,防止暴露句子中带预测的信息,影响
模型的效果
:param vocab_size:token大小
:param num_layers:编码解码... | 68,936 |
def nn_layer(input_tensor, input_dim, output_dim, layer_name, act=tf.nn.relu):
"""Reusable code for making a simple neural net layer.
It does a matrix multiply, bias add, and then uses ReLU to nonlinearize.
It also sets up name scoping so that the resultant graph is easy to read,
and adds a number of s... | 68,937 |
def root():
"""
Returns:
cim.objects.TreeNamespace: the root namespace of the win7/deleted-instance repo.
"""
r = repo()
with cim.objects.Namespace(r, cim.objects.ROOT_NAMESPACE_NAME) as ns:
yield ns | 68,938 |
def main():
"""Computes a list of duplicate movie entries."""
# Students should not run two profiling functions at the same time,
# e.g. they should not be running 'timeit' on a function that is
# already decorated with @profile
filename = 'movies.txt'
print("--- Before optimization ---")
... | 68,939 |
def get_device_names():
"""
"""
devices = [comport.device for comport in serial.tools.list_ports.comports()]
devices = [comport.device for comport in serial.tools.list_ports.comports()]
device_names = []
if os.name == 'posix': # macOS
# Strip the device prefix
device_names... | 68,940 |
def _main() -> None:
"""Helper function for script execution
:rtype: None
"""
import random
import sys
try:
topic = sys.argv[1]
except IndexError:
topic = random.choice(('math', 'trivia', 'date', 'year'))
fact = get_random_fact(topic)
print(f"Random '{topic}' fac... | 68,941 |
def divide(data: tuple, domain='freq'):
"""Divide pyfar audio objects, array likes, and scalars.
Pyfar audio objects are: :py:func:`Signal`, :py:func:`TimeData`, and
:py:func:`FrequencyData`.
Parameters
----------
data : tuple of the form (data_1, data_2, ..., data_N)
Data to be divide... | 68,942 |
def first_job(api, dates, t_current):
"""
Creates the tables and populates them with the historical data
from T_0
to T_current
"""
# subset of dates
dates_hist = dates[dates <= t_current]
# crime_categories table
s_crime_cat = set()
for date in dates_hist:
s_crime_... | 68,943 |
def norm_D_sum(D_sum):
"""Normalize a D_sum by the elements for each feature by
smallest absolute size (that element becomes 1 in norm).
For unweighted feature sensitivities, or else it
unweights weighted ones."""
D_n = {}
for feat, pD in D_sum.items():
pD_min_abs = min(abs(array(pD.valu... | 68,944 |
def collate_fn(data):
"""Creates mini-batch tensors from the list of tuples (image, caption).
We should build custom collate_fn rather than using default collate_fn,
because merging caption (including padding) is not supported in default.
Args:
data: list of tuple (image, caption).
... | 68,945 |
async def ntest_admin_create_group(setup):
"""Proves that can login and use admin api.
All api uses application/json body and not urlencode, except for login.
"""
me, app, client, admin_log, user_log, logout = setup
admin_log()
res = client.post("/groups/add", data=dumps({"short": "New group 3... | 68,946 |
def getLeastReplaggedCommons():
"""
Returns the name of the least replagged Commons replica among s1, s2 and s3
"""
return "commonswiki-p.rrdb.toolserver.org"
# broken:
#return urllib.urlopen("http://toolserver.org/~eusebius/leastreplag").readline() | 68,947 |
def reportCoverage(logger, bins=False):
"""Print sorted coverage with optional bins details.
Args:
logger (func): a logger object.
bins (bool): print bins details.
"""
sorted_cov = sorted(coverage_db, key=str.lower)
for ii in sorted_cov:
logger(" " * ii.count('.') + "%s :... | 68,948 |
def parse_line(header, line):
"""Parse one line of data from the message file.
Each line is expected to contain chunk key - comma - tile key (CSV style).
Args:
header (dict): Data to join with contents of line to construct a full message.
line (string): Contents of the line.
Returns:
... | 68,949 |
async def handle(request):
""" index req """
dt = datetime.datetime.now()
dtstr = str(dt)
myulid = ulid.new()
strmyulid = myulid.str
intmyulid = myulid.int
bmyulid = bazed_ulid(intmyulid)
text = tpl % (
version, dtstr, strmyulid, len(strmyulid), bmyulid, len(bmyulid))
# ... | 68,950 |
def start_protocol(self,wait_time='1m'):
""" Starts all protocols and wait for ``wait_time``
Default ``wait_time`` is 1 minute. Make sure ``wait_time`` is big engouh to
start all protocols.
"""
cli = self._clients[self._cur_name]
ix = cli['connection']
result = ix.execute('startAllProtoco... | 68,951 |
def filequote(text):
"""Transform text to file name."""
trans = str.maketrans(' /()', '____')
return text.translate(trans) | 68,952 |
def do_role_component_show(cs, args):
"""Show details about a component by zone and role."""
zone = _find_zone(cs, args.zone)
role = _find_role(cs, args.zone, args.role)
component = args.component
component_zone_role = cs.components.get_zone_role(zone, role, component)
keys = ['_links']
fina... | 68,953 |
def SingleQubitIRB_AC(qubit: qreg, seqFile):
"""
Single qubit interleaved randomized benchmarking using atomic Clifford pulses.
Parameters
----------
qubit : logical channel to implement sequence (LogicalChannel)
seqFile : file containing sequence strings
"""
# Original:
# # Setup... | 68,954 |
def characteristic(text, ontology=None):
"""
Making a ENA Biosamples characteristic
"""
if ontology:
return [{"text": text, "ontologyTerms": [ontology]}]
else:
return [{"text": text}] | 68,955 |
def test_4_1_17_audit_rule_file_exists(host):
"""
CIS Ubuntu 20.04 v1.0.0 - Rule # 4.1.17
Tests if /etc/audit/rules.d/4.1.17.rules file exists
"""
host.file(RULE_FILE_4117).exists | 68,956 |
def test_reconnecting_after_disconnect(hass, monkeypatch):
"""An unexpected disconnect should cause a reconnect."""
domain = 'sensor'
config = {
'rflink': {
'port': '/dev/ttyABC0',
CONF_RECONNECT_INTERVAL: 0,
},
domain: {
'platform': 'rflink',
... | 68,957 |
def prepare_query_res_pairs(params):
""" prepare query-response raw pairs """
raw_file_path = params['raw_file_path']
raw_data = json.load(open(raw_file_path, 'rb'))
print(("#dialog", len(raw_data)))
print("sessID\tMsgID\tText\tDialogAct")
f = open('./multiwoz/annotated_qr_pairs.t... | 68,958 |
def create_update_ledger_template(
token_address: str,
data: CreateUpdateLedgerTemplateRequest,
issuer_address: str = Header(...),
db: Session = Depends(db_session)):
"""Create or Update Ledger Template"""
# Validate Headers
validate_headers(issuer_address=(issuer_address, a... | 68,959 |
def create_table(table_name: str, schema_name: str, columns: dict, partitions: dict, path: str, session_helper: SessionHelper):
"""
Creates a table in AWS redshift. The table will be named schema_name.table_name and belong to the (existing) Redshift db db_name.
Args:
table_name: name of created tabl... | 68,960 |
def nexmon(csifile, index, chip, bw):
"""nexmon"""
print("="*40+"[nexmon]")
if csiread.__version__ < '1.3.5':
print("csiread.Nexmon: version >= 1.3.5 is required");return
members = [s for s in dir(csiread.Nexmon) if not s.startswith("__") and callable(getattr(csiread.Nexmon, s))]
print("Me... | 68,961 |
def clear_access_list_hitcounts_ip_interface(
enode, acl_name, port,
_shell='vtysh',
_shell_args={
'matches': None,
'newline': True,
'timeout': None,
'connection': None
}
):
"""
Clear ACL state values per port.
This function runs the following vtysh command:
... | 68,962 |
def expand_template(template_path, destination_path, data):
"""
Expand an EmPy template.
The directory of the destination path is created if necessary.
:param template_path: The patch of the template file
:param destination_path: The path of the generated expanded file
:param dict data: The da... | 68,963 |
def get_full_vol_name(vmdk_name, datastore, vm_datastore):
"""
Forms full volume name from vmdk file name an datastore as volume@datastore
For volumes on vm_datastore, just returns volume name
"""
vol_name = vmdk_utils.strip_vmdk_extension(vmdk_name)
logging.debug("get_full_vol_name: %s %s %s", ... | 68,964 |
def import_od(source, node_id=None):
"""Parse an EDS, DCF, or EPF file.
:param source:
Path to object dictionary file or a file like object or an EPF XML tree.
:return:
An Object Dictionary instance.
:rtype: canopen.ObjectDictionary
"""
if source is None:
return ObjectD... | 68,965 |
def _strip_trailing_ffs(binary_table):
"""
Strip all FFs down to the last 32 bytes (terminating entry)
"""
while binary_table.endswith("\xFF"*64):
binary_table = binary_table[0:len(binary_table)-32]
return binary_table | 68,966 |
def customization_data(client=None):
"""Produce any customization definitions (types, fields, message destinations, etc)
that should be installed by `resilient-circuits customize`
"""
# This import data contains:
# Incident fields:
# ml_prediction
# Function inputs:
# ml_... | 68,967 |
def params_schedule_fn_constant_09_01(outside_information):
"""
In this preliminary version, the outside information is ignored
"""
mdp_default_gen_params = {
"inner_shape": (7, 5),
"prop_empty": 0.9,
"prop_feats": 0.1,
"start_all_orders": [
{"ingredients": ["... | 68,968 |
def getFileListing(files, recurse):
"""Creates recursive or non-recursive file listing.
Args:
file: path to evaluate
recurse: True/False value which dictates whether the listing is recursive
Returns:
fileList: array containing the results of the file listing
"""
logger.debu... | 68,969 |
def is_same_day(t1, t2, refresh_time=None):
"""check two times in same day"""
return get_day_time(t1, refresh_time) == get_day_time(t2, refresh_time) | 68,970 |
def main(args):
"""Main function.
Args:
args (ArgumentParser): arguments
"""
# Logging
if args.verbose:
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=logging.WARNING)
can_decoder = CANDecoder(args.assign_list)
can_data = can_decoder.a... | 68,971 |
def benchmark(synthesizers, datasets=DEFAULT_DATASETS, iterations=3, add_leaderboard=True,
leaderboard_path=LEADERBOARD_PATH, replace_existing=True):
"""Compute the benchmark scores for the synthesizers and return a leaderboard.
The ``synthesizers`` object can either be a single synthesizer or, a... | 68,972 |
def test_measmodestmt_factory():
""" Test MeasuringModeStmt factory method
"""
line = 'M72'
stmt = MeasuringModeStmt.from_excellon(line)
assert_equal(stmt.units, 'inch')
line = 'M71'
stmt = MeasuringModeStmt.from_excellon(line)
assert_equal(stmt.units, 'metric') | 68,973 |
def context_from_format(format_def: str, **kwargs) -> (
InvokeContext, io.BytesIO):
"""
Creates a context from request
:param format_def: function format
:type format_def: str
:param kwargs: request-specific map of parameters
:return: invoke context and data
:rtype: tuple
"""
... | 68,974 |
def detec_data_space():
"""判断是否有free分区磁盘"""
diskLists = commands.getoutput(""" fdisk -l | grep -iw "^Disk"
| grep "/dev/" | grep -vi "\/mapper\/"
| awk -F ":" '{print $1}' |
awk '{print $2}' | sort """)
diskLists = diskLists.split('\n')
return diskLists | 68,975 |
def arctand(x):
"""Trigonometric inverse tangent using :func:`np.arctan <numpy.arctan>`, element-wise with an output in degree.
Parameters
----------
x : array_like
Input array.
Returns
-------
y : array_like
The corresponding tangent values. This is a scalar if x is a scal... | 68,976 |
def test_options_class_attr(request, test_options):
"""Provides test_options as class attribute
Used as transition from TestCase to pytest
"""
request.cls.test_options = test_options | 68,977 |
def byte_to_float(b1, b2, b3, b4):
"""
A function to get a 32 bit float from 4 bytes read in order [b1, b2, b3, b4]
:param b1: first byte
:param b2: second byte
:param b3: third byte
:param b4: fourth byte
:return: the byte array from b1, b2, b3, b4 unpacked as a float using the 'struct' mod... | 68,978 |
def interpolate_and_average(xs, ys, interp_points=None):
"""
Average bunch of repetitions (xs, ys)
into one curve. This is done by linearly interpolating
y values to same basis (same xs). Maximum x of returned
curve is smallest x of repetitions.
If interp_points is None, use maximum number of p... | 68,979 |
def classFactory(iface): # pylint: disable=invalid-name
"""Load PlanheatMappingPlugin class from file PlanheatMappingPlugin.
:param iface: A QGIS interface instance.
:type iface: QgsInterface
"""
#
from .PlanheatMappingPlugin import PlanheatMappingPlugin
return PlanheatMappingPlugin(iface) | 68,980 |
def test_fromIsoFormat(gregorian: str, tzolkin: TzolkinDate) -> None:
"""Test `Tzolkin.fromIsoFormat`."""
gregorian_date = datetime.datetime.strptime(gregorian, USED_DATEFMT).date()
to_test = Tzolkin.fromIsoFormat(date_str=gregorian_date.isoformat())
assert to_test.getDayNumber() == tzolkin.number # no... | 68,981 |
def clean_website_build():
"""Clean content directory and remove output directory"""
content_path = "content"
content_pages_path = os.path.join(content_path, "pages")
# Clean content directory
for filename in os.listdir(content_path):
if filename != "docs" and filename != "pages":
... | 68,982 |
def plot_marker_3d(x, y, z, max_size=0.75, min_size=0.05, marker_type='scatter', num_lines=8, ax=None, **kwargs):
"""Pseudo-3D scatter plot using marker size to indicate height.
This plots markers at given ``(x, y)`` positions, with marker size determined
by *z* values. This is an alternative to :func:`mat... | 68,983 |
def linerlyInterpSelected():
"""convenience function to interpolate selected. Select A and B then the
rest of the nodes to constrain
"""
selected = cmds.ls(sl=True)
if not len(selected) > 2:
return
a = selected[0]
b = selected[1]
nodes = selected[2:]
linerlyInterperlateNodes(... | 68,984 |
def is_record(obj):
"""Check whether ``obj`` is a "record" -- that is, a (text, metadata) 2-tuple."""
if (
isinstance(obj, (tuple, list))
and len(obj) == 2
and isinstance(obj[0], compat.unicode_)
and isinstance(obj[1], dict)
):
return True
else:
return Fal... | 68,985 |
def get_used_by_from_comments(lines: "list[str]") -> "tuple[int, list[str]]":
"""Read the module-used-by block comment from a module file.
Args:
lines (list[str]): The content of the module file as a list of strings.
Returns:
tuple[int, list[str]]: The integer indicates the last line numbe... | 68,986 |
def test_device_put_method_end_with_line_break_device_type(flask_app, db): # pylint: disable=unused-argument
""" To verify that registration device
method is working properly and response is correct"""
registration = create_registration(REG_REQ_DATA, uuid.uuid4())
registration.update_status('Pendi... | 68,987 |
def text_to_layer(block, unit, return_sequences=False):
"""Build tensorflow layer, easily."""
layer = None
if block == "CNN":
layer = tf.keras.layers.Conv1D(unit, kernel_size=1, strides=1, padding='same', activation='relu')
elif block == "LCNN":
layer = tf.keras.layers.LocallyConnected1D... | 68,988 |
def construct_target_path(participant_name, model_name, roi):
"""Construct path to save results to."""
project_root = Path(__file__).parents[1]
return project_root / "results" / participant_name / f"model_{model_name}"\
/ f"roi_{roi}" | 68,989 |
def txidFromBroadcast (hexStr):
"""Extracts the hex txid from a broadcast in hex."""
# The prevout txid is the first part of the broadcast data
# in serialised form. But we need to reverse the bytes.
hexRev = hexStr[:64]
bytesRev = codecs.decode (hexRev, "hex")
return bytesRev[::-1].hex () | 68,990 |
def _tm_range_from_secs(start, dur, rate=25.0):
"""
Return a TimeRange for the given timestamp and duration (in
seconds).
"""
return otio.opentime.TimeRange(
_rat_tm_from_secs(start), _rat_tm_from_secs(dur)) | 68,991 |
def clear(without=""):
"""
Clear images of all phases, can specify --without as filter
"""
yml = lain_yaml(ignore_prepare=True)
without_phases = without.split(',')
for name in yml.img_names.values():
if docker.get_phase(name) not in without_phases:
docker.remove_image(name) | 68,992 |
def is_known_scalar(value):
"""
Return True if value is a type we expect in a dataframe
"""
def _is_datetime_or_timedelta(value):
# Using pandas.Series helps catch python, numpy and pandas
# versions of these types
return pd.Series(value).dtype.kind in ('M', 'm')
return not ... | 68,993 |
def get_model_results(ldamodel, corpus, dictionary):
""" Create doc-topic probabilities table and visualization for the LDA model
"""
vis = pyLDAvis.gensim.prepare(ldamodel, corpus, dictionary, sort_topics=False)
transformed = ldamodel.get_document_topics(corpus)
df = pd.DataFrame.from_records([{... | 68,994 |
def i18n(request):
"""
Set client language preference, lasts for one month
"""
from django.conf import settings
next = request.META.get('HTTP_REFERER', settings.SITE_ROOT)
lang = request.GET.get('lang', settings.LANGUAGE_CODE)
if lang not in [e[0] for e in settings.LANGUAGES]:
# la... | 68,995 |
def repr_errors(res, estimator=None, method: Optional[str] = None) -> str:
"""Pretty print original docstring and the obtained errors
Parameters
----------
res : dict
result of numpydoc.validate.validate
estimator : {estimator, None}
estimator object or None
method : str
... | 68,996 |
def install_with_constraints(session: Session, *args: str, **kwargs: Any) -> None:
"""Install Packages constrained by Poetry's lock file.
See https://cjolowicz.github.io/posts/hypermodern-python-03-linting/
Args:
session: Session from Nox
*args: Args
**kwargs: Kwards
"""
wi... | 68,997 |
def get_modelfield(typo):
"""
>>> get_modelfield('Input')
<class 'hstore_flattenfields.db.fields.HstoreCharField'>
>>> get_modelfield('Integer')
<class 'hstore_flattenfields.db.fields.HstoreIntegerField'>
>>> get_modelfield('Random')
<class 'hstore_flattenfields.db.fields.HstoreCharField'>
... | 68,998 |
def initialize_aggregation_file(config, fullpath):
# type: (Config, str) -> None
"""
Based on the configuration, initialize a file in which to write the aggregated output.
In other words, resurrect a netcdf file that would result in config.
:param config: Aggregation configuration
:param ... | 68,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.