content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def broad_sel_egress_queue(
data # type: "XDR Data"
):
"""Broadcom Selected Egress Queue - Type: Flow, Enterprise: 4413, Format: 1"""
datagram = {}
datagram["Queue"] = packet_direction(data.unpack_uint())
data.done() # Verify all data unpacked
return datagram | 5,289,500 |
async def test_login_success(aresponses, login_success_response):
"""Test a successful login and API object creation."""
aresponses.add(
"mysecurity.eufylife.com",
"/api/v1/passport/login",
"post",
aresponses.Response(text=json.dumps(login_success_response), status=200),
)
... | 5,289,501 |
def _earlygetopt(aliases, args):
"""Return list of values for an option (or aliases).
The values are listed in the order they appear in args.
The options and values are removed from args.
>>> args = ['x', '--cwd', 'foo', 'y']
>>> _earlygetopt(['--cwd'], args), args
(['foo'], ['x', 'y'])
>... | 5,289,502 |
def cluster_leftovers(times, waveforms):
"""Reassign all datapoints labeled -1"""
time_joined_waveforms = np.hstack([
waveforms,
(times - np.mean(times))[:, None] / 3600.0
])
time_based_umap = umap.UMAP(n_components=3, n_neighbors=10, min_dist=0.01).fit_transform(
time_joined_wa... | 5,289,503 |
def cue_iti_responding(timecode, eventcode, code_on, code_off, counted_behavior):
"""
:param timecode: list of time codes from operant conditioning file
:param eventcode: list of event codes from operant conditioning file
:param code_on: event code for the beginning of a cue
:param code_off: event c... | 5,289,504 |
def rmse(a, b):
"""Root Mean Square Error"""
return np.sqrt(np.mean(np.sum((a - b)**2, axis=1))) | 5,289,505 |
def write_to_latex(arr, title, m, function_type, region, save_outputs):
"""
Write outputs to latex.
Parameters
----------
arr: array
Convert arr to a Pandas dataframe and then write to latex.
title : string
Name of saved outputs.
m : integer
Number of... | 5,289,506 |
def ensure_shape(tensor, shape):
"""Raises a ValueError if the input tensor doesn't have the expected shape."""
real_shape = tensor.get_shape().as_list()
failing = False
if len(real_shape) != len(shape):
failing = True
if not failing:
for dim, si in enumerate(shape):
if si != -1 and si != real_s... | 5,289,507 |
def ais6tobitvecSLOW(str6):
"""Convert an ITU AIS 6 bit string into a bit vector. Each character
represents 6 bits. This is for text sent within ais messages
If the original BitVector had ((len(bitvector) % 6 > 0),
then there will be pad bits in the str6. This function has no way
to know how man... | 5,289,508 |
def test_model_backup_loading(shapes_image_size, shapes_sample_config, shapes_temp_dir):
"""Test the model checkpoint recovering
"""
config = read_config(shapes_sample_config)
label_ids = [x['id'] for x in config['labels'] if x['is_evaluate']]
cnn = FeatureDetectionNetwork("test", image_size=shapes... | 5,289,509 |
def get_footprint(
site: str,
domain: str,
height: str,
model: str = None,
start_date: Timestamp = None,
end_date: Timestamp = None,
species: str = None,
) -> FootprintData:
"""
Get footprints from one site.
Args:
site: The name of the site given in the footprints. This ... | 5,289,510 |
def test_fbeta_score_binary_labels():
"""Test of `fbeta_score` with binary labels."""
y_pred = np.array([1, 1, 1, 0, 1])
y_true = np.array([0, 1, 1, 1, 1])
assert fbeta_score(y_pred, y_true, 0.5) == 0.75 | 5,289,511 |
def _daemon_thread(*a, **kw):
"""
Create a `threading.Thread`, but always set ``daemon``.
"""
thread = Thread(*a, **kw)
thread.daemon = True
return thread | 5,289,512 |
def test_feature_view_inference_respects_entity_value_type(simple_dataset_1):
"""
Tests that feature view inference still respects an entity's value type.
"""
# TODO(felixwang9817): Remove this test once entity value_type is removed.
with prep_file_source(df=simple_dataset_1, timestamp_field="ts_1")... | 5,289,513 |
def fib(n): # write Fibonacci series up to n
"""Print a Fibonacci series up to n."""
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
print() | 5,289,514 |
def autolink(text, trim_url_limit=None, nofollow=False):
"""
Converts any URLs in text into clickable links. Works on http://, https:// and
www. links. Links can have trailing punctuation (periods, commas, close-parens)
and leading punctuation (opening parens) and it'll still do the right thing.
If... | 5,289,515 |
def chunks(l, n):
"""
https://stackoverflow.com/a/1751478
"""
n = max(1, n)
return (l[i : i + n] for i in range(0, len(l), n)) | 5,289,516 |
def update_status(syn: Synapse, main_queue: str, internal_queue: str,
config: dict):
"""If internal submission is invalid, then make update main leaderboard
with site_submission_status to INVALID
Args:
syn: Synapse connection
"""
main_sub_viewid = config[int(main_queue)]['... | 5,289,517 |
def make_0235(pc):
"""EXP/JOBEXP"""
result = pack_int(0) #EXP(x0.1%)
result += pack_int(0) #JobEXP(x0.1%)
result += pack_byte(0) #WarRecodePoint
result += pack_int(0) #ecoin
return result | 5,289,518 |
def np_hsv_value_histogram(v):
"""
Create Matplotlib histogram of value values for an HSV image and return the histogram as a NumPy array image.
Args:
v: Value values as a 1-dimensional float NumPy array
Returns:
Matplotlib histogram of saturation values converted to a NumPy array image.
"""
title... | 5,289,519 |
def test_invalid_pay_system(session, public_user_mock):
"""Test invalid data."""
from pay_api.factory.payment_system_factory import PaymentSystemFactory # noqa I001; errors out the test case
from pay_api.exceptions import BusinessException
with pytest.raises(BusinessException) as excinfo:
Pay... | 5,289,520 |
def get_stock(stock: str, beg: datetime, fin: datetime):
"""gets stock data and writes .csv file"""
new_beg = datetime(beg.year, beg.month, beg.day - 1)
df = yf.download(stock, start=new_beg, end=fin)
return df | 5,289,521 |
def is_case_special_activated(b, location, k):
"""Teste si le toit n'est pas affiché en raison de la position de Knil"""
x, y = location
x0, y0 = getOrigin(b)
kx, ky = Knil.getPos(k)
knil_case = getCase(b, kx+x0, ky+y0)
special_attrib = bool("special_case" in knil_case.keys())
case = getCase(b, x, y)
if "spec... | 5,289,522 |
def plugin_zip(p):
"""Maps columns to values for each row in a plugins sql_response and returns a list of dicts
Parameters
----------
p : :class:`taniumpy.object_types.plugin.Plugin`
* plugin object
Returns
-------
dict
* the columns and result_rows of the sql_response in P... | 5,289,523 |
def write_results(response, results_file=RESULTS_FILE):
"""Write tracking API results for labels into /tracking/results.csv."""
logging.info("Entering write_results() function")
with open(results_file, "w", newline="") as file:
csv_writer = writer(file)
headers = response["results"][0].keys... | 5,289,524 |
def species_list():
""" """
spc_081 = (
SpeciesFactory(
spc="081", spc_nmco="lake trout", spc_nmsc="Salvelinus namaycush"
),
)
spc_091 = (
SpeciesFactory(
spc="091", spc_nmco="lake whitefish", spc_nmsc="Coregonus clupeaformis"
),
)
spc_093... | 5,289,525 |
def enable_dump_permission(sdk_path, device_id, dest_dir, package_name):
"""Enable the DUMP permission on the specified and installed Android
app.
"""
print 'Starting dump permission grant'
perm_command = [os.path.join(sdk_path, 'platform-tools', 'adb'),
'-s', device_id,
... | 5,289,526 |
def get_annotated_sentences(sentences: pd.DataFrame) -> Tuple[
List[int],
List[Tuple[LexicalTreeNode, List[IGTag]]],
List[str]
]:
"""
:param sentences: DataFrame of sentences with sentence type (r/c) - output of get_sentence_type
:return: Tuple with tagged tokens and used layers
"""
tre... | 5,289,527 |
def ping(host):
"""
Returns True if host responds to a ping request
"""
# Ping parameters as function of OS
ping_num_param = "-n" if platform.system().lower() == "windows" else "-c"
# Ping
return subprocess.run(['ping', ping_num_param, '1', host], stdout=subprocess.DEVNULL, stderr=subproce... | 5,289,528 |
def get_content_message_handler(
callback: Callable[[Update, CallbackContext], Any]
) -> MessageHandler:
"""
Creates a universal message handler, that catches all messages, that should be considered as diary content.
:param callback: Function to be ran when such message is caught
:return: `MessageH... | 5,289,529 |
def get_string_from_ascii(input):
"""
This function is reversed engineered and translated to python
based on the CoderUtils class in the ELRO Android app
:param input: A hex string
:return: A string
"""
try:
if len(input) != 32:
return ''
byt = bytearray.fromhex... | 5,289,530 |
def test_ControlFlowGraph_unequal_graph_names_are_equal():
"""Test that graph names are not used in comparison."""
# Graph 1: A --> B
g1 = control_flow_graph.ControlFlowGraph(name="foo")
g1.add_node(0, name="A", entry=True)
g1.add_node(1, name="B", exit=True)
g1.add_edge(0, 1)
# Graph 2: A --> B
g2 = c... | 5,289,531 |
def admin_new_prompt():
"""
get: resets prompt
"""
if session.get('admin') is True:
random_generator()
flash('New random prompt generated')
return redirect(url_for('.admin'))
abort(404) | 5,289,532 |
def split_multiline(value):
"""Special behaviour when we have a multi line options"""
value = [element for element in
(line.strip() for line in value.split('\n'))
if element]
return value | 5,289,533 |
def get_price_change_rate(order_book_ids, start_date=None, end_date=None, expect_df=False, market="cn"):
"""获取价格变化信息
:param order_book_ids: 股票列表
:param start_date: 开始日期: 如'2013-01-04'
:param end_date: 结束日期: 如'2014-01-04';在 start_date 和 end_date 都不指定的情况下,默认为最近3个月
:param expect_df: 返回 DataFrame (Defa... | 5,289,534 |
def positive_x_gradient(x, constants, variables):
""" Returns gradients of the positive x constraints.
:param np.ndarray x: Parameters of updated Voce-Chaboche model.
:param dict constants: Defines the constants for the constraint.
:param dict variables: Defines constraint values that depend on x.
... | 5,289,535 |
def pretty(states: List[str]) -> None:
"""Pretty print of one or more 8-puzzle boards
Parameters
----------
states : List[str]
List of linear representations of 8-puzzle boards
"""
for state in states:
print(state[:3])
print(state[3:6])
print(state[6:])
p... | 5,289,536 |
def create_borrow_time_list(config):
"""create a list of borrow time limits"""
limit_list = []
current = 0
for i in range(MAX_LEVEL + 1):
current = max(current, config['core']['borrow time limit'].get(str(i), 0))
limit_list.append(current)
config['core']['borrow time limit'] = limit_... | 5,289,537 |
def _to_pdb_ccd_cif_dict(component):
"""Export component to the PDB CCD CIF file.
Args:
component (pdbeccdutils.core.Component): Component to be
exported.
Returns:
(dict of str: str)): dictionary representation of the component
to be serialized as a cif file.
""... | 5,289,538 |
def create_random_individual(cities, solutions):
"""Create random individual from cities list."""
cities = copy(cities)
random.shuffle(cities, random.random)
new_individu = Individual(cities)
while(new_individu in solutions):
random.shuffle(cities, random.random)
new_individu ... | 5,289,539 |
def git_src_dir(projects_yaml, project):
"""
Return the directory where the specified project's source is located.
"""
parent_dir = '/mnt/openstack-git'
projects = _git_yaml_load(projects_yaml)
if 'directory' in projects.keys():
parent_dir = projects['directory']
for p in projects... | 5,289,540 |
def yield_stdev(
model: pyhf.pdf.Model,
parameters: np.ndarray,
uncertainty: np.ndarray,
corr_mat: np.ndarray,
) -> Tuple[List[List[float]], List[float]]:
"""Calculates symmetrized yield standard deviation of a model, per bin and channel.
Returns both the uncertainties per bin (in a list of cha... | 5,289,541 |
def limit_carbon(comp, C_limit=25):
"""True if the compound exceeds the carbon atom limit, otherwise False."""
regex = re.compile('[A-Z]{1}[a-z]*[0-9]*')
try:
formula = comp['Formula']
except KeyError:
try:
comp_id = comp['_id']
except KeyError:
comp_id = ... | 5,289,542 |
def main(file_name, port):
"""HTTP Backend API for Grafana Annotations."""
global annotation_db
annotation_db = Annotation(file_name)
annotation_db.dump()
app.run(host = '0.0.0.0', port = port, debug = True, threaded=True) | 5,289,543 |
async def add_premis_event(
base_path, workspace_path, event_type, event_datetime,
event_detail, event_outcome, event_target=None,
event_outcome_detail=None, **kwargs):
"""
Add a PREMIS event using dpres-siptools tool 'premis-event'
"""
args = [
"premis-event", "--base_pa... | 5,289,544 |
def xmlprettify(elem: lxml.html.HtmlElement, chars: str=' ', _level: int=1):
"""
prettify the given element-tree w/ new indentations
:param elem: element being prettified
:param chars: characters used for single indent
:param _level: internal variable used to track indent level
"""
star... | 5,289,545 |
def create_vocab_dictionaries(args):
"""Takes as input the path for an annotated freebase data file, and returns
dictionaries word2ix, ix2word w.r.t the questions found in the file"""
sbj_mid, predicate, obj_mid, question = DataCreator.get_spo_question(args.path_load_sq,
... | 5,289,546 |
def send_get_request(url, params=None):
"""
Return HTTP GET decoded JSON response as dict.
"""
response = request_get(url, params=params)
if response.status_code != HTTP_200_OK:
exception(response)
return ''
return response.json() | 5,289,547 |
def restore_cursor() -> None:
"""Restore cursor position saved by `save_cursor()`"""
# _tput(['rc'])
_stdout.write("\x1b[u") | 5,289,548 |
def MakeListComprehensionFunction (name, nsets):
"""Returns a function applicable to exactly <nsets> sets.
The returned function has the signature
F(set0, set1, ..., set<nsets>)
and returns a list of all element combinations as tuples.
A set may be any iterable object.
"""
if nsets <... | 5,289,549 |
def local_t_star(gdir, *, ref_df=None, tstar=None, bias=None,
clip_mu_star=None, min_mu_star=None, max_mu_star=None):
"""Compute the local t* and associated glacier-wide mu*.
If ``tstar`` and ``bias`` are not provided, they will be interpolated from
the reference t* list (``ref_df``).
... | 5,289,550 |
def transform_trace_log_to_event_log(log, include_case_attributes=True, case_attribute_prefix='case:'):
"""
Converts the trace log to an event log
Parameters
----------
log: :class:`pm4py.log.log.TraceLog`
A trace Log
includes_case_attributes:
Default is True
case_attribute_... | 5,289,551 |
def avg_pool(x, inds):
"""
Pools features with the maximum values.
:param x: [n1, d] features matrix
:param inds: [X, X, ..., X, max_num] pooling indices
:return: [X, X, ..., X, d] pooled features matrix
"""
# Add a last row with minimum features for shadow pools
x = torch.cat(... | 5,289,552 |
def validate_ip_address(ip_address):
"""Return True if the provided IP address
is a valid IPv4 or IPv6 address"""
return validate_ipv4_address(ip_address) or \
validate_ipv6_address(ip_address) | 5,289,553 |
def lambda_remove_resource_policy(**kwargs):
"""Remove lambda resource policy."""
response = aws_lambda.remove_permission(**kwargs)
log.info("lambda_remove_resource_policy: {}".format(response))
return response | 5,289,554 |
def gen_f_array(a,b,n): ### The tests are failing due to the extra indent space in the line below this one
"""gen_f_array(a, b, n=1000)
Generate a discrete approximation of y = x^2, including its
domain and range, stored as a pair of numpy arrays.
Args:
a (float) : Lower boun... | 5,289,555 |
def getDiskImages(db: ArtifactDB, limit: int = 0) -> Iterator[Artifact]:
"""Returns a generator of disk images (type = disk image).
Limit specifies the maximum number of results to return.
"""
return _getByType(db, 'disk image', limit) | 5,289,556 |
async def add_unconfirmed_transaction(transaction: Transaction):
""" broadcasts transactions to all nodes """
sender_signature = transaction.sender_signature
pub_sender_key = transaction.sender_public_send_key
receiver = transaction.receiver
amount = transaction.amount
new_transaction = bl... | 5,289,557 |
def new_jobcards(args):
"""command for drawing shortcut"""
core.jobcards(*args) | 5,289,558 |
async def test_manifest_get(opp, websocket_client):
"""Test getting a manifest."""
hue = await async_get_integration(opp, "hue")
await websocket_client.send_json(
{"id": 6, "type": "manifest/get", "integration": "hue"}
)
msg = await websocket_client.receive_json()
assert msg["id"] == 6... | 5,289,559 |
def delete_main_and_details_dashboards(existing_dashboards):
"""Delete specified dashboards
:param existing_dashboards: the dashboards to delete
:type existing_dashboards: list
"""
print('You have chosen to delete the existing dashboards. Deleting the dashboards now ...')
delete_command = 'aws ... | 5,289,560 |
def _add_response_chain ( chain , *args ) :
"""Specific axction to ROOT.TChain
"""
import ostap.trees.trees
files = chain.files()
cname = chain.GetName()
status = None
verbose = True and 1 < len ( files )
from ostap.utils.progress_bar import progress_bar
for f... | 5,289,561 |
def mod_launch_rpc_thread(mode, mod, args, outputs, results, need_retry, retry, tuning=False):
"""internal RPC thread, should be called by mod_launch_rpc_multithread."""
remoteevb = '0'
host = None
port = None
env_dic = os.environ
if env_dic.get('RPC_HOST') and env_dic.get('RPC_PORT'):
h... | 5,289,562 |
def center_align_x(shapes):
"""
Returns a constraint setting the shapes' centers' x-coordinates equal.
"""
s = FreshSymbol(REAL)
return And(Equals(shape.center.x, s) for shape in shapes) | 5,289,563 |
def test_ps_s3_topic_on_master():
""" test s3 topics set/get/delete on master """
zones, _ = init_env(require_ps=False)
realm = get_realm()
zonegroup = realm.master_zonegroup()
bucket_name = gen_bucket_name()
topic_name = bucket_name + TOPIC_SUFFIX
# clean all topics
delete_all_s3_topi... | 5,289,564 |
def locate_qr_code_using_slider(image, scanner):
"""Try sliding a window over the image to search for the QR code."""
for slider in window_slider(image):
cropped = image.crop(slider)
results = scanner.scan(cropped)
if results:
box = bbox(results)
# Box is relative... | 5,289,565 |
def load(path):
"""
Imports a previously saved session from disk
:type path: str
:param path: path to the previously saved session
"""
# Load parameters and paths from a JSON file
for name in ['parameters', 'paths']:
fullfile = os.path.join(_full(path), f"seisflows_{name}.json")
... | 5,289,566 |
def ParseRegionalFlags(args, resources, message=None):
"""Make Frontend suitable for RegionalLister argument namespace.
Generated client-side filter is stored to args.filter.
Args:
args: The argument namespace of RegionalLister.
resources: resources.Registry, The resource registry
message: The respo... | 5,289,567 |
def GetArgs():
"""
Supports the command-line arguments listed below.
"""
parser = argparse.ArgumentParser(description='A utility to perform various conversions for the ZeroOne project')
parser.add_argument('-i', '--input', required=True, action='store', help='Specify the name of the input file')
... | 5,289,568 |
def __virtual__():
"""
Only load if boto libraries exist.
"""
has_boto_reqs = salt.utils.versions.check_boto_reqs()
if has_boto_reqs is True:
__utils__["boto3.assign_funcs"](__name__, "sns")
return has_boto_reqs | 5,289,569 |
def test_sum_prod_utility():
"""Test the summation and product utility."""
v = Vec('v')
vecs = [v[i] for i in range(3)]
v0, v1, v2 = vecs
# The proxy object cannot be directly compared.
assert parse_terms(sum_(vecs)) == parse_terms(v0 + v1 + v2)
assert parse_terms(prod_(vecs)) == parse_ter... | 5,289,570 |
def GetRegionFromZone(zone_or_region):
"""Returns the region a zone is in (or "zone_or_region" if it's a region)."""
if IsRegion(zone_or_region):
return zone_or_region
return zone_or_region[:-1] | 5,289,571 |
def plot_progress(param_str=None, log_filen=log_file, open_spectrum=True):
"""
Plot progress during serch, search_range, and search_grid
:param param_str: [None] parameter to search for
:param log_filen: ['backups/conuss_log.txt'] log file name
:param open_spectrum: [True] open a pdf file of spectr... | 5,289,572 |
def unhtmlify(html):
"""
Remove html-tags and unescape encoded html-entities.
:param html: Evil-string containing html
:return:
"""
return unescape(re.sub(r'<.*?>', '', html)) | 5,289,573 |
def CalculatePath3(mol):
"""
#################################################################
Calculation of the counts of path length 3 for a molecule
#################################################################
"""
return _CalculatePathN(mol, 3) | 5,289,574 |
def _preferred_string(value1, value2): # pylint:disable=too-many-return-statements
"""
Retrieves preferred title from both values.
:param value1:
:type value1: str
:param value2:
:type value2: str
:return: The preferred title
:rtype: str
"""
if value1 == value2:
return v... | 5,289,575 |
def load_nets(name: str, in_shape: List[int], bias=False, **kwargs) -> torch.nn.Module:
"""
Creates an instance of a network architecture.
:param name: name of the model of which an instance is to be created.
:param in_shape: shape of the inputs the model expects (n x c x h x w).
:param bias: whethe... | 5,289,576 |
def timestamp_to_epoch(timestamp: str) -> int:
"""Takes a `timestamp` str and attempts to convert it to an epoch
value using the list of known time stamp formats.
:param timestamp: str
:return: int
"""
for ts_fmt in KNOWN_TIMESTAMP_FORMATS:
try:
return pendulum.from_format(... | 5,289,577 |
def get_labels_from_responsibility_string(responsibility_string, include_none=False, warn_on_legacy_responsibilities=True):
"""
:param responsibility_string:
:param include_none: If 'none' should be included in the returned list when no other responsibilities are present
:return:
"""
if respons... | 5,289,578 |
def setter_func():
""" The MAIN function.... """
st.sidebar.header("Select Input Mode")
selected_mode = st.sidebar.selectbox('Modes', modes)
st.sidebar.header("Select number of words you want to use")
selected_word_count = st.sidebar.selectbox(
"No of words", range(10, 1000, 10))
typ =... | 5,289,579 |
def get_saved_session(**kwargs):
"""Gets a SessionState object for the current session.
Creates a new object if necessary.
Parameters
----------
**kwargs : any
Default values you want to add to the session state, if we're creating a
new one.
Example
-------
>>> session... | 5,289,580 |
def frame_center_satspots(array, xy, subim_size=19, sigfactor=6, shift=False,
debug=False):
""" Finds the center of a frame with waffle/satellite spots (e.g. for
VLT/SPHERE). The method used to determine the center is by centroiding the
4 spots via a 2d Gaussian fit and finding t... | 5,289,581 |
def prev_surname(prev_surname_val: str, **kwargs) -> ValidatedRecord:
"""Coerce and validate previous surname.
Validation rules: Must contain only uppercase alphabetic characters and
space, apostrophe or hyphen. Max length 35.
Args:
prev_surname_val (str): Previous surname to validate.
Re... | 5,289,582 |
def class_in_endpoint(class_, entrypoint):
"""Check if a given class is in the EntryPoint object as a class."""
regex = r'(vocab:)?(.*)EntryPoint/(.*/)?' + re.escape(class_["title"]) + r'$'
# Check supportedProperty for the EntryPoint
try:
supportedProperty = entrypoint["supportedProperty"]
... | 5,289,583 |
def compute_mean_median(all_methods_df):
"""
Computes the mean values and the median values for each column of the Pandas.DataFrame grouped by the methods.
Parameters
----------
all_methods_df : Pandas.DataFrame
Returns
-------
list
- means: Pandas.DataFrame containing the ... | 5,289,584 |
def get_circumsphere(S):
"""
Computes the circumsphere of a set of points
Parameters
----------
S : (M, N) ndarray, where 1 <= M <= N + 1
The input points
Returns
-------
C, r2 : ((2) ndarray, float)
The center and the squared radius of the circumsphere
"""
U = ... | 5,289,585 |
def random_mac(separator='', uppercase=False, oui=''):
"""return random mac address. OUI should not contain separators"""
if len(oui) == 6 and is_hex(oui):
digits = textwrap.wrap(oui, 2)
digits += [format(randrange(256), '02x') for _ in range(3)]
else:
digits = [format(randrange(256)... | 5,289,586 |
def unmold_boxes_x(boxes, class_ids, masks, image_shape, window, scores=None):
"""Reformats the detections of one image from the format of the neural
network output to a format suitable for use in the rest of the
application.
detections: [N, (y1, x1, y2, x2, class_id, score)]
masks: [N, height, wid... | 5,289,587 |
def iter_nearest_neighbours(umis, substr_idx):
"""
Use substring dict to get (approximately) all the nearest neighbours to
each in a set of UMIs.
"""
for u in umis:
neighbours = set()
for idx, substr_map in substr_idx.items():
u_sub = u[slice(*idx)]
neighbours... | 5,289,588 |
def get_volumes_in_pool_recycle_bin(session, pool_id, start=None, limit=None,
return_type=None, **kwargs):
"""
Retrieves a list of volumes in the pool's recycle bin.
:type session: zadarapy.session.Session
:param session: A valid zadarapy.session.Session object. Req... | 5,289,589 |
def max_change(model, max_param_change=2.0, max_change_scale=1.0, scale=1.0):
"""Untested implementation of max_param_change in Kaldi"""
scale_factors = []
num_components_updated = 0
for i, p in enumerate(model.parameters()):
if i == 0:
device = p.device
max_param_change ... | 5,289,590 |
def test_interpolator():
"""Test that interpolate method works as true projectors."""
random = np.random.default_rng(seed=42)
nu_train = np.linspace(1, 10, num=101)
physical_points = np.linspace(0, 1, 1001)
training = np.array([BesselJ(nn, physical_points) for nn in nu_train])
RB = arby.reduc... | 5,289,591 |
def test_build_has_clnsig(
adapter,
case_obj,
):
"""Test building query to retrieve all variants with ClinVar tag"""
case_id = case_obj["_id"]
query = {"clinvar_tag": True}
mongo_query = adapter.build_query(case_id, query=query)
assert {"clnsig": {"$exists": True}} in mongo_query["$and"]
... | 5,289,592 |
def get_cosinebased_yaw_pitch(input_: torch.Tensor) -> torch.Tensor:
"""
Returns a tensor with two columns being yaw and pitch respectively. For yaw, it uses cos(yaw)'s value along with
sin(yaw)'s sign.
Args:
input_: 1st column is sin(yaw), 2nd Column is cos(yaw), 3rd Column is sin(pitch)
""... | 5,289,593 |
def test_interpolation():
"""Test setting image interpolation mode."""
shapes = [(40, 20), (20, 10), (10, 5)]
np.random.seed(0)
data = [np.random.random(s) for s in shapes]
layer = Image(data, multiscale=True)
assert layer.interpolation == 'nearest'
layer = Image(data, multiscale=True, inte... | 5,289,594 |
def generate_episode_statistics(trackers: Iterable['Tracker']
) -> AgentStatisticsMap:
"""Generate episode statistics from set of trackers """
statistics = combine_statistics([t.get_episode() for t in trackers])
return statistics | 5,289,595 |
def main():
"""
"""
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("INPUT", type=argparse.FileType('r'),
help="distribution file")
parser.add_argument("-c", dest="cutoff", type=int, default=150,
help="cutoff value")... | 5,289,596 |
def save_debug_image( name, image, out_debug_image_dict ):
"""
If output_debug_image_dict isn't None, save the
given image in the dict as a compressed array.
"""
if out_debug_image_dict is None:
return
if hasattr(image, 'axistags'):
axistags=image.axistags
else:
axis... | 5,289,597 |
def GaussElimination(MATRIX,B):
""" Applies Gauss Elimination Algorithm to MATRIX in order to solve a linear system MATRIX.X = B.
MATRIX is transformed to row echelon form:
|1 * * * * * |
|0 1 * * * * |
|0 0 1 * * * |
|0 0 0 1 * * |
|0 0 0 0 1 * |
|0 0 ... | 5,289,598 |
def main():
"""
Main Function of the program where we construct objects of tictactoe_game class and player class. We also plot the result in this function.
"""
player1 = Player()
player2 = Player()
player3 = Player()
player1.qlagent()
player2.human()
player1 = player1.kind
player2 = player2.kind
pickle_in = ... | 5,289,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.