content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_boolean_unpack() -> None:
"""Test boolean unpack."""
type = data_types.Boolean()
type.unpack(bytearray([0x55]))
assert type.value
assert type.size == 0 | 5,321,700 |
def block_solve_agd(
r_j,
A_j,
a_1_j,
a_2_j,
m,
b_j_init,
t_init=None,
ls_beta=None,
max_iters=None,
rel_tol=1e-6,
verbose=False,
zero_thresh=1e-6,
zero_fill=1e-3,
):
"""Solve the optimization problem for a single block with accelerated
gradient descent."""
... | 5,321,701 |
def RemoveAuthorizedKey(file_name, key):
"""Removes an SSH public key from an authorized_keys file.
@type file_name: str
@param file_name: path to authorized_keys file
@type key: str
@param key: string containing key
"""
RemoveAuthorizedKeys(file_name, [key]) | 5,321,702 |
def get_jars_location():
"""
Return the location of the JAR files for installed library.
"""
root_dir = os.path.dirname(flexneuart.__file__)
return os.path.join(root_dir, 'resources/jars/') | 5,321,703 |
def bin_array_max(arr, bin_size, pad_value=0):
"""
Given a NumPy array, returns a binned version of the array along the last
dimension, where each bin contains the maximum value of its constituent
elements. If the array is not a length that is a multiple of the bin size,
then the given pad will be u... | 5,321,704 |
def harmony(img, center, angle=None):
"""Harmonize the pattern by exploiting symmetry
If the shape of the pattern is not anymore odd after the rotation has been
performed the pattern is padded with zeros such that its shape is odd.
:param img: pattern
:param center: center coordinates in patte... | 5,321,705 |
def getClimateDataForStation(config, outputDir, outFilename, stationID, overwrite=True):
"""Fetch climate timeseries data for a GHCN daily station
@param config A Python ConfigParser (not currently used)
@param outputDir String representing the absolute/relative path of the directory into which... | 5,321,706 |
def is_following(request, author) -> bool:
"""Checks if this author is in the user's subscriptions"""
if Follow.objects.filter(user=request.user, author=author):
return True
return False | 5,321,707 |
def find_revert_op(input_state_index: int):
"""Looks in the Cayley table the operation needed to reset the state to ground state from input state_tracker
:param input_state_index: Index of the current state tracker
:return: index of the next Clifford to apply to invert RB sequence
"""
for i in rang... | 5,321,708 |
def _column_number_to_letters(number):
"""
Converts given column number into a column letters.
Right shifts the column index by 26 to find column letters in reverse
order. These numbers are 1-based, and can be converted to ASCII
ordinals by adding 64.
Parameters
----------
number : int... | 5,321,709 |
def toGRBFromStr():
""" Module for program-wide constant maps (e.g., dicts that should never change) """
import gurobipy as gb
return {"=": gb.GRB.EQUAL,
"le": gb.GRB.LESS_EQUAL,
"ge": gb.GRB.GREATER_EQUAL} | 5,321,710 |
def _generate_mea_comment(obj: GamObject, object_module: GamObject):
"""
Check whether the object has a module, then generate the measurement comment and update the object ID to add
the measurement to.
Args:
obj (GamObject): The object.
object_module (GamObject): The object module, if t... | 5,321,711 |
def master_do(func, *args, **kwargs):
"""Help calling function only on the rank0 process id ddp"""
try:
rank = dist.get_rank()
if rank == 0:
return func(*args, **kwargs)
except AssertionError:
# not in DDP setting, just do as usual
func(*args, **kwargs) | 5,321,712 |
def news_msg(result):
""" Interface Function for news intent """
campus_publication = ""
news_result = []
try:
campus_publication = result.parameters['club']
campus_publication = campus_publication.lower()
except BaseException:
campus_publication = ""
return ... | 5,321,713 |
def init_aws_client():
"""Initializes and returns AWS boto3 client object"""
client = boto3.client("network-firewall")
return client | 5,321,714 |
def verify_file_integrity(fchunk):
"""
@TODO: implement
"""
logger.debug("Verify md5sum...{}".format(fchunk))
return True | 5,321,715 |
def _chunk_member_lag(chunk, repl_member_list, primary_optimedates, test_run_indices):
"""Helper function to compute secondary lag from values in a chunk
:param collection.OrderedDict chunk: FTDC JSON chunk
:param list[str] repl_member_list: list of all members in the replSet
:param str primary: which ... | 5,321,716 |
def graph_build_split(X, edge_index, node_mask: np.array):
""" subgraph building through spliting the selected nodes from the original graph """
row, col = edge_index
edge_mask = (node_mask[row] == 1) & (node_mask[col] == 1)
ret_edge_index = edge_index[:, edge_mask]
return X, ret_edge_index | 5,321,717 |
def get_pagination_class():
"""
Returns custom pagination class, set in settings
"""
pagination_class = LIKES_REST_PAGINATION_CLASS
if pagination_class:
try:
return import_string(pagination_class)
except ImportError:
pass
return api_settings.DEFAULT_PAGI... | 5,321,718 |
def get_us_presidents_gender(president):
"""Given the name of a US President, return his gender, or None if not found. """
data = load('us_president_gender')
for row in data:
if row['president'] == president:
return row['gender']
return None | 5,321,719 |
def ProtoFromTfRecordFiles(files,
max_entries=10000,
features=None,
is_sequence=False,
iterator_options=None):
"""Creates a feature statistics proto from a set of TFRecord files.
Args:
files: A list of d... | 5,321,720 |
def smallest_evenly_divisible(min_divisor, max_divisor, minimum_dividend=0):
"""Returns the smallest number that is evenly divisible (divisible
with no remainder) by all of the numbers from `min_divisor` to
`max_divisor`. If a `minimum_dividend` is provided, only dividends
greater than this number will ... | 5,321,721 |
def execute(args):
"""Coastal Blue Carbon.
Args:
workspace_dir (str): location into which all intermediate and
output files should be placed.
results_suffix (str): a string to append to output filenames.
lulc_lookup_uri (str): filepath to a CSV table used to convert
... | 5,321,722 |
def pct75(input_tensor, weights_tensor):
"""Compute the 75th percentile of a given tensor."""
del weights_tensor
return tfp.stats.percentile(input_tensor, 75) | 5,321,723 |
def get_bad_sequences(GoodSequenceList, Bad1st_list, BadOther_list):
"""Take each good sequence and implant a codec error at any possible byte
position.
RETURNS: List of bad sequences.
"""
result = []
for sequence in GoodSequenceList:
# Implement a couple of bad sequences based on the g... | 5,321,724 |
def factorial(n):
"""
Returns the factorial of n
Parameters
----------
n : int
denotes the non-negative integer for which factorial value is needed
"""
if(n<0):
raise NotImplementedError(
"Enter a valid non-negative integer"
)
if(n==0 or n==... | 5,321,725 |
def main():
"""
CRSF Driver node wrapper
"""
rospy.init_node("CRSF joy emulation driver")
rospy.loginfo("CRSF joy emulation driver starting")
publisher = rospy.Publisher("~/joy", Joy, queue_size=10)
config = CRSFConfiguration(
rospy.get_param("~mapping/axis", default=[]),
ros... | 5,321,726 |
def check_redis(*args, **kwargs):
"""Checks if configured Redis instance is pingable."""
try:
r = StrictRedis.from_url(current_app.config['CACHE_REDIS_URL'])
t1 = time.time()
res = r.ping()
t2 = time.time()
return 'redis', res, {'time': t2 - t1}
except (ConnectionErro... | 5,321,727 |
def Divide(a, b):
"""Returns the quotient, or NaN if the divisor is zero."""
if b == 0:
return float('nan')
return a / float(b) | 5,321,728 |
def convert_file_idea_into_idmef(input_filename, output_filename, time_output_filename=None, unconverted_filename=None,
single_message=False, prettify=False, idmef_namespace=False):
"""
Function which takes file with IDEA message (messages) and converts it into file with IDMEF m... | 5,321,729 |
def craft_item():
"""Get craft item from environ varriable"""
return os.environ.get('CRAFT_ITEM', None) | 5,321,730 |
def guess_typecode(value):
"""Guess Gwyddion typecode for `value`."""
if np.isscalar(value) and hasattr(value, 'item'):
# Seems to be a numpy type -- convert
value = value.item()
if isinstance(value, GwyObject):
return 'o'
elif isinstance(value, string_types):
if len(valu... | 5,321,731 |
def _ProtobufDefinitionToFields(message_class):
"""Flattens the fields in a protocol buffer definition.
For example, given the following definition:
message Point {
required int32 x = 1;
required int32 y = 2;
optional string label = 3;
}
message Polyline {
repeated Point point... | 5,321,732 |
def create_region(entity: Entity, author: Identity) -> Identity:
"""Create a region"""
custom_properties: Dict[str, Any] = {"x_opencti_location_type": "Region"}
return Location(
created_by_ref=author,
name=entity.value,
region=entity.value,
custom_properties=custom_propertie... | 5,321,733 |
def roles_list(sphinx, extensions):
"""List available roles."""
namespace = compile_namespace(extensions=extensions, use_sphinx=sphinx)
click.echo(" ".join(namespace.list_roles())) | 5,321,734 |
def post(post_id):
"""
实例化一个评论表单,并将其传入post.html
:param post_id:
:return:
"""
post = Post.query.get_or_404(post_id)
form = CommentForm()
if form.validate_on_submit():
comment = Comment(comment_body=form.comment_body.data,
post=post,
... | 5,321,735 |
def noisify(chse, dE, dt, dU):
"""
Create a nosified chain
Parameters
chse : Chain instance
cE: float
spread in on-site energies
dt: float
spread in hoppings
dU: float
spread in interaction
"""
dEs = np.zeros((chse.N,))
dts = np.zeros((chse.N,))
dUs =... | 5,321,736 |
def test_dicts_same_keys(dpaths, sw):
"""Test translation vectors startwidth keys."""
assert all(k.startswith(sw) for k in dpaths) | 5,321,737 |
def test_from_data_frame_time_series_data_set_multi_call(patch_time_series_data_set):
"""Tests that ``TabularForecastingData.from_data_frame`` calls ``TimeSeriesDataSet`` with the expected
parameters when called separately for each stage."""
patch_time_series_data_set.return_value.get_parameters.return_valu... | 5,321,738 |
def kepio(keplcfile):
"""Read in a Kepler LC file and return the time, flux, and error"""
with fits.open(keplcfile) as hdu:
print(hdu.info())
t = hdu[1].data["TIME"]
f = hdu[1].data["SAP_FLUX"]
e = hdu[1].data["SAP_FLUX_ERR"]
return t,f,e | 5,321,739 |
def camera_matrix(K: np.ndarray, R: np.ndarray, t: np.ndarray) -> np.ndarray:
"""Derive the camera matrix.
Derive the camera matrix from the camera intrinsic matrix (K),
and the extrinsic rotation matric (R), and extrinsic
translation vector (t).
Note that this uses the matlab convention, such tha... | 5,321,740 |
def point_point_copy(inpath, outpath, filename):
"""
Copy a file from one absolute path to another.
:param inpath: Input path.
:type inpath: str
:param outpath: Output path.
:type outpath: str
:param filename: Filename.
:type filename: str
"""
if os.sep in filename:
fi... | 5,321,741 |
def path_leaf(path):
"""
Extract the file name from a path.
If the file ends with a slash, the basename will be empty,
so the function to deal with it
Parameters
----------
path : str
Path of the file
Returns
-------
output : str
The name of the file
"""
... | 5,321,742 |
def expand_import_star(
node: Union[ast.ImportFrom, _nodes.ImportFrom], path: Path
) -> Union[ast.ImportFrom, _nodes.ImportFrom]:
"""Expand import star statement, replace the `*` with a list of ast.alias.
:param node: `_nodes/ast.ImportFrom` node that has a '*' as `alias.name`.
:param path: where the n... | 5,321,743 |
def hoi2result(instance_labels, verb_scores, bboxes, sub_ids, obj_ids, max_per_img=100, valid_hois=None):
"""Convert detection hois to a list of numpy arrays.
Used in QPIC.
Args:
valid_hois ():
max_per_img ():
obj_ids ():
sub_ids ():
verb_scores ():
instance_... | 5,321,744 |
def focus_metric(data, merit_function='vollath_F4', **kwargs):
"""Compute the focus metric.
Computes a focus metric on the given data using a supplied merit function.
The merit function can be passed either as the name of the function (must be
defined in this module) or as a callable object. Additional... | 5,321,745 |
def get_canonical_import(import_set):
"""Obtain one single import from a set of possible sources of a symbol.
One symbol might come from multiple places as it is being imported and
reexported. To simplify API changes, we always use the same import for the
same module, and give preference to imports coming from... | 5,321,746 |
def additive_white_gaussian_noise(signal, noise_level):
"""
Add gaussian white noise to audio signal.
:param signal: Audio signal to permute.
:param noise_level: standard deviation of the gaussian noise.
"""
# SNR = 10 * log((RMS of signal)^2 / (RMS of noise)^2)
# RMS_s = np.sqrt(np.mean(si... | 5,321,747 |
def data_four_of_a_kind():
"""Prepare data for Four of a Kind
"""
random.seed(None)
for deuces in (0, 1, 2, 3):
for rank in ranks_no_deuce:
second_rank = rank
while second_rank == rank:
second_rank = ranks_no_deuce[
random.randint(0, le... | 5,321,748 |
def _tensor_in(tensor: torch.Tensor, iterable: Iterable[torch.Tensor]):
"""Returns whether `tensor is element` for any element in `iterable` This function is necessary because `tensor in
iterable` does not work reliably for `Tensor`s.
See https://discuss.pytorch.org/t/how-to-judge-a-tensor-is-in-a-list/159... | 5,321,749 |
def test_get_config_invalid():
"""Test that we get a proper exception on an invalid config."""
config_file = StringIO(
"""{
"source_jira": {
"url": "https://source.atlassian.net",
"email": "login@login.com",
"project_key": "JIRA",
"tempo_token": "b"
},
"destination_jira": {
"ur... | 5,321,750 |
def flip(a, dim=0):
"""
Flip an array along a dimension.
Parameters
----------
a : af.Array.
Multi dimensional array.
dim : optional: int. default: 0.
The dimension along which the flip is performed.
Returns
-------
out : af.Array
The output after flippin... | 5,321,751 |
def get_cnn_model(params):
"""
Load base CNN model and add metadata fusion layers if 'use_metadata' is set in params.py
:param params: global parameters, used to find location of the dataset and json file
:return model: CNN model with or without depending on params
"""
input_tensor = Inp... | 5,321,752 |
def is_development_mode(registry):
"""
Returns true, if mode is set to development in current ini file.
:param registry: request.registry
:return: Boolean
"""
if 'mode' in registry.settings:
return registry.settings['mode'].lower() == 'development'
return False | 5,321,753 |
def snoop_queue(mongo_collection, queue: Queue, logger: logging.Logger):
"""
Takes in items from the multiprocessing queue and yields them so that they
can consumed by streaming_bulk. After that, that item's status is updated in
mongo
"""
for item in iter(queue.get, None):
yield item
... | 5,321,754 |
def configure_logging(log_level, log_format, log_dest):
"""
Configure logging from CLI options
:param log_level: logging verbosity
:type log_level: int or str
:param log_format: format string for messages
:type log_format: str
:param log_dest: where to send log message to
:type log_dest... | 5,321,755 |
def abs_filepath(env, paths, relative_offset="."):
"""
Convert file path(s) to their absolute file path equivalent.
Args:
env (SCons.Environment): The scons environment to use
paths (str or list/tuple): The scons parameter(s) to conviert into absolute file path
relative_offset (st... | 5,321,756 |
def run_summarizer(parser, sentences, language='english'):
"""
:params parser: Parser for selected document type
:params sentences: Maximum sentences for summarizer.
:returns summary: Summarized page.
"""
summarizer = Summarizer(Stemmer(language))
summarizer.stop_words = get_stop_words(lan... | 5,321,757 |
def mk_input(ctx, name, type):
"""
mk_input(Int_ctx ctx, char const * name, Int_type type) -> Int_net
Parameters
----------
ctx: Int_ctx
name: char const *
type: Int_type
"""
return _api.mk_input(ctx, name, type) | 5,321,758 |
def coo_fromdense_mhlo(mat, *, nnz, data_dtype, index_dtype,
index_type):
"""COO from dense matrix."""
mat_type = ir.RankedTensorType(mat.type)
rows, cols = mat_type.shape
buffer_size, opaque = _hipsparse.build_coo_fromdense_descriptor(
data_dtype, index_dtype, rows, cols, nnz)
... | 5,321,759 |
def test_construct_invalid_arguments():
"""
Tests instanciating SnekConfig with invalid arguments.
"""
#
# These arguments must raise an exception when passed to SnekConfig
#
invalid_arguments = [
{'build_path': 12},
{'content_path': 12},
{'data_path': 12},
{'... | 5,321,760 |
def __get_wight(last_link: Link, end_link: Link, end_fraction, weight_function):
"""
Calculate the wight of the end_link.
:param last_link: Needed to determine from which direction you comes
:param end_link: Link from which the weight is calculated
:param end_fraction: fraction as Number (1 >= fract... | 5,321,761 |
def float_fraction(trainpct):
""" Float bounded between 0.0 and 1.0 """
try:
f = float(trainpct)
except ValueError:
raise Exception("Fraction must be a float")
if f < 0.0 or f > 1.0:
raise Exception("Argument should be a fraction! Must be <= 1.0 and >= 0.0")
return f | 5,321,762 |
def test_admin_config():
"""Does admin config return a 200 by default"""
app = create_ctfd()
with app.app_context():
client = login_as_user(app, name="admin", password="password")
r = client.get('/admin/config')
assert r.status_code == 200 | 5,321,763 |
def handle_internal(msg):
"""Process an internal message."""
internal = msg.gateway.const.Internal(msg.sub_type)
handler = internal.get_handler(msg.gateway.handlers)
if handler is None:
return None
return handler(msg) | 5,321,764 |
def _lower_bound_grad(op, grad):
"""Gradient for `lower_bound` if `gradient == 'identity_if_towards'`.
Args:
op: The op for which to calculate a gradient.
grad: Gradient with respect to the output of the op.
Returns:
Gradient with respect to the inputs of the op.
"""
inputs, bound = op.inputs
... | 5,321,765 |
def assert_any_match_regex(pattern, values, message=None):
"""Assert that at least one value in an iterable matches a regex pattern.
Args:
pattern -- a regex.
values -- an iterable of values to test.
Raises AssertionError if all values don't match.
"""
for value in values:
if re.m... | 5,321,766 |
def test_POST_aliases_unauthenticated(client, user, guid, aliases, unused_aliases):
"""
expect request to fail with 403 if user is unauthenticated
"""
new_aliases = unused_aliases
new_aliases_payload = to_payload(new_aliases)
res = client.post(get_endpoint(guid), json=new_aliases_payload)
a... | 5,321,767 |
def main():
"""Main function"""
parser = ArgumentParser()
parser.add_argument("config", help="json cluster configuration file")
parser.add_argument("command", help="command to run", nargs=REMAINDER)
args = parser.parse_args()
config = get_config(parser, args)
command = " ".join(args.command)... | 5,321,768 |
def list_ms(msname, ack=False):
""" List sources and data descriptors in a MeasurementSet
:param msname: File name of MS
:param ack: Ask casacore to acknowledge each table operation
:return: sources, data descriptors
For example::
print(list_ms('3C277.1_avg.ms'))
(['1302+5748', '03... | 5,321,769 |
def obv(s_interval: str, df_stock: pd.DataFrame) -> pd.DataFrame:
"""On Balance Volume
Parameters
----------
s_interval: str
Stock data interval
df_stock: pd.DataFrame
Dataframe of stock prices
Returns
-------
pd.DataFrame
Dataframe with technical indicator
... | 5,321,770 |
def get_cultural_hotspots(url: str, params: Dict) -> pd.DataFrame:
"""Get cultural hotspots within city boundaries."""
package = requests.get(url, params=params).json()
ch_locations = package["result"]["resources"][0]["url"]
ch_locs_dir_path = "data/raw/cultural-hotspot-points-of-interest-wgs84"
wit... | 5,321,771 |
def writeProtToPep(seenPeptides, groupedBy, outputPath):
"""
Called by writeOutputFiles(), this function produces a csv file with either the proteins as headings followed by
the peptides each protein produces underneath, or with the peptides as headings and the proteins each peptide
could have come from... | 5,321,772 |
def setopts():
""" Setup all possible command line options....
"""
usage = 'USAGE: %s [options]' % (NAME)
version = NAME + " " + __version__
parser = optparse.OptionParser(usage=usage, version=version)
parser.add_option("-v",
"--voicefile",
dest="voice... | 5,321,773 |
def run() -> None:
"""Command runner."""
APP() | 5,321,774 |
def create_track_json(
directory: str,
image_count: int,
track_count: int,
type_count: int,
max_track_length: int,
width: int,
height: int,
):
"""
Read in JSON file and video file and extract bounds and create files for all the other data
"""
types = []
for type in range(... | 5,321,775 |
def f_test(df, ann):
"""Pre-select features without difference between types of dataset
Parameters
----------
df : pandas.DataFrame
A pandas DataFrame whose rows represent samples
and columns represent features.
ann : pandas.DataFrame
DataFrame with annotation of samples. Th... | 5,321,776 |
def _is_group(cli_obj: Union[Group, Command, MultiCommand]) -> bool:
"""Detects if cli obj is a Group or not"""
return isinstance(cli_obj, Group) and hasattr(cli_obj, "commands") | 5,321,777 |
def playGame(wordList):
"""
Allow the user to play an arbitrary number of hands.
1) Asks the user to input 'n' or 'r' or 'e'.
* If the user inputs 'e', immediately exit the game.
* If the user inputs anything that's not 'n', 'r', or 'e', keep asking them again.
2) Asks the user to inp... | 5,321,778 |
def _get_input_json(input_path):
"""
A really basic helper function to dump the JSON data. This is probably a
leftover from when I was iterating on different reduce() functions.
"""
# Read in the input file.
input_file = codecs.open(input_path, encoding="utf-8", mode="r")
json_data = json.lo... | 5,321,779 |
def raw_data_keys(d):
"""
Validate raw dictionary, no top-level keys with leading underscores,
except for _module, and no keys with double underscores anywhere
"""
keys_all = get_keys_for_dict(d)
errors = []
try:
no_double_underscores(keys_all)
except ValueError as e:
er... | 5,321,780 |
def urn_from_member_name(member, base_urn):
"""Returns a URN object from a zip file's member name."""
member = utils.SmartUnicode(member)
# Remove %xx escapes.
member = re.sub(
"%(..)", lambda x: chr(int("0x" + x.group(1), 0)),
member)
# This is an absolute URN.
if urllib.parse... | 5,321,781 |
def dataset():
"""Proof-of-Concept command for dataset operations using new metadata.""" | 5,321,782 |
def create_data_set():
"""
创建数据集
:return:
"""
data_set_ = [
[1, 1, 'yes'],
[1, 1, 'yes'],
[1, 0, 'no'],
[0, 1, 'no'],
[0, 1, 'no']
]
labels_ = ['no surfacing', 'flippers']
return np.array(data_set_), np.array(labels_) | 5,321,783 |
def get_text(xml: bytes, context: Dict[str, Any]) -> TablesList:
"""Xml as a string to a list of cell strings.
:param xml: an xml bytes object which might contain text
:param context: dictionary of document attributes generated in get_docx_text
:returns: A 4-deep nested list of strings.
Sorts the ... | 5,321,784 |
def test_landusage_to_waterarea_2():
"""Parks converted to water moved from landusages to waterareas"""
assert_cached_way(11001)
assert_cached_way(12001)
assert_cached_way(13001)
assert not query_row(db_conf, 'osm_landusages', 11001)
assert not query_row(db_conf, 'osm_landusages', -12001)
a... | 5,321,785 |
def day(query: int, field_name: str, object: Any) -> bool:
"""
Checks if value of object is equal to query
"""
return query == getattr(object, field_name).day | 5,321,786 |
def test_gh_6843():
"""check if x0 is being used by tracing iterates"""
A, b = get_sample_problem()
# Random x0 to feed minres
np.random.seed(12345)
x0 = np.random.rand(10)
trace = []
def trace_iterates(xk):
trace.append(xk)
minres(A, b, x0=x0, callback=trace_iterates)
trace... | 5,321,787 |
def glob_read(path, read_fun, stop_i=None, show_bar=False):
"""read all files in path by glob
Args:
path (str): absolute path
read_fun ([type]): different read function based on file type
stop_i (int, optional): stop read at file i. Defaults to None.
show_bar (bool, optional): ... | 5,321,788 |
def test_ap_hs20_min_bandwidth_home2(dev, apdev):
"""Hotspot 2.0 network selection with min bandwidth - special cases"""
check_eap_capa(dev[0], "MSCHAPV2")
bssid = apdev[0]['bssid']
params = hs20_ap_params()
hapd = hostapd.add_ap(apdev[0], params)
dev[0].hs20_enable()
dev[0].scan_for_bss(bs... | 5,321,789 |
def create_lmdb_for_reds():
"""Create lmdb files for REDS dataset.
Usage:
Before run this script, please run `merge_reds_train_val.py`.
We take two folders for example:
train_sharp
train_sharp_bicubic
Remember to modify opt configurations according to your settin... | 5,321,790 |
def argument(*name_or_flags, **kwargs):
"""Convenience function to properly format arguments to pass to the
subcommand decorator.
"""
return list(name_or_flags), kwargs | 5,321,791 |
def main(cfg):
"""Run the diagnostic."""
sns.set(**cfg.get('seaborn_settings', {}))
cfg = deepcopy(cfg)
cfg.setdefault('group_by_attribute', 'mlr_model_name')
cfg.setdefault('group_attribute_as_default_alias', True)
cfg.setdefault('legend_kwargs', {})
cfg.setdefault('map_plot_type', 'pcolorm... | 5,321,792 |
def conv_float2negexp(val):
"""Returns the least restrictive negative exponent of the power 10
that would achieve the floating point convergence criterium *val*.
"""
return -1 * int(math.floor(math.log(val, 10))) | 5,321,793 |
def pick_wm_class_2(tissue_class_files):
"""Returns the white matter tissue class file from the list of segmented tissue class files
Parameters
----------
tissue_class_files : list (string)
List of tissue class files
Returns
-------
file : string
Path to segment_seg_2.nii... | 5,321,794 |
def role_parse(role_path=None):
"""Parse a role.
Args:
role_path (str, optional): Path to role. Defaults to None.
Raises:
NotImplementedError: for now
"""
raise NotImplementedError("Roles parsing is not supported yet!") | 5,321,795 |
def collect_datasets(data_type, varnames, list_of_ds, labels, **kwargs):
"""
Concatonate several different xarray datasets across a new
"collection" dimension, which can be accessed with the specified
labels. Stores them in an xarray dataset which can be passed to
the ldcpy plot functions (Call thi... | 5,321,796 |
def split_tiles(image, tile_size):
"""Splits the image into tiles of size `tile_size`."""
# The copy is necessary due to the use of the memory layout.
if image.ndim == 2:
image = image[..., None]
image = np.array(image)
image = make_divisible(image, tile_size).copy()
height = width = tile_size
nrows, ... | 5,321,797 |
def load_weights_params_from_file(exe, prog, weights, place):
"""
The params of the training process is stored in the file named weights.
However, the network of the training and test process is slightly different due to the layer
named "pred" was fc in trainng but convolution in test. When loading wei... | 5,321,798 |
def test_local_no_files(test_dir, args_no_files):
"""Test get_html_files when no files are found."""
path_ = test_dir / "test_inputs" / "test_inputs_crawler" / "get_cazy_pages"
file_io.make_output_directory(path_, True, False)
with pytest.raises(SystemExit) as pytest_wrapped_e:
parse_local_pa... | 5,321,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.